About Struts2 file upload and custom interceptor

Source: Internet
Author: User

1. access or add request/session/application attributes

Public String scope () throws Exception {
ActionContext ctx = ActionContext. getContext ();
Ctx. getApplication (). put ("app", "Application Scope"); // Add the app to the ServletContext
Ctx. getSession (). put ("ses", "session range"); // put ses into the session
Ctx. put ("req", "request range"); // Add req to the request
Return "scope ";
}
JSP:
<Body>
$ {ApplicationScope. app} <br>
$ {SessionScope. ses} <br>
$ {RequestScope. req} <br>
</Body>

2. Get the HttpServletRequest/HttpSession/ServletContext/HttpServletResponse object

Method 1: Use the ServletActionContext. Class to directly obtain:
Public String rsa () throws Exception {
HttpServletRequest request = ServletActionContext. getRequest ();
ServletContext servletContext = ServletActionContext. getServletContext ();
Request. getSession ()
HttpServletResponse response = ServletActionContext. getResponse ();
Return "scope ";
}
Method 2: implement the specified interface, which is injected during the struts framework runtime:
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;
}
}

Iii. File Upload

Step 1: Add WEB-INF, commons-fileupload-1.2.1.jar under commons-io-1.3.2.jar/lib. These two files can be downloaded from http://commons.apache.org.

Step 2: Set the enctype of the form table to "multipart/form-data", as shown below:
<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 to 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; // obtain the uploaded File
Private String uploadImageContentType; // obtain the object type.
Private String uploadImageFileName; // obtain the file name.
// The getter/setter method of the attribute is 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 ";
}
}

Iv. Multifile upload

Step 1: Add WEB-INF, commons-fileupload-1.2.1.jar under commons-io-1.3.2.jar/lib. These two files can be downloaded from http://commons.apache.org.

Step 2: Set the enctype of the form table to "multipart/form-data", as shown below:
<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 to 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; // obtain the object type.
Private String [] uploadImagesFileName; // obtain the file name.
// The getter/setter method of the attribute is 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 must implement the com. opensymphony. xwork2.interceptor. Interceptor interface:
Public class PermissionInterceptor implements Interceptor {
Private static final long serialVersionUID =-51783101_32210602l;
Public void destroy (){
}
Public void init (){
}
Public String intercept (ActionInvocation invocation) throws Exception {
System. out. println ("Access Interceptor ");
If (a user exists in the 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" class = "cn. csdn. aop. PermissionInterceptor"/>
<Interceptor-stack name = "permissionStack">
<Interceptor-ref name = "defaultStack"/>
<Interceptor-ref name = "permission"/>
</Interceptor-stack>
</Interceptors>
<Action name = "helloworld _ *" class = "cn. csdn. action. HelloWorldAction" method = "{1}">
<Result name = "success">/WEB-INF/page/hello. jsp </result>
<Interceptor-ref name = "permissionStack"/>
</Action>
</Package>

In struts2, functions such as file upload, data verification, and encapsulation of request parameters to actions are implemented by the system's default stack Interceptor. Therefore, the defined interceptor must reference the system's default defaultStack, in this way, the application can use all the functions provided by the struts2 framework.

If you want to use a custom interceptor for all actions under the package, you can use <default-interceptor-ref name = "permissionStack"/> to define the interceptor as the default interceptor. Note: Only one default interceptor can be specified for each package. In addition, once an interceptor is explicitly specified for an action in the package, the default interceptor does not work.

Vi. Input Validation

In struts2, we can verify all the methods of the action or the specified method of the action.
Two input verification methods are provided for struts2:
1. Use manual coding for implementation.
2. Implementation Based on XML configuration.

7. Manually write the code to verify the input of all methods in the action

By Rewriting the validate () method, the validate () method verifies all methods in the action that are the same as the execute method signature. When a data verification fails, we should call the addFieldError () method to add verification failure information to the fieldErrors of the System. (to use the addFieldError () method, action can inherit ActionSupport ), if the system's fieldErrors contains Failure Information, struts2 forwards the request to the result named input. In the input view, you can use <s: fielderror/> to display the failure information.
Example of validate:
Public void validate (){
If (this. mobile = null | "". equals (this. mobile. trim () {this. addFieldError ("username", "the mobile phone number cannot be blank ");
} Else {if (! Pattern. compile ("^ 1 [358] \ d {9}"). matcher (this. mobile. trim (). matches ()){
This. addFieldError ("mobile", "Incorrect mobile Phone Number Format ");}
}
}

After verification fails, the request is forwarded to the input View:

<Result name = "input">/WEB-INF/page/addUser. jsp </result>
On the addUser. jsp page, use <s: fielderror/> to display the failure information.
By using the validateXxx () method, validateXxx () only verifies the method named Xxx in the action. The first letter of Xxx must be in uppercase. When a data verification fails, we should call the addFieldError () method to add verification failure information to the fieldErrors of the System. (to use the addFieldError () method, action can inherit ActionSupport ), if the system's fieldErrors contains Failure Information, struts2 forwards the request to the result named input. In the input view, you can use <s: fielderror/> to display the failure information.

Example of validateXxx () method:
Public String add () throws Exception {return "success ";}
Public void validateAdd (){
If (username = null & "". equals (username. trim () this. addFieldError ("username", "username cannot be blank ");
}

After verification fails, the request is forwarded to the input View:

<Result name = "input">/WEB-INF/page/addUser. jsp </result>
On the addUser. jsp page, use <s: fielderror/> to display the 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 saves the exception information to ActionContext. The conversionError interceptor adds the exception information to fieldErrors. No matter whether the type conversion is abnormal or not, it will go to step 1.
3. The system uses reflection technology to call the validateXxx () method in action. Xxx is the method name.
4. Call the validate () method in action.
5. After the preceding four steps, if fieldErrors in the system has an error message (that is, the size of the Set storing the error information is greater than 0), the system automatically forwards the request to the view named input. If fieldErrors in the system does not have any error information, the system will execute the processing method in the action.

9. Input Validation for all action methods based on XML Configuration

When using XML-based configuration method to achieve input validation, Action also needs to inherit ActionSupport, and provide the validation file, the validation file and action class in the same package, the file name format is: ActionClassName-validation.xml, specifically, ActionClassName is the simple class name of action, and-validation is the fixed writing method. If the Action class is cn. csdn. UserAction, the file name should be: UserAction-validation.xml. The following is a template for file Verification:
<? Xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE validators PUBLIC "-// OpenSymphony Group // XWork Validator 1.0.3 //" 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> the user name cannot be blank! </Message>
</Field-validator>
</Field>
</Validators>

<Field> specifies the attribute to be verified in the action. <field-validator> specifies the validator. The requiredstring specified above is provided by the system, the system provides validators that meet most of the verification requirements, and the definitions of these validators can be in the xwork-2.x.jar of com. opensymphony. xwork2.validator. default under validators. in xml.
<Message> This is the prompt message after verification failure. If you want to internationalize the message, you can specify the key attribute for the message. The key value is the key in the resource file.
In this verification file, to verify the string-type username attribute in the action, you must first call the trim () method to remove spaces and then determine whether the username is empty.
No help information is available when you compile the verification file.
When writing a ActionClassName-validation.xml validation file, if there is no help information, you can solve the problem as follows:
Windwos-> preferences-> myeclipse-> files and editors-> xml-> xmlcatalog
Click add, select File system in the location in the window that appears, and then select the xwork-2.1.2 In the src \ java directory of the xwork-validator-1.0.3.dtd extract directory, when you return to the settings window, do not rush to close the window. You should change the Key Type in the window to URI. Key to http://www.opensymphony.com/xwork/xwork-validator-1.0.3.dtd

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.