Struts2.x tutorial (3) Struts2 interceptor

Source: Internet
Author: User

Struts2.x tutorial (3) Struts2 interceptor
1. Introduction to Struts2 interceptorThe Struts2 interceptor is implemented using AOP and mainly blocks action objects. It can intercept a method or field of an action before or after it is accessed. You can configure multiple interceptors for the action. Struts2 organizes the group of interceptors into an interceptor stack in a certain order. Action can directly reference an interceptor stack to configure multiple interceptors. Action in the package that inherits struts_default will reference the interceptor stack of name = defaultStack by default (various interceptors provided by struts_default are defined in struts_default). For the call sequence of the interceptor, see:Ii. interceptor implementationThe Interceptor of Struts2 implements the com. opensymphony. xwork2.interceptor. Interceptor interface:

Public interface Interceptor extends Serializable {
// Destruction method
Void destroy ();
// Initialization Method
Void init ();
// Interception Method
String intercept (ActionInvocation invocation) throws Exception;
}
To implement a custom Interceptor, we need to implement the Interceptor interface and implement the intercept () method. For example, we implement a simple authentication Interceptor:
Public class AuthorityInterceptor implements Interceptor {

Public void init (){
}

Public void destroy (){
}

@ Override
Public String intercept (ActionInvocation invocation) throws Exception {
Object user = ActionContext. getContext (). getSession (). get ("user ");
If (user = null ){
System. out. println ("not logged on, please log on first! ");
Return "login ";
}
Return invocation. invoke ();
}
}
In intercept () of the custom interceptor, we can return a string Result. At this time, the request is terminated and the corresponding result is redirected. Invocation is a reference of ActionInvocation. ActionInvocation is used to call the action of the request and a series of interceptors. When invocation is called. when invoke () is used, it will determine whether there is an interceptor in the interceptor stack at this time. If yes, it will call the interception method of the next interceptor; otherwise, it will call the request method corresponding to the action. Above, we have implemented a custom interceptor. To make the custom interceptor work, you need to configure it in the struts. xml configuration file: first, declare the interceptor under the package element: Then, you can reference this interceptor in the action element, for example: /Success. jsp However, you must note that when you set It will overwrite the reference of the default defastack stack interceptor stack. Assume that the custom interceptor is only a log blocker. In this way, the interceptor in defaultStack will not be called. For example, if the most important parameter interceptor is ParametersInterceptor, problems will occur when calling the action. Therefore, when adding an interceptor reference to an action, it is usually configured as follows: /Success. jsp 3. Use an interceptor to upload filesStruts 2 uses commons-fileupload to upload files. First, use commons-fileupload to upload the files to a temporary directory, and then the Struts2 interceptor encapsulates the file information into the action object, then, upload the specified directory as a local file. File Upload steps: 1. Set the File Upload form on the page
< S: Form Action= "DoUpload" Method= "POST" Enctype= "Multipart/form-data">
< S: File Name= "Upload" label = "File"/>
< S: Submit/>
S: Form>
2. Compile the File Upload Action
Public class FileUploadAction extends ActionSupport {
Private static final long serialVersionUID = 5156288255337069381L;
Private String contentType; // type of the object to be uploaded
Private File upload; // upload a File
Private String fileName; // name of the uploaded file
Private String caption; // submitted information
Public String input () throws Exception {
Return SUCCESS;
}
Public String upload () throws Exception {
String path = "upload \\";
InputStream in = new FileInputStream (upload );
String contextPath = ServletActionContext. getServletContext (). getRealPath ("/");
File dir = new File (contextPath );
If (! Dir. exists ()){
Dir. mkdir ();
}
String filePath = contextPath + path + fileName;
OutputStream out = new FileOutputStream (filePath );
Int bytesRead;
Byte [] buffer = new byte [8192];
While (bytesRead = in. read (buffer, 0, 8192 ))! =-1 ){
Out. write (buffer, 0, bytesRead );
}
Out. close ();
In. close ();

Return SUCCESS;
}
Public String getUploadFileName (){
Return fileName;
}
Public void setUploadFileName (String fileName ){
This. fileName = fileName;
}
Public String getUploadContentType (){
Return contentType;
}
Public void setUploadContentType (String contentType ){
This. contentType = contentType;
}
Public File getUpload (){
Return upload;
}
Public void setUpload (File upload ){
This. upload = upload;
}
Public String getCaption (){
Return caption;
}
Public void setCaption (String caption ){
This. caption = caption;
}
}
Note: The interceptor will encapsulate the file name and the file encoding type into the uploadFileName and uploadContentType attributes, where upload is the name of the file tag corresponding to the page, and FileName and ContentType are fixed suffixes, therefore, the getter and setter methods must correspond to these two names. Otherwise, the file information cannot be encapsulated. 3. In the struts. xml configuration file, configure the action request. /Upload. jsp /Upload. jsp Upload-success.jsp Note: a and Struts2 use the Interceptor to upload files. Because the default defaultStack interceptor stack referenced by the action already contains the fileUpload interceptor, you do not need to add a reference to the file upload interceptor. B. By default, Struts2 uploads a file up to 2 MB. To modify the maximum size of files to be uploaded (20 mb in bytes) 4. Submit the interceptor repeatedlyIn Struts2, the mechanism to prevent repeated submission is also implemented by the Interceptor. The principle is as follows: 1. Add Tag: it generates a random string with the key struts. token in the session, and adds corresponding hidden tags to the page, for example: 2. When a form is submitted, the hidden fields are also submitted. In the token interceptor, the submitted token value is compared with the saved token value in the session. If the value is equal, the subsequent request is processed, at the same time, the token in the session is cleared. If not, the request is blocked. It intercepts repeated requests in this way to prevent repeated submission. Struts2 provides two types of repeated submission interceptors. token: When repeated submission occurs, it jumps to the specified page and needs to be configured. /Input TokenSession: When the button is submitted repeatedly, the page will not be adjusted. After the first request is completed, the page will jump to the successful page to compare the two blocking mechanisms. The tokenSession is more adaptable. Implementation steps: 1. Add on the page In the form. The token label of Struts1 must be Struts2 does not have this restriction, and common html tags can still be used. To prevent repeated submission. 2. Add the interceptor reference to struts. xml. The toultstack interceptor stack does not contain the token Interceptor. Therefore, you need to add the reference. /User-input /User. jsp If you use the tokenSession interceptor, you do not need to configure invalid. token: /User. jsp The preceding steps are implemented by the Interceptor to prevent repeated submission.

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.