Struts2
A
WebWork
Framework: Applications based on request response (Request-response) patterns.
Performance Logic Structure:
1 Controller (controll)-controls the coordination of the components in the entire framework.
2 Business Logic Layer (Business Logic)-Concepts and several basic components that can provide services (real implementations need to be extended over the framework again).
3 Logic Layer (data Logic)-including data logic and data access interface.
Significance: Reusable Modular design
Flexibility and availability
ognl--Expression Language
Two
Development steps: See-click Open link
1 New Project
2 Import Package
3 New JSP file
4 Configuring Web.xml Files
5 src under the new Struts.xml file and configure
6 new Action file (Bean)
Add a jar pack if you need to start an error with Tomcat
Javassit.jar to be added after struts2.2 (excluding JBoss, built in)
The following statement gets the request field content (similar to request.getattribute):
Username:${requestscope.username}<br/>
Password:${requestscope.password}
Struts Basic execution principle (find matching information for processing-* logic)
Reflection
Struts.xml->extends:struts-default (with package) inheritance
Filter Takeover request
Each request generates an Action object
Three
STRUTS2 type conversions (common data types, such as 8 native data types, are automatically converted using built-in type converters, but manual conversions are required for custom data)
Action inherits from Actionsupport (provides various support for struts)
Built-in type conversion: Click to open link
Converter conversion (Converter): Click to open link
Type conversions
1 {type converter converter (inherited from Defaulttypeconverter-> placed Ognl)->convertervalue method
StringTokenizer (split extract string)->nexttoken (get split string)
return SUCCESS;
Conversion processing code (Hello;word conversion to two strings):
Use object as a generic
if (User.class==totype) {
CONVERT (convert from page to background object)
String[] str= (string[]) value;//converts value to a String array
String firstvalue=str[0];//out strings
To split a string array
StringTokenizer st=new StringTokenizer (firstvalue, ";"); /The first parameter is the delimiter for the second argument of the string to be converted
Get the string after split
String Username=st.nexttoken ();//Remove the first
String Password=st.nexttoken ();//Remove the second
Generate User Object
User User=new user ();
User.setusername (username);//Put the converted string into the Usre object
User.setpassword (password);
return user;
New useraction-conversion.properties configuration file in action package specify converter
Custom type conversions need to provide 3 information: the name of the action, the name of the property to be converted in the action, and the type converter (properties file converter file) action name that corresponds to the attribute is obtained by the property file name, The name of the property to be converted in action is obtained by key in the property file, and the type converter for the property obtains the->properties by the type converter name value corresponding to the key.
}
JSP Application Tag Library: <%@ taglib prefix= "s" uri= "/struts-tags"%>
2 Struts2 type conversion (typeconverter-> inheritance Defaulttypeconverter):
public class UserConverter2 extends Strutstypeconverter {
@Override the public
Object convertfromstring (Map Context, string[] values, Class toclass} {
//TODO auto-generated Method stub
//from page to background convert
user user=new User () ;
String value=values[0];//extract Strings
stringtokenizer st=new stringtokenizer (";"); /Split
User.setusername (St.nexttoken ());
User.setpassword (St.nexttoken ());
return user;
}
@Override public
String converttostring (Map context, Object o) {
//TODO auto-generated method stub
User u Ser= (User) o;
String username=user.getusername ();
String Password=user.getpassword ();
String userinfo= "Username:" +username+ "-password:" +password;
Return UserInfo
}
}
/struts2-1/src/com/sw/struts2/useraction-conversion.properties (configuration file-Specify the transform file):
#user =com.sw.converter.userconverter (#为注释)
3 Batch Conversion data type (using Set)-> set conversion
Code:
(1) from the page to the background
@Override public
Object convertfromstring (Map context, string[] values, Class toclass) {
//TODO auto-generated m Ethod stub
//batch processing
list<user> list=new arraylist<user> ();
for (String value:values) {//traverse
StringTokenizer st=new StringTokenizer (value, ";");
User User=new User ();
User.setusername (St.nexttoken ());
User.setpassword (St.nexttoken ());//Load
list.add (user);
}
return list;
}
(2) from the background to the page
@Override public
String converttostring (Map context, Object o) {
//TODO auto-generated method stub
list< User> list= (list<user>) o;//cast
StringBuffer buffer=new ();//concatenation string (all strings in the collection) for
( User user:list) {//Traverse
String username=user.getusername ();
String Password=user.getpassword ();
Stitching
Buffer.append ("Username:"). Append (username). Append ("-PASSWPRD:"). append (password);
return buffer.tostring ();
}
4 Development-Time type conversion (global conversion)
Xwork-conversion.properties file:
class to convert = Name of converter
For example:
Com.sw.bean.user=com.sw.converter.userconverter3
Excute similar to Doget () and Dopost ()
Custom execute (other than the method name)-> does not recommend rewriting-> makes code confusing
Four
Input checksum-> (client-side inspection, server checksum)
1 Client Authentication
Tag Library: Property (specify that an attribute is displayed)
(1) Validate ()-> validation-> override method-> execute before Execute
<s:actionerror/>---Show action error
Calendar-> comparison Time
Error Tip:
This.addactionerror ("username size:4-6!"); /Drop Action Level error message
This.addfielderror (username, "username size:4-6");//attribute level error message
Struts2 with label (less)
Theme-> Custom Form Theme
Process:
(1) First type conversion (can be internal conversion)
(2) Input checksum (execute Validate method)
(3) Any error (type conversion error, input checksum error) that occurs in the process above will not execute the Execute method again, the page turns to the page of the action named input in Struts.xml
This.getfielderrors (). Clear ();//Empty error message
This.getactionerrors (). Clear ();
A when the call to the Getaction () method returns a list of error messages at the action level, the return is actually a copy of the collection rather than the collection itself, so calling the clear () method on the copy of the collection is still the element in the replica, not the element in the original collection. The contents of this collection are not affected by any of these. The error list for the action level is read-only for developers.
b filederror level error information is implemented using LINKEDHASHMAP, the map key is String type, value is the list<string> type, which means that a filed name can correspond to multiple error messages , these error messages are placed in the List<string> collection.
Hasactionerrors ()->bool type, detect if there is an error message
Hasfilederrors ()->
The Addactionerror () method of the Actionsupport class:
First create a ArrayList object, and then place the ArrayList in the object
Input checksum for custom methods in action: For the custom method specified by the action's method attribute, its corresponding custom input validation method name is Validatemyexcute (assuming the custom method name is Myexecute)-> Validatemyexecute is superior to validate
Myexecute is superior to execute
Custom methods are executed before the Execute method.
Custom error message (corresponding to the package action sibling):
New profile: Action name. Properties:invalid.fieldvalue. Error variable =age invalid!
Struts validation Framework (valid XML file->action under sibling directory)
Registeraction-validation.xml
It can be divided into field priority Calibrator and Calibrator Priority checker
(1) Field Priority Checker (contains filed)
<validators> root element
. xml file:
<validators>
<field name= "username" >
< Field-validator type= "requiredstring" >
<message>username cant ' t be blank!</message>
</ field-validator>
</field>
</validators>
Chinese and English error message profile (key property):
package_en_us.properties-> English
Package_zh_cn.properties
I18n->locale
Internationalized resource file naming rules: Package_ language Name _ Country name
Example: PACKAGE_ZH_CN
Package_en_us
(2) Checker priority calibrator
. xml file:
<!--checksum-->
<validator>
<validator type= "requiredstring" >
<param name= " FieldName ">username</param>
<message>uaername cant ' t be blank!</message>
</ validator>
<validator type= "Stringlength" >
<param name= "FieldName" >username</param>
<param name= "minlength" >4</param>
<param name= "MaxLength" >6</param>
< Message>username size:${minlength}-${maxlength}</message>
</validator>
<validator >
Both can be used together
The order in which struts verifies the execution of frames:
(1) First execute the Validation framework (XML file)
(2) Implementation of custom calibration method (Validatemyexecute)
(3) Execute Validate method
Any one step error will not be executed again
Five
Handling of exceptions (can also handle checksums)
Processing: Struts.xml files under Action <exception-mapping>
Global result set:<global-results></global-results>
Global Exception:<global-exception-mappings></global-exception-mappings>
The local always takes precedence over the global.
Local: Unique action sharing
Global: All Action shares
Six
Business logic Processing
(1) Create service (interface)
(2) Implement service (Impelment)
(3) Create DAO (have implement invoke DAO implementation Class)-can omit
(4) Implement service object in action
Seven
Layered architecture for struts2 underlying applications
Action->service (interface and Impelment)->dao (interacting with the database)
STRUTS2 model Driver-> a single property as a model, invokes the model, and then looks for a single property.
Property driver (a single property is called in the action)
The difference between attribute-driven and model-driven:
(1) The property driver is flexible, accurate, and the model driver is not flexible, because many times, the parameters submitted by the page do not belong to the attributes in the model, which means that the parameters submitted by the page are not consistent with the model.
(2) Model-driven more in line with object-oriented programming style, so that we get objects rather than discrete values.
Summary: Use attribute drivers to write action as much as possible
(eight)
There are two modes of unit testing for server-side code:
(1) Container test (Jetty)-> server
(2) Mock test (simulated test)-> inherits Servlet APIs such as HttpServletRequest, HttpSession, HttpServletResponse, etc.
JMock, EasyMock (agent mechanism->java dynamic agent)
Preparable (xwork) interface:
Let the action do some initialization work, which is done in the prepare method of the Preparable interface, which is invoked before the Execute method executes.
Nine
Actual development:
A request for forwarding to complete the addition of the form content will cause the content to be inserted repeatedly.
Redirect: redirect
Diapatcher
Redirectaction-> Redirect to an action
<result name= "SUCCESS" type= "redirectaction" >action2</result>-> Redirect to Action2
Redirect and pass value (development common):
<action name= "Action1" class= "Com.sw.struts2.Action1" > <result name= "SUCCESS" type= "Redirectaction"
>
<param name= "ActionName" >action2</param>
<param name= "username" >${username}</ param>
<param name= "password" >${password}</param>
<param name= "Usernameandpassword" >${usernameAndPassword}</param>
</result>
</action>
Request Forwarding: Type=chain
Prevent forms from being submitted repeatedly:
(1) through redirection (redirect)
(2) through session Token (Session token)-> Check whether for the first commit (with string matching is repeated submission)
Token->struts.xml configuration:
<action name= "token" class= "com.sw.struts2.TokenAction" >
<result name= "SUCCESS" >/tokenSuccess.jsp</result>
<result name= "Invalid.token" >/tokenErr.jsp</result>
<!--Interceptor-->
<interceptor-ref name= "token" ></interceptor-ref>
<interceptor-ref name= "Defaultstack" ></interceptor-ref>
</action>
JSP configuration:
<s:form action= "token.action" theme= "simple" >
Username:<s:textfield name= "username" ></s:textfield><br/>
Password:<s:password name= "Password" ></s:password><br/>
<s:token></s:token>
<s:submit value= "Submit" ></s:submit>
</s:form>
When the client requests the page, the server generates a random number through the token tag and places the random number in the session, then changes the random number to the client, and if the customer submits it for the first time, the random number is sent to the server side. The server receives the random number and compares it to the random number saved in the session. The value of the two is the same, the server is considered to be the first submission, and the server's random value will be updated; If this is repeated, then the client sends a random number to the server or the previous one, The server side of the random number has changed, the difference between the two, the server that this is a duplicate submission, and then to the Invalid.token point of the results page.
(10)
Interceptor (Interceptor)
The 1 interceptor is the core of struts2, and Struts2 's many functions are achieved through interceptors.
Interceptor can intercept action
Servlet filter.
The interceptor must be stateless
Steps:
(1) New package
(2) New Interceptor class, inherited from Interceptor
(3) Write Intercept method
(4) Configure Struts.xml (define Interceptor):
<!--Interceptor-->
<interceptors>
<interceptor name= "Theinterceptor" class= "Com.sw.TheInterceptor1" >
<param name= "Test" >swxctx</param>
</interceptor>
</interceptors>
With the action configuration (using interceptors):
</result>
<interceptor-ref name= "Theinterceptor1" ></interceptor-ref>
</action>
In-depth analysis of struts-default.xml * * *
After customizing the Interceptor, Defaultstack will no longer be useful and needs to be defined by itself
2 You can inherit abstractinterceptor when defining interceptors (this class implements the Interceptor interface and implements the Init and Destory methods), and then implements its abstract method interceptor.
The 3 method filters the Interceptor (interceptor that can intercept the specified method)->methodfilterinterceptor (abstract class)-> can specify
Includemethods-> represents a method that requires blocking:
<interceptor-ref name= "Theinterceptor3" > <param name= "includemethods" >execute</param>
</interceptor-ref>
As indicated above, the execute is intercepted.
<param name= "Excludemethods" >myExecute</param>
Indicates no Myexecute interception (interceptor not executed, not myexecute not performed)
If the Includemethods parameter is not specified and the Exincludemethods parameter is not specified, then all methods are intercepted, meaning that all methods are considered to be of includemethods type.
If only the includemethods is specified, then only the method in the Includemethods is intercepted, so that his will not be disturbed.
(11)
Preresultlistener (inherited from Actioninvocation)
Do login Processing
Interceptor Stack: Multiple interceptors are defined together
Struts.xml can place multiple packages.
Can be divided into multiple configuration sub files.
(12)
Struts.xml
Abstract-> represents the package that is currently wrapped as abstract.
Abstract= "true";
The Struts-default package is abstract, so it needs to be inherited.
Namespace
Path partitioning, module partitioning
(13)
File Upload
1 using servlet
Follow the principles:
Basic form->
<form action= "fileuploadresult.jsp" method= "post" enctype= "Multipart/form-data" >
username:<input Type = "text" name= "Useranme" >
file:<input type= "file" name= "file" >
<input type= "Submit" value= "Upload" >
</form>
Read:
<%
InputStream is=request.getinputstream ();
BufferedReader br=new BufferedReader (New InputStreamReader (IS));
String Buffer=null;
Read while
(null!= (Buffer=br.readline ())) {
out.print (buffer+ "<br/>");
}
Br.close ();
Is.close ();
%>
File upload is, you must set the method property to the Post,enctype property must be set to Multipart/form-data
Using the servlet requires the use of the Apache component, Commons->fileupload
Select multiple Files:
File:<input type= "File" name= "file" multiple size= "><br/>"
Select File Upload interface:
<form action= "Uploadservlet" method= "post" enctype= "Multipart/form-data" >
username:<input type= "text" Name= "Useranme" ><br/>
file:<input type= "file" name= "file" multiple size= "no" ><br/>
File2:<input type= "File" name= "File2" >
<input type= "Submit" value= "Upload" >
</form>
Use action to process:
public string Execute () throws Exception {/
/TODO auto-generated Method stub
//For File upload processing
String root= Servletactioncontext.getrequest (). Getrealpath ("/upload");//file storage path
inputstream is=new fileinputstream (file); /The input stream file
destfile=new file (root,filefilename);//Files
outputstream os=new fileoutputstream (destfile);//output stream
byte[] buffer=new byte[400];
int length=0;
while ((Length=is.read (buffer))!=-1 {
//write
os.write (buffer, 0, length);
}
Is.close ();
Os.close ();
return "SUCCESS";
}
STRUTS2 is actually implemented in two steps when uploading files:
(1) The file uploaded by the client is first saved to the directory specified by the Struts.multipart.saveDir (struts.properties) key, if the corresponding directory does not exist, then it is saved to the Javax.servlet.context , tempdir in the directory specified by the environment variable.
(2) The member variable of the file type defined in the action file actually points to a temporary file in the temporary directory and then writes the temporary file to the specified server-side directory on the server side via IO.
Upload Multiple files:
File1:<input type= "File" name= "file" ><br/>
File2:<input type= "File" name= "file" ><br/>
Name is the same.
OGNL (object graph navigation Language): Objects Graph Navigation language
Control Upload Size:
Struts.properties:
struts.multipart.maxsize=1048576000
or struts.xml:
<!--specify upload file size-->
<constant name= "struts.multipart.maxSize" value= "1048576000" ></constant>
Priority level:
Struts.properties>struts.xml
File Download:
Action:
public class Downloadaction extends Actionsupport {
//File Download public
InputStream getdownloadfile ()
Servletactioncontext.getservletcontext (). getResourceAsStream ("/upload/upload.txt");
@Override public
String execute () throws Exception {
//TODO auto-generated a stub return
"SUCCESS";
}
}
Struts.xml configuration:
<!--Download-->
<action name= "DownloadFile" class= "com.sw.struts2.DownloadAction" >
< Result type= "Stream" >
<param name= "contentdisposition" >attachment;filename= "Upload.txt" </param >
<param name= "InputName" >downloadFile</param>
</result>
</action>\
Resolve file name garbled problem:
Chinese garbled processing (file name is Chinese) this.filename=new String (this.filename.getBytes ("GBK"), "8859_1");
(14)
Annotations
STRYTS2 can be implemented using the Struts2-convention-plugin-2.3.30.jar plug-in for annotations based configurations.
Action Head:
@ParentPackage ("Struts-default")
@Action (value= "Login", result={@Result (name= "SUCCESS", location= "result.jsp", type= "", Param= "")), @Result ...}
@InterceptorRef (value= "intercept name")
@InterceptorRefs ({@Interceptor (""), @Interceptor ("")})
@ExceptionMapping (Exception)
@ExceptionMappings {@ExceptionMapping (), @ExceptionMapping ()}
Custom Interceptor: Can be defined in Struts.xml, in action reference
(15)
Parsing XML and JSON methods
Ajax Asynchronous communication
Json->
(1) Custom JSON strings
(2) using Plug-ins
(16)
(1) Action (important)->exxcute
(2) filters (filter)
(3) Valuestack
(4) Actionproxy (Action proxy object)
Actioninvocation
Source code and Help document analysis