1. Access or add request/session/application attributes
public String scope() throws Exception{
ActionContext ctx = ActionContext.getContext();
ctx.getApplication().put("app", "Application scope");//Put app into ServletContext
ctx.getSession().put("ses", "session range");//Put ses into the session
ctx.put("req", "request range");//Put req into request
return "scope";
}
JSP:
<body>
${applicationScope.app} <br>
${sessionScope.ses}<br>
${requestScope.req}<br>
</body>
2. Obtain the HttpServletRequest / HttpSession / ServletContext / HttpServletResponse object
Method one, obtain directly through the ServletActionContext. class:
public String rsa() throws Exception{
HttpServletRequest request = ServletActionContext.getRequest();
ServletContext servletContext = ServletActionContext.getServletContext();
request.getSession()
HttpServletResponse response = ServletActionContext.getResponse();
return "scope";
}
Method two, implement the specified interface and inject it when the struts framework is running:
public class HelloWorldAction implements ServletRequestAware, ServletResponseAware, ServletContextAware{
private HttpServletRequest request;
private ServletContext servletContext;
private HttpServletResponse response;
public void setServletRequest(HttpServletRequest req) {
this.request=req;
}
public void setServletResponse(HttpServletResponse res) {
this.response=res;
}
public void setServletContext(ServletContext ser) {
this.servletContext=ser;
}
}
3. File upload
Step one: Add commons-fileupload-1.2.1.jar and commons-io-1.3.2.jar under WEB-INF/lib. Both files can be downloaded from http://commons.apache.org/.
Step 2: Set the enctype of the form table to: "multipart/form-data", as follows:
<form enctype="multipart/form-data" action="${pageContext.request.contextPath}/xxx.action" method="post">
<input type="file" name="uploadImage">
</form>
Step 3: Add the following attributes in the Action class. The red part of the attribute corresponds to the name of the file field in the form:
public class HelloWorldAction{
private File uploadImage;//Get the uploaded file
private String uploadImageContentType;//Get the file type
private String uploadImageFileName;//Get the name of the file
//The getter/setter methods of the properties are omitted here.
public String upload() throws Exception{
String realpath = ServletActionContext.getServletContext().getRealPath("/images");
File file = new File(realpath);
if(!file.exists()) file.mkdirs();
FileUtils.copyFile(uploadImage, new File(file, uploadImageFileName));
return "success";
}
}
4. Multiple file upload
Step one: Add commons-fileupload-1.2.1.jar and commons-io-1.3.2.jar under WEB-INF/lib. Both files can be downloaded from http://commons.apache.org/.
Step 2: Set the enctype of the form table to: "multipart/form-data", as follows:
<form enctype="multipart/form-data" action="${pageContext.request.contextPath}/xxx.action" method="post">
<input type="file" name="uploadImages">
<input type="file" name="uploadImages">
</form>
Step 3: Add the following attributes in the Action class. The red part of the attribute corresponds to the name of the file field in the form:
public class HelloWorldAction{
private File[] uploadImages;//Get the uploaded file
private String[] uploadImagesContentType;//Get the type of file
private String[] uploadImagesFileName;//Get the name of the file
//The getter/setter methods of the properties are omitted here.
public String upload() throws Exception{
String realpath = ServletActionContext.getServletContext().getRealPath("/images");
File file = new File(realpath);
if(!file.exists()) file.mkdirs();
for(int i=0 ;i<uploadImages.length; i++){ File uploadImage = uploadImages[i];
FileUtils.copyFile(uploadImage, new File(file, uploadImagesFileName[i]));
}
return "success";
}}
5. Custom interceptor
To customize the interceptor, you need to implement the com.opensymphony.xwork2.interceptor.Interceptor interface:
public class PermissionInterceptor implements Interceptor {
private static final long serialVersionUID = -5178310397732210602L;
public void destroy() {
}
public void init() {
}
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("Enter interceptor");
if(user exists in session){
String result = invocation.invoke();
}else{
return "logon";
}
//System.out.println("Return value:"+ result);
//return result;
}
}
<package name="csdn" namespace="/test" extends="struts-default">
<interceptors>
<interceptor name="permission" />
<interceptor-stack name="permissionStack">
<interceptor-ref name="defaultStack" />
<interceptor-ref name=" permission " />
</interceptor-stack>
</interceptors>
<action name="helloworld_*" method="{1}">
<result name="success">/WEB-INF/page/hello.jsp</result>
<interceptor-ref name="permissionStack"/>
</action>
</package>
Because functions in struts2 such as file upload, data verification, and encapsulation of request parameters into actions are all implemented by the interceptor in the system's default defaultStack, the interceptor we define needs to reference the system's default defaultStack so that the application can use struts2 Numerous features provided by the framework.
If you want all actions under the package to use a custom interceptor, you can define the interceptor as the default interceptor through <default-interceptor-ref name="permissionStack"/>. Note: Only one default interceptor can be specified per package. In addition, once we explicitly specify an interceptor for an action in the package, the default interceptor will not work.
6. Input verification
In struts2, we can verify all methods of action or verify specified methods of action.
Struts2 provides two implementation methods for input verification:
1. Implemented by manually writing code.
2. Implemented based on XML configuration.
7. Manually write code to verify the input of all methods in the action
By overriding the validate() method, the validate() method will verify all methods in the action that have the same signature as the execute method. When a certain data verification fails, we should call the addFieldError() method to add verification failure information to the system's fieldErrors (in order to use the addFieldError() method, the action can inherit ActionSupport). If the system's fieldErrors contain failure information, struts2 will The request is forwarded to the result named input. Failure information can be displayed through <s:fielderror/> in the input view.
validate() usage example:
public void validate() {
if(this.mobile==null || "".equals(this.mobile.trim())){ this.addFieldError("username", "Mobile phone number cannot be empty");
}else{ if(!Pattern.compile("^1[358]//d{9}").matcher(this.mobile.trim()).matches()){
this.addFieldError("mobile", "The format of the mobile phone number is incorrect"); }
}
}
After verification fails, the request is forwarded to the input view:
<result name="input">/WEB-INF/page/addUser.jsp</result>
Use <s:fielderror/> in the addUser.jsp page to display failure information.
Implemented through the validateXxx() method, validateXxx() will only verify the method named Xxx in the action. The first letter of Xxx should be capitalized. When a certain data verification fails, we should call the addFieldError() method to add verification failure information to the system's fieldErrors (in order to use the addFieldError() method, the action can inherit ActionSupport). If the system's fieldErrors contain failure information, struts2 will The request is forwarded to the result named input. Failure information can be displayed through <s:fielderror/> in the input view.
Example of using validateXxx() method:
public String add() throws Exception{ return "success";}
public void validateAdd(){
if(username==null && "".equals(username.trim())) this.addFieldError("username", "Username cannot be empty");
}
After verification fails, the request is forwarded to the input view:
<result name="input">/WEB-INF/page/addUser.jsp</result>
Use <s:fielderror/> in the addUser.jsp page to display failure information.
8. Input verification process
1. The type converter performs type conversion on the request parameters and assigns the converted value to the attribute in the action.
2. If an exception occurs during type conversion, the system will save the exception information to the ActionContext, and the conversionError interceptor will add the exception information to fieldErrors. Regardless of whether an exception occurs during type conversion, step 3 will be entered.
3. The system first calls the validateXxx() method in the action through reflection technology, where Xxx is the method name.
4. Then call the validate() method in the action.
5. After the above 4 steps, if there is error information in fieldErrors in the system (that is, the size of the collection storing error information is greater than 0), the system will automatically forward the request to the view named input. If there is no error information in the fieldErrors in the system, the system will execute the processing method in the action.
9. Implement input verification for all action methods based on XML configuration method
When using the XML-based configuration method to implement input verification, the Action also needs to inherit ActionSupport and provide a verification file. The verification file and the action class are placed in the same package. The file naming format is: ActionClassName-validation.xml, where ActionClassName is the simple class name of action, and -validation is a fixed writing method. If the Action class is cn.csdn.UserAction, then the name of the file should be: UserAction-validation.xml. The following is a template for the verification file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.3//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.3.dtd">
<validators>
<field name="username">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>Username cannot be empty!</message>
</field-validator>
</field>
</validators>
<field> specifies the attributes to be verified in the action, and <field-validator> specifies the validator. The validator requiredstring specified above is provided by the system. The system provides validators that can meet most verification requirements. These The definition of the validator can be found in default.xml under com.opensymphony.xwork2.validator.validators in xwork-2.x.jar.
<message> is the prompt message after the verification fails. If internationalization is required, you can specify the key attribute for the message, and the value of key is the key in the resource file.
In this verification file, the username attribute of the string type in the action is verified. It is first required to call the trim() method to remove spaces, and then determine whether the username is empty.
When writing the verification file, the help message cannot appear. When writing the ActionClassName-validation.xml verification file, if the help message does not appear, you can solve the problem as follows:
windowwos->preferences->myeclipse->files and editors->xml->xmlcatalog
Click "add", select "File system" in the location in the window that appears, then select xwork-validator-1.0.3.dtd in the src/java directory of the xwork-2.1.2 decompression directory, and return to the setting window Don't rush to close the window, you should change the Key Type in the window to URI. Key changed to http://www.opensymphony.com/xwork/xwork-validator-1.0.3.dtd