About Struts2 file upload and custom interceptor _java

Source: Internet
Author: User
Tags file upload trim

First, access or add request/session/application properties

Public String scope () throws exception{
Actioncontext CTX = Actioncontext.getcontext ();
Ctx.getapplication () put ("app", "Application Range");//Add app to ServletContext
Ctx.getsession ("ses", "Session Scope"); Put SES into the session
Ctx.put ("req", "request Range")//Put Req in Request
return "Scope";
}
Jsp:
<body>
${applicationscope.app} <br>
${sessionscope.ses}<br>
${requestscope.req}<br>
</body>

Ii. getting Httpservletrequest/httpsession/servletcontext/httpservletresponse objects

Method one, through the Servletactioncontext. Class Direct Access:
Public String RSA () throws exception{
HttpServletRequest request = Servletactioncontext.getrequest ();
ServletContext ServletContext = Servletactioncontext.getservletcontext ();
Request.getsession ()
HttpServletResponse response = Servletactioncontext.getresponse ();
return "Scope";
}
Method Two, which implements the specified interface and is injected by 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;
}
}

Third, File upload

The first step: Add Commons-fileupload-1.2.1.jar, Commons-io-1.3.2.jar under Web-inf/lib. These two files can be downloaded from the http://commons.apache.org/.

The second step: the form table enctype set 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 three: In the Action class, add the following property, which corresponds to the name of the file field in the form:

public class helloworldaction{
Private file uploadimage;//get uploaded files
Private String uploadimagecontenttype;//the type of file
Private String uploadimagefilename;//The name of the file
This is a bit of a getter/setter method for attributes.
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";
}
}

Four, multiple file upload

The first step: Add Commons-fileupload-1.2.1.jar, Commons-io-1.3.2.jar under Web-inf/lib. These two files can be downloaded from the http://commons.apache.org/.

The second step: the form table enctype set 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 three: In the Action class, add the following property, which corresponds to the name of the file field in the form:
public class helloworldaction{
Private file[] uploadimages;//get uploaded files
Private string[] uploadimagescontenttype;//to get the type of file
Private string[] uploadimagesfilename;//get the name of the file
This is a bit of a getter/setter method for attributes.
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";
}}

v. Custom interceptors

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 ("Entry 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" 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>

Because struts2 such as file upload, data validation, encapsulation request parameters to action and other functions are implemented by the system's default Defaultstack interceptor, so our definition of interceptors need to refer to the system default Defaultstack, This allows applications to use the many features provided by the STRUTS2 framework.

If you want all the action under the package to use a custom interceptor, you can define the interceptor as the default interceptor by <default-interceptor-ref name= "Permissionstack"/>. Note: Only one default interceptor can be specified per package. Also, once we explicitly specify an interceptor for an action in the package, the default interceptor does not work.

Six, input check

In Struts2, we can validate all the methods of the action or validate the action's specified method.
Two implementations are provided for input checksum struts2:
1. Implement by hand-coded code.
2. Implementation based on XML configuration method.

Seven, hand-written code implementation of the action in all methods input validation

By overriding the Validate () method implementation, the validate () method verifies all methods in the action that are identical to the Execute method signature. When a data checksum fails, we should call the Addfielderror () method to add checksum failure information to the fielderrors of the system (in order to use the Addfielderror () method, the action can inherit Actionsupport), If the system's Fielderrors contains failure information, STRUTS2 forwards the request to result named input. Failure information can be displayed in the input view through <s:fielderror/>.
Validate () Use example:
public void Validate () {
if (This.mobile==null | | "". Equals (This.mobile.trim ()) {This.addfielderror ("username", "cell phone number cannot be empty");
}else{if (!pattern.compile ("^1[358]\\d{9}"). Matcher (This.mobile.trim ()). Matches ()) {
This.addfielderror ("mobile", "cell phone number is not the correct format"); }
}
}

The request is forwarded to the input view after the validation fails:

<result name= "Input" >/WEB-INF/page/addUser.jsp</result>
Use <s:fielderror/> to display failure information in the adduser.jsp page.
Implemented by the ValidateXxx () method, ValidateXxx () only validates the method named XXX in the action. Where the first letter of XXX should be capitalized. When a data checksum fails, we should call the Addfielderror () method to add checksum failure information to the fielderrors of the system (in order to use the Addfielderror () method, the action can inherit Actionsupport), If the system's Fielderrors contains failure information, STRUTS2 forwards the request to result named input. Failure information can be displayed in the input view through <s:fielderror/>.

ValidateXxx () method Use Example:
Public String Add () throws exception{return "success";}
public void Validateadd () {
if (Username==null && "". Equals (Username.trim ())) This.addfielderror ("username", "user name cannot be empty");
}

The request is forwarded to the input view after the validation fails:

<result name= "Input" >/WEB-INF/page/addUser.jsp</result>
Use <s:fielderror/> to display failure information in the adduser.jsp page.

Eight, the input check process

1. The type converter performs a type conversion on the request parameter 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 the Actioncontext,conversionerror interceptor to add the exception information to the fielderrors. The 3rd step is entered regardless of whether the type conversion occurs unexpectedly.
3. The system calls the ValidateXxx () method in action first by reflection technology, and XXX is the method name.
4, and then invoke the Validate () method in the action.
5, after the above 4 steps, if the system in the Fielderrors error message (that is, the set containing the error message size greater than 0), the system automatically forwards the request to the name input view. If the fielderrors in the system does not have any error messages, the system executes the processing method in the action.

Implementation of input validation of all methods of action based on XML configuration mode

When you implement an input checksum based on an XML configuration, the action also needs to inherit Actionsupport and provide a checksum file, and the validation file and the action class are placed under the same package. The file name format is: Actionclassname-validation.xml, where actionclassname is the action of the Simple class name,-validation for the fixed wording. 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 validating files:
<?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> user name cannot be empty!</message>
</field-validator>
</field>
</validators>

<field> specify the property to validate in action,<field-validator> specifies the validator, the requiredstring specified above is provided by the system, and the system provides a validator that satisfies most of the verification requirements, The definitions of these validators can be found in the Default.xml under Com.opensymphony.xwork2.validator.validators in Xwork-2.x.jar.
<message> to verify the failure of the prompt information, if you need internationalization, you can specify the key attribute, key value is the resource file key.
In this checksum file, the Username property of the string type in the action is validated, first requiring that the trim () method be invoked to remove the space and then determine whether the user name is empty.
Help information cannot appear when writing a checksum file
When writing a actionclassname-validation.xml checksum file, if no help information appears, you can resolve it in the following way:
Windwos->preferences->myeclipse->files and Editors->xml->xmlcatalog
Click "Add", select "File system" in the window in which it appears, and then choose Xwork-validator-1.0.3.dtd in the Src\java directory of xwork-2.1.2 extract directory, location When you go back to the Settings window, don't rush to close the window, you should change the key type in the window to a URI. Key changed 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.