Sie sind auf Seite 1von 15

Struts & MVC

Servlet Servlet /
Servlet
Static page
Struts

HTTP Request
Example
„ Functionality: input and display staff info (first
name, last name, position)
„ Workflow
… If the staff info is new, return to home page
… If the staff info already exists in the db, error 1
… If the staff info conflicts with data in db, error 2

r 1
ro
er
Inp
ut
General steps to build web app
using Struts
„ JSP pages
„ Form Bean
„ Action
„ Workflow
taglib
„ Java libraries we can use to facilitate JSP
programming,
… custom tags, e.g. <html:form>
… custom actions

„ When compiling JSP, custom actions are


called to render the corresponding tags
JSP pages
Idata.jsp
Result.jsp
<html:form action="/inputdata"
method="post"> <% ArrayList<String> result =
<h1>Input Staff Info</h1> (ArrayList<String>)request.getAtt
ribute("result");
<table> for (int i = 0; i < result.size(); i+=3)
<tr><td>First Name</td> { %>
<td><html:text
property="firstName"/> <tr><td
</td></tr> width="250"><%=result.get(i)%>
…… </td>
<tr> <td><html:submit <td><%=result.get(i+1)%></td>
value="Submit"/></td> <td><%=result.get(i+2)%></td>
</tr> </tr>
</table>
<% } %>
</html:form>
Java class – form bean
InputForm.java:

public class InputForm extends ActionForm {


private String firstName;
private String lastName;
private String position;

// setter and getter for each variable


……
}
configure struts-config.xml
Form bean:

<form-beans>
<form-bean type="InputForm" name="form"/>
</form-beans>

name attribute: the name of this form bean instance


Identify actions
„ What actions we have?
… Input action: save the data in database
„ logic (action result)
… Success: if no such staff in the database
… Failure 1: this staff has already existed in the database

… Failure 2: input info conflicts with staff in the database

… Display action: exact the data from database


„ Always success
How to connect pages: flow
Struts-config.xml:
<action
path="/inputdata"
type="InputAction"
validate="false"
scope="request"
input="idata.jsp"
name="form">
<forward name="success" path="/pages/Welcome.jsp"/>
<forward name="exist" path="/pages/error1.jsp"/>
<forward name="conflict" path="/pages/error2.jsp"/>
</action>
Write action codes
public class InputAction extends Action {
public ActionForward execute(…) {
……
if (type == 0) return mapping.findForward("success");
else if (type == 1) return mapping.findForward("exist");
else return mapping.findForward("conflict");
}
}

public class DisplayAction extends Action {


public ActionForward execute(…) {
……
request.setAttribute("result", staff);
return mapping.findForward("success");
}
}
Version Issue
„ Struts 1.3
… ActionError is replaced by ActionMessage
„ In validate() in form bean class
Variance
Rethink of the scope of form bean

HTTP Request
<action
path="/inputdata"
type="InputAction"
validate="false"
scope="request"
input="idata.jsp“
……
</action> Bean is valid
for these JSP’s

Das könnte Ihnen auch gefallen