Struts2 (2), struts2 (advanced tutorial)
I. Action and MVC
Struts2 is a web application framework based on MVC. It divides an application into three components: model, view, and controller.
Model: contains the application business logic and business data, which is composed of Data encapsulation and business processing javaBean.
View: encapsulates the output form of the application, that is, the page, such as jsp and html.
Controller: It is responsible for receiving users' http requests, then calling the response method in the model to process the business, and then calling the response view for display.
The three work together to respond to client requests.
In struts2, the controller is divided into two parts:
1. Core Controller: The StrutsPrepareAndExecuteFilter configured in web. xml is used to filter all user requests and distribute different actions based on different requests.
2. Business Controller: namely, Action, which calls the model to implement the requested business and submits the result to the view layer.
Ii. Action receiving Parameters
There are three methods for receiving parameters from jsp in action:
1. Attribute Method
2. JavaBean Method
3. ModelDriven Mode
(1). Attribute method:
Package action; import java. util. hashMap; import java. util. list; import java. util. map; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import javax. servlet. http. httpSession; import org. apache. struts2.ServletActionContext; import com. opensymphony. xwork2.ActionSupport; public class UserAction extends ActionSupport {private String username; private String password; public void setUsername (String username) {this. username = username;} public void setPassword (String password) {this. password = password;}/*** business logic layer */public String login () {Map <String, Object> map = new HashMap <String, Object> (); boolean isLogin = (Boolean) map. get ("isLogin"); if (isLogin) {// logon succeeded // session ==>>>>>>>>>>>>>>>>>>/*** to get a Map object, it is equivalent to the built-in Object session Decoupling Method * // ** Map <String, Object> * session = ActionContext. getContext (). getSession (); * session. put ("user", map. get ("user"); * // *** coupling mode * // ServletContext // SC = ServletActionContext. getServletContext (); // get the Servlet context HttpServletRequest request = ServletActionContext. getRequest (); HttpServletResponse response = ServletActionContext. getResponse (); HttpSession session = request. getSession (); session. setAttribute ("user", map. get ("user"); return SUCCESS;} else {return INPUT ;}}}
Login. jsp page definition form:
<Form action = "login" method = "post"> username: <input name = "username"/> password: <input name = "password"/> <input type = "submit" value = "submit"/> <input type = "reset" value = "reset"/> </form>
Note:
1. the name attribute username and password in the <input> tag of the username and password in the form are the same as the member variables username and password defined in the action, when submitting a form, struts assigns the value to the same field name.
2. If the uploaded file contains Chinese characters, the action may receive garbled characters. You can modify the struts. xml file and add <constant name = "struts. i18n. encoding" value = "UTF-8">
Ii. JavaBean Method
1. Define the object class of the User object, and add username, password, and the corresponding get and set methods.
package entity;public class User {private String username;private String password;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}
2. Add the action of JavaBean, add the User member variable of the user type, and get, set method, execute () method
package action;import com.opensymphony.xwork2.ActionSupport;import entity.User;public class UserActionByJavaBean extends ActionSupport {private User user;@Overridepublic String execute() throws Exception {return "success";}public User getUser() {return user;}public void setUser(User user) {this.user = user;}}
3. Add the Page code to the form:
<Form action = "login" method = "post"> Username: <input name = "user. username "/> password: <input name =" user. password "/> <input type =" submit "value =" submit "/> <input type =" reset "value =" reset "/> </form>
Note:
1. When submitting the form, the attribute value is passed to the Action through the User object attribute, but the consistency between the front and back attributes must be maintained.
2. On the jsp page, you can use <s: property value = "user. username"/> to output the value of the username attribute of the user object in the Action.
3. parameters received in ModelDriven Mode
The ModelDriven interface is implemented in the action to receive parameters uploaded by the client. This method requires the entity User.
Its running process is: Struts2 calls the getModel () method in the ModelDriven interface to obtain the user object in the Action, and then saves the uploaded user name and password to the user object.
package action;import com.opensymphony.xwork2.ModelDriven;import entity.User;public class UserActionByModelDriven implements ModelDriven {private User user = new User();@Overridepublic Object getModel() {return null;}public String execute(){return "success";}}
The User object in the UserAction class is used to receive the User name and password. GetModel () is a method defined in the ModelDriven interface. It provides class access to external user objects.
<Form action = "login" method = "post"> username: <input name = "username"/> password: <input name = "password"/> <input type = "submit" value = "submit"/> <input type = "reset" value = "reset"/> </form>
Note:
1. Use ModelDriven to receive page parameters. You do not need to add an object for the name attribute. name = "username ";
Iii. usage of the method attribute in the <action> tag in Struts. xml
1. in the <action> configuration code, the method attribute calls the execute () method of the action class by default. However, in actual application, an action needs to process many methods, you can add method = "different method names" to call the corresponding methods in acton.
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN""http://struts.apache.org/dtds/struts-2.3.dtd"><struts><constant name="struts.devMode" value="true" /><constant name="struts.i18n.encoding" value="utf-8" /> <package name="default" namespace="/" extends="struts-default"><action name="login" class="action.UserAction" method="login"><result type="chain">all</result><result name="input">login.jsp</result></action><action name="all" class="action.DeptAction" method="getDept"><result>list.jsp</result></action> </package></struts>
The <action> label defines the method = 'login' and method = 'getdept' methods, and requests the methods named login and getDept in the Action class.
2. dynamic method call
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN""http://struts.apache.org/dtds/struts-2.3.dtd"><struts><constant name="struts.devMode" value="true" /><constant name="struts.i18n.encoding" value="utf-8" /> <package name="default" namespace="/" extends="struts-default"> <action name="all" class="action.DeptAction"><result>list.jsp</result></action> </package></struts>
It is not difficult to find that the method above does not specify which method to call, which should be specified in the form below.
<Form action = "login! GetAllDept "method =" post "> Username: <input name =" user. username "/> password: <input name =" user. password "/> <input type =" submit "value =" submit "/> <input type =" reset "value =" reset "/> </form>
In the form, action = "login! GetAllDept "calls the getAllDept method in the Action class.
The syntax for dynamic calling is: actionName! MethodName. action, where. action can be omitted, but it is worth noting that dynamic method calling may bring security risks and expose business methods to users. This is not recommended by the official authorities, but it can be used in struts. add <constant name = "struts. enable. dynamicMethodInvocation "value =" false "/> to disable dynamic method calls.
4. Use wildcards to simplify the configuration of <action> labels in struts. xml
1. Simplify the configuration by using wildcards in <action>
Configuration in struts. xml:
<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE struts PUBLIC "-// Apache Software Foundation // DTD Struts Configuration 2.3 // EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name = "struts. devMode "value =" true "/> <constant name =" struts. i18n. encoding "value =" UTF-8 "/> <package name =" default "namespace ="/"extends =" struts-default "> <! -- Define the default interceptor --> <default-interceptor-ref name = "myDefault"/> <action name = "index"> <result> index. jsp </result> </action> <action name = "host _ *" class = "action. houseAction "method =" {1} "> <result> list _ {1 }. jsp </result> </action> </package> </struts>
<Form action = "house_add"> </form> or <form action = "house_update"> </form> On the jsp page will receive a response request, that is, if the action attribute is any character of house _, a request is sent. The jsp page with the list _ arbitrary character in the result is returned, that is, the characters after house _ are the same as {1.
Q: Which one will match when multiple <action> matches?
Which of the following configurations will match:
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN""http://struts.apache.org/dtds/struts-2.3.dtd"><struts><action name="house_add" class="action.HouseAction" method="add"><result name="success">add.jsp</result></action><action name="house_*" class="action.HouseAction" method={1}><result>{1}.jsp</result></action> </package></struts>
Answer: if there is a full match, the full match is preferred. If there is no full match, the wildcard match is used. If there are multiple wildcard matches, the first match is prioritized.