A simple addition, subtraction, multiplication, and Division calculator is used to copy a struts1demo modification: struts1calc
Solution 1: struts1calc create actionform:
Calcform extends actionform, num1 num2, generate getter setter;
Create four actions. On the page, use JavaScript to control the submission to different action beans.
Addaction:
public class AddAction extends Action {@Overridepublic ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {CalcForm cf = (CalcForm) form;int result = cf.getNum1()+cf.getNum2();request.setAttribute("result", result);return mapping.findForward("success");}}
The other three are omitted ..
Servlet in Wen. xml
Add
<Load-on-startup> 1 </load-on-startup>
Configuration inside the struts-config.xml:
<!-- Form --><form-beans><form-bean name="calcForm" type="com.demo.form.CalcForm"></form-bean></form-beans><!-- Action --><action-mappings><action name="calcForm" path="/add" type="com.demo.action.AddAction"scope="request"><forward name="success" path="/result.jsp"></forward><forward name="input" path="/calc.jsp"></forward></action></action-mappings>
The other three configurations are omitted...
Add CLAC. jsp
</Head> <SCRIPT type = "text/JavaScript"> function calc (c) {document. getelementbyid ("form "). action = C + ". do "; document. getelementbyid ("form "). submit () ;}</SCRIPT> <body> <Form ID = "form" Action = "#" method = "Post"> Number 1: <input name = "num1"> <br/> Number 2: <input name = "num2"> <br/> <input type = "button" value = "add" onclick = "calc ('add ') "> <input type =" button "value =" minus "onclick =" calc ('sub ') "> <input type =" button "value =" multiply by "onclick =" calc ('mul ') "> <input type =" button "value =" except "onclick =" calc ('div ') "> </form> </body>
Add result. jsp
Number 1: $ {requestscope. calcform. num1}
<Br/> Number Two: $ {requestscope. calcform. num2}
<Br/> structure: $ {requestscope. Result}
Deployment access:
Http: // localhost: 8080/struts1calc/Calc. jsp
Source code download
Http://pan.baidu.com/s/1kTDRVi3
Solution 2:
Add a hidden form field to indicate the operation type. In the action bean, perform different processing based on different operation types.
Add the following in the Calc. jsp form:
<Input id ="Province"Name ="Province"Type ="Hidden"Value ="Province">
Modify the script:
<script type="text/javascript"> function calc(c){ /* document.getElementById("form").action=c+".do"; */ document.getElementById("oper").value=c; document.getElementById("form").submit(); } </script>
Change the form action to action = "Calc. Do"
Modify the path of the calcform in the <action-mappings> In the struts-config.xml to the calc Configuration:
<action name="calcForm" path="/calc" type="com.demo.action.CalcAction" scope="request"><forward name="success" path="/result.jsp"></forward><forward name="input" path="/calc.jsp"></forward></action>
Add in calcform
Private string delimiter;
And getter and setter methods;
Modify calcaction:
public class CalcAction extends Action {@Overridepublic ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {CalcForm cf = (CalcForm) form;int result = 0;if("add".equals(cf.getOper())){result = cf.getNum1()+cf.getNum2();}else if("div".equals(cf.getOper())){result = cf.getNum1()/cf.getNum2();}//....request.setAttribute("result", result);return mapping.findForward("success");}}
Deployment access:
Http: // localhost: 8080/struts1calc2/Calc. jsp test addition and division;
Source code: http://pan.baidu.com/s/1c0nbPsc
Use dispatchaction
The preceding two solutions are described as follows:
Solution 1 creates an action for each operation, which is easy to confuse when the system grows.
Solution 2 organizes related operations in an action and uses the operate parameter to differentiate different operations. However, it is easy to make the code of the execute method in the action too long and difficult to maintain.
To use dispatchaction to calculate a machine:
Copy struts1calc2 from the previous project and change it to struts1calcdispatchaction.
1. Create calcaction, inherited from dispatchaction
2. Create four methods in calcaction: add, subtract, multiply, and divide
Press ex and press Alt +/and select the parameter httpservletresponse... and change the method name to add, Div...
public ActionForward add(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {CalcForm cf = (CalcForm) form;int result = 0;result = cf.getNum1() + cf.getNum2();request.setAttribute("result", result);return mapping.findForward("success");}/*public ActionForward div … public ActionForward sun … public ActionForward mul … */
Configure calcaction in struts-config.xml
Parameter = "parameter" in action-Mapping"
<action name="calcForm" path="/calc" type="com.demo.action.CalcAction"scope="request" parameter="oper"><forward name="success" path="/result.jsp"></forward><forward name="input" path="/calc.jsp"></forward></action>
There must be a signature in parameter, and there must be a corresponding signature in Calc. jsp.
<Input id = "comment" name = "comment" type = "hidden" value = "comment">
3. Compile the Page code
Do not modify the page;
How dispatch works
The dispatchaction can automatically select a method with the same name in the action based on the input parameter value for execution.
Parameter is a bit similar to our struts2 method;
Deployment and running:
Http: // localhost: 8080/struts1calcdispatchaction1/Calc. jsp
Source code: http://pan.baidu.com/s/1bnnJOIV
Show friendly error messages
Struts provides an error reporting mechanism to provide user-friendly error messages.
The divisor is 0, not a number.
Create the property file applicationresources. properties under com. Demo. Resources.
Set the error message format by defining the errors. header and errors. footer attributes in the attribute file.
Modify the configuration file Struts-config
<message-resources parameter="com.demo.resources.ApplicationResources"></message-resources>
Modify the corresponding action Method
When the input is not a number or the divisor is zero, only Div division is performed here.
public ActionForward div(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {CalcForm cf = (CalcForm) form;ActionMessages errors = new ActionMessages();if (!this.isFloat(cf.getNum1())) {errors.add("error1",new ActionMessage("error.valudate.inputnumber"));}if (this.isZero(cf.getNum2())) {errors.add("error2", new ActionMessage("error.valudate.number"));}if (!errors.isEmpty()) {super.saveErrors(request, errors);return mapping.findForward("input");}int result = 0;result = cf.getNum1() / cf.getNum2();request.setAttribute("result", result);return mapping.findForward("success");}private boolean isZero(int num2) {return num2 == 0;}private boolean isFloat(int i) {if (i==0)return false;elsereturn true;}
Error message displayed on the page
<% @ Taglib prefix = "html" uri = "http://struts.apache.org/tags-html" %> first count: <input name = "num1"> <HTML: errors property = "error1"/> <br/> Number 2: <input name = "num2"> <HTML: errors property = "error2"/> <br/>
Deploy and run divisor input 0 test; http: // localhost: 8080/struts1calcdispatchaction1/Calc. jsp
Second Method of displaying friendly error messages in source code
Added to the global error message. The scope is request.
if (!this.isFloat(cf.getNum1())) {errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.valudate.inputnumber"));// errors.add("error1",new// ActionMessage("error.valudate.inputnumber"));}if (this.isZero(cf.getNum2())) {// errors.add("error2", new ActionMessage("error.valudate.number"));errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.valudate.number"));}
Use <HTML: errors/> In vlac. JAP to display all error messages;
When using dynamic form for simplified development and using struts framework for development, an actionform attribute must be created for the attributes submitted on each page.
Review the actionform attributes of the calculator
1. There are only two attributes. 2. If complicated services are processed, the attributes may be very large. 3. errors may be missed. 4. A large amount of "physical" code is filled
Use dynamic form to solve the problem
Create a form struts-config.xml as configured:
<form-beans><form-bean name="calcDynaForm" type="org.apache.struts.action.DynaActionForm"><form-property name="num1" type="java.lang.Integer" /><form-property name="num2" type="java.lang.Integer" /></form-bean></form-beans>
Same as using a normal form
<action name="calcDynaForm" parameter="oper" path="/calc"scope="request" type="com.demo.action.CalcAction"><forward name="success" path="/result.jsp"></forward><forward name="input" path="/calc.jsp"></forward></action>
Action Code
......
DynaactionformCf = (dynaactionform) form;
......
Result = (integer) Cf. Get ("num1")/(integer) Cf. Get ("num2 ");
......
Benefits of using an object as a form attribute to use dynamic actionform
Eliminating the need to write actionform classes
When the page submits data changes, you only need to modify the configuration in the struts-config.xml
Dynamic actionform Defects
The code in action is not so easy
When the business logic changes and the database adds or removes fields, the object class, dynamic actionform definition, and corresponding code in the action must be modified.
It is easy to miss something and introduce errors
Use object as form attribute
We already know:
Form data submitted on the page, which can be automatically filled in the actionform
Assume that the code of actionform is as follows:
Public class userform
Extends actionform {
Private user = new user ();
// Getter and setter
}
Assume that the page code is as follows:
<Input name = "user. uname"/>
Can the values of form fields be automatically filled in form?
Actionform code
Public class userform extends actionform {
Private user = new user ();
// Getter and setter
}
Struts-config.xml
<Form-bean name = "userform" type = "com. Aptech. JB. Web. Form. userform"/>
...
<Action name = "userform "...
Action Code
Userform myform = (userform) form;
// Execute Logon
User userwithuid = userbiz. login (myform. getuser ());
This avoids manual encoding. When adding or removing database fields, you do not need to modify the form and action code.