Struts2 scattered notes

Source: Internet
Author: User

Struts2-Action:
Set up the myeclipse framework, set the directory of server/tomcat in window/prefrence, and set the JDK path on the Java tab.

Struts operating mechanism:
The URL request is sent to Tomcat through the HTTP protocol (assume that our URL is http: // localhost: 8080/$ webapplication name $/Hello ),
Based on the requested webapplication in the URL, submit it to the corresponding webapplication for processing, and then refer to its Web. xml configuration, which includes:
...
<Filter>
<Filter-Name> struts2 </filter-Name>
<Filter-class> org. Apache. struts2.dispatcher. Ng. Filter. strutsprepareandexecutefilter </filter-class>
</Filter>
...
Accepted by org. Apache. struts2.dispatcher. Ng. Filter. strutsprepareandexecutefilter. It will refer to the namespace of Struts. XML, and then according to the corresponding action and result,
Forward the request to the corresponding JSP file.

Struts separates requests from views.

Struts. xml:
<Struts>

<Constant name = "struts. devmode" value = "true"/>
<Package name = "Front" extends = "struts-Default" namespace = "/Front"> // The package name must be unique; if the namespace is not empty, it must start with '/'. To access the action in this namespace, you must add this path in front of it.
<Action name = "Index"> ***
<Result>/namespace. jsp </result>
</Action>
</Package>

<Package name = "Main" extends = "struts-Default" namespace = "">
<Action name = "Index">
<Result>/namespace. jsp </result>
</Action>
</Package>

</Struts>

For example, to access the action with the *** name = "Index", the URL is http: // localhost: 8080/$ webapplication name $/Front/Index
Namespace determines the action access path. If this parameter is left blank, the default value is "". You can receive actions in all paths.
Namespace can be written as/,/XXX, or/XXX/yyy. The corresponding action access path is/index. action,/XXX/index. action, or/XXX/YYY/index. action.
The namespace should also be named by the module.

<Constant name = "struts. devmode" value = "true"/>
<Package name = "Front" extends = "struts-Default" namespace = "/">
<Action name = "Index" class = "com. bjsxt. struts2.front. action. indexaction1 "> // when requesting this action, find the corresponding class and execute () method in it. If the returned value is string, it is treated as an action.
<Result name = "success">/actionintroduction. jsp </result>
</Action>
</Package>

The response of a specific view can be determined by the user-defined action.
The specific method is to find the corresponding configuration item based on the returned string to determine the View content.
The implementation of specific actions can be a common Java class with the Public String execute method.
Or implement the Action interface.
However, the most common method is to inherit from actionsupport. The advantage is that you can directly use struts2 encapsulated methods.

There is a difference between struts1 and struts2: every action in struts2 is new, and struts1 is not. Therefore, 2 solves the thread synchronization problem.

The Path Problem in struts2 is determined based on the action path rather than the JSP path, so do not use the relative path whenever possible.
Although the Redirect method can be used, the Redirect method is not necessary.
The solution is simple and the absolute path is used in a unified manner. (Request. getcontextroot is used in JSP to obtain the webapp path)
You can also use myeclipse to specify the basepath:
<% // Obtain the root directory path
String Path = request. getcontextpath ();
String basepath = request. getscheme () + ": //" + request. getservername () + ":" + request. getserverport () + path + "/";
%>
<Base href = "<% = basepath %>"/> // set the root path of the link on the current page.

You do not have to execute the execute method when executing an action.
You can use method = to specify the method to be executed when configuring action in the configuration file.
You can also specify the dynamic method call DMI in the URL address (recommended ):! + Method name
The former produces too many actions, so it is not recommended.

Wildcards can be used to minimize the configuration, but the rule must be "better than the configuration ". Video 14.

There are three methods for passing parameters in an action.

Each element in the value Stack has a name and a value.

// Use JavaScript to specify the action submitted by the form.
<Input type = "button" value = "submit1" onclick = "javascript: Document. f. Action = 'login/login1'; document. f. Submit ();"/>

---- Loginaction1.java ----
Public class loginaction1 extends actionsupport {

Private map request;
Private map session;
Private map application;

Public loginaction1 (){
// Send this method to request (MAP type), session, and Application
Request = (MAP) actioncontext. getcontext (). Get ("request ");
Session = actioncontext. getcontext (). getsession ();
Application = actioncontext. getcontext (). getapplication ();
}

Public String execute (){
// Place values in the request, which can be accessed at the front-end.
Request. Put ("R1", "R1 ");
Session. Put ("S1", "S1 ");
Application. Put ("A1", "A1 ");
Return success;
}
Front-end page:
...
// Use <s: property value = "# request. R1"/> or <% = request. getattribute ("R1") %>
<S: property value = "# request. R1"/> | <% = request. getattribute ("R1") %> <br/>
<S: property value = "# session. S1"/> | <% = session. getattribute ("S1") %> <br/>
<S: property value = "# application. A1"/> | <% = application. getattribute ("A1") %> <br/>
...
---- Loginaction2.java ----
* *** The most common method ****

Package com. bjsxt. struts2.user. Action;

Import java. util. Map;

Import org. Apache. struts2.interceptor. applicationaware;
Import org. Apache. struts2.interceptor. requestaware;
Import org. Apache. struts2.interceptor. sessionaware;

Import com. opensymphony. xwork2.actioncontext;
Import com. opensymphony. xwork2.actionsupport;

Public class loginaction2 extends actionsupport implements requestaware, sessionaware, applicationaware {

Private Map <string, Object> request;
Private Map <string, Object> session;
Private Map <string, Object> application;

Public String execute (){
// It can be used directly (design idea IOC or DI), and an excuse for implementing requestaware, sessionaware, and applicationaware
Request. Put ("R1", "R1 ");
Session. Put ("S1", "S1 ");
Application. Put ("A1", "A1 ");
Return success;
}

// Use setrequest (Map <string, Object> request) to set the request
Public void setrequest (Map <string, Object> request ){
This. Request = request;
}

Public void setsession (Map <string, Object> session ){
This. Session = session;
}

Public void setapplication (Map <string, Object> application ){
This. Application = application;
}


}


Add the following statement to struts. XML to solve the Chinese encoding problem:
<Constant name = "struts. i18n. encoding" value = "GBK"/> <! -- Internationalization -->

<Include file = "login. xml"/> // contains another. xml file to the Struts. xml file.

<Default-action-ref name = "Index"> <* default-action-ref> defines the default action. If no action is found, go to the action under the package

Action summary:
1. The most reusable way to implement an action: Inherit from actionsupport
2. DMI dynamic method call +!
3. wildcard: * ASD * -- {1} {2}
* _ * -- {1} {2}
4. Method for accepting parameters (generally accepted by attributes or domainmodel)
5. Simple parameter verification addfielderror
Generally, struts2 UI labels are not applicable.
6. Access web elements
Map type
LOC (most commonly used)
Dependent on struts2
Original Type
Loc
Dependent on struts2
7. Include File Configuration
8. Default action Processing

The result type can be specified. The default value is DISPATCHER (the result page is displayed on the server, not action:
Redirect (cannot jump to action), chain (jump to an action), and redirectaction (jump to another action ).
The above four are the most commonly used, and the first two are the most commonly used. Freemarker, httpheader, stream, velocity, xsit, plaintext, tiles, and so on.
Client jump and server jump-video 27
Dispatcher and chain are server-side redirects, while redirect and redirectaction are client-side redirects.

The chain type jump to another action requires parameters:
<Result type = "chain">
<Param name = "actionname"> aasdafa </param> // specify the action name.
<Param name = "namespace">/asdasd </param> // specify the namespace of the action
</Result>

Global-results is used to process the total result set in the package, and extend is used to inherit global-results from other packages.

Specify result dynamically: You can specify a string parameter in the Action Implementation class to point to the JSP page address, for example:
...
Private string R;

Public String execute () throws exception {
If (type = 1) r = "/user_success.jsp ";
Else if (type = 2) r = "/user_error.jsp ";
Return "success ";
}
...
In struts. XML,
...
<Action name = "user" class = "com. bjsxt. struts2.user. Action. useraction">
<Result >$ {r} </result>
</Action>
...
To determine the display page of the result, because the parameters in the action are stored in the value stack.
Directly use the following in index. jsp:
<Li> <a href = "User/user? Type = 1 "> return success </a> </LI>
<Li> <a href = "User/user? Type = 2 "> error returned </a> </LI>
To pass Parameters in the Action Implementation class.


If there is a server jump in a request, all actions before and after the jump are public value stacks, so no parameters need to be passed between each action.
However, if the parameters passed to the JSP page are not stored in the value stack, you can only use the value in actioncantext.
...
<Action name = "user" class = "com. bjsxt. struts2.user. Action. useraction">
<Result type = "Redirect">/user_success.jsp? T =$ {type} </result>
</Action>
...

...
From valuestack: <s: property value = "T"/> <br/> // value from the value Stack
From actioncontext: <s: property value = "# parameters. t"/> // value from actioncantext
...

Ognl (Object grapg Navigation language) expression:
A parameter must be passed for the action class to construct the (new) object. At this time, there must be an empty constructor.
You can also construct the object directly in the class without passing parameters.

To access static methods, you must set the following statement in struts. xml:
<Constant name = "struts. ognl. allowstaticmethodaccess" value = "true"> </constant>
Access static attributes and static methods:
<S: property value = "@ [email protected] ()"/>
<S: property value = "@ [email protected]"/>
"@ Class Name @ attribute (method )"
"@ Method (attribute)" -- only the methods and attributes of math can be accessed.

---- Ognl. jsp ----

<? XML version = "1.0" encoding = "gb18030"?>
<% @ Page Language = "Java" contenttype = "text/html; charset = gb18030"
Pageencoding = "gb18030" %>
<% @ Taglib uri = "/Struts-tags" prefix = "S" %>
<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb18030"/>
<Title> ognl Expression Language Learning </title>
</Head>
<Body>
<Ol>
<Li> common attribute of the action in the Access value Stack: username = <s: property value = "username"/> </LI>
<Li> common properties of objects in the Access value stack (Get Set Method): <s: property value = "user. age "/> | <s: property value =" User ['age'] "/> | <s: property value = "User [\" Age \ "]"/> | wrong: <% -- <s: property value = "User [age]"/> -- %> </LI>
<Li> Get Set Method: <s: property value = "cat. Friend. Name"/> </LI>
<Li> common method for accessing objects in the value Stack: <s: property value = "password. Length ()"/> </LI>
<Li> common method for accessing objects in the value Stack: <s: property value = "cat. miaomiao ()"/> </LI>
<Li> common method for accessing action in the value Stack: <s: property value = "m ()"/> </LI>
<HR/>
<Li> static access method: <s: property value = "@ [email protected] ()"/> </LI>
<Li> access static properties: <s: property value = "@ [email protected]"/> </LI>
<Li> static method for accessing the math class: <s: property value = "@ max (2, 3)"/> </LI>
<HR/>
<Li> constructor for accessing common classes: <s: property value = "new COM. bjsxt. struts2.ognl. User (8)"/> </LI>
<HR/>
<Li> access list: <s: property value = "users"/> </LI>
<Li> access an element in the list: <s: property value = "users [1]"/> </LI>
<Li> access the set of an attribute of an element in the list: <s: property value = "users. {age}"/> </LI>
<Li> access the specific value of an attribute set in the element list: <s: property value = "users. {age} [0] "/> | <s: property value =" users [0]. age "/> </LI>
<Li> access set: <s: property value = "dogs"/> </LI>
<Li> access an element in the Set: <s: property value = "Dogs [1]"/> </LI>
<Li> Access Map: <s: property value = "dogmap"/> </LI>
<Li> access an element in map: <s: property value = "dogmap. dog101 "/> | <s: property value =" dogmap ['dog101 '] "/> | <s: property value = "dogmap [\" dog101 \ "]"/> </LI>
<Li> access all keys in map: <s: property value = "dogmap. Keys"/> </LI>
<Li> access all values in map: <s: property value = "dogmap. Values"/> </LI>
<Li> access container size: <s: property value = "dogmap. size () "/> | <s: property value =" users. size "/> </LI>
<HR/>
<Li> projection (filter): <s: property value = "users .{? # This. Age = 1} [0] "/> </LI>
<Li> projection: <s: property value = "users. {^ # This. age> 1}. {age}"/> </LI>
<Li> projection: <s: property value = "users. {$ # This. age> 1 }. {age}"/> </LI>
<Li> projection: <s: property value = "users. {$ # This. age> 1 }. {age }= = NULL"/> </LI>
<HR/>
<Li> []: <s: property value = "[0]. username"/> </LI>

</OL>

<S: Debug> </S: Debug>
</Body>
</Html>

Projection (filter ):{? # This. Age = 1}, {^ # This. age> 1}, and {$ # This. age> 1} are filter conditions.
^ Indicates the first, and $ indicates the end.
<S: property value = "[0]. username"/> indicates the set from 0th to the end. When the server jumps, multiple actions are generated.


Struts2 labels can be divided into general tags, control tags, UI tags, Ajax tags, and the difference between $ # %.

1. General labels:
A) Property
B) Set
I. The default value is action scope, which puts the value in request and actioncontext.
Ii. Page, request, session, Application
C) bean
D) include (it is not recommended to support Chinese files. To include Chinese files, use JSP inclusion instead)
E) Param
F) debug

2. Control labels
A) if elseif else
B) iterator
I. Collections map enumeration iterator Array
C) Subset

3. UI tag
A) Theme
I. Simple XHTML (default) css_xhtml Ajax

4. Ajax tag
A) Supplement

5. Differences between $ # %
A) $ for i18n and Struts configuration files
B) # obtain the actioncontext Value
C) % resolve the original text attribute to ognl, which does not work for the attribute originally named ognl
I. See <s: Property and <s: Include

 

 


Naming rules:

1. Database Name:
Table naming (simple is beautiful ):
_ Table name, for example:
_ TOPIC)

Field Name:
Keep consistent with the attribute name (do not conflict with the database name whenever possible)
For example, Id property ID
Foreign key topicid

Database Name:
Use the project name


2. Class and file naming:
There are two ways to do this: 1. Split the module first and then the Level 2. Split the module first.
Hierarchical classification (the package names are all in lower case ):
Com. bjsxt. bbs. Action. model. Service

Action class ends with action, such as xxxaction. Java

JSP name :*_*

Namespace: used directly at the front end "/"
Use "/admin" in the background"

Package:
Front-end: aciton
Background: adminaction


Project development sequence:
1. Create an interface prototype
2. Create struts. xml
A. Confirm namespace
B. Confirm the package.
C. determine the action name. Empty Method
D. Confirm rssult
E. modify the original page and match the existing settings.
F. Test
G. Make plans
3. Create a database (or entity class)
4. Create a model layer
5. Create a service layer (hibernate)
Unit test with JUnit
6. Start Development


When a request arrives, it is filtered by the filter. When a specific action method is called, the interceptor adds something during the call.
(In fact, the interceptor is called first, the interceptor then calls action, then returns to the interceptor, and then returns to the filter)

I18n
In general editer, Chinese writing will be garbled.
International files can use the propertiesediter plug-in, where the written Chinese will be converted into a UTF-8 to save.

Struts2 can be internationalized in three ways:
Action-package-app level
It mainly uses apps and is effective for the entire project.


The actual execution process of struts2:
1. struts2flter accepts page requests
2. Call the serviceaction () method of dispatcher
3. Dispatcher creates an actionproxy object and calls its execute () method.
4. The execute () method also calls the invoke () method of actioninvocation.
5. The invoke () method calls the Interceptor () method of the first inerceptor object.
6. the Interceptor () method calls the invoke () method of the actioninvocation object.
7. The nvoke () method calls the Interceptor () method of the next inerceptor object.
8. Repeat until all inerceptor calls are completed. The actioninvocation object calls the execute () method of the most action class.

 

When multiple identical parameters are passed, you can use the collection container, but you need to use the generic type.
For example, the action class has attributes:
......
List <interst>; // do not use new
......

Use the token Interceptor to control repeated submission (rarely used)

Write your own converter:
Public class mypointconverter extends defaulttypeconverter {

@ Override
Public object convertvalue (object value, class totype ){
If (totype = point. Class ){
Point P = new point ();
String [] STRs = (string []) value;
String [] xy = STRs [0]. Split (",");
P. x = integer. parseint (XY [0]);
P. Y = integer. parseint (XY [1]);
Return P;
}
If (totype = string. Class ){
Return Value. tostring ();
}
Return super. convertvalue (value, totype );
}

}
Public class mypointconverter extends strutstypeconverter {



@ Override
Public object convertfromstring (MAP context, string [] values, class toclass ){

Point P = new point ();
String [] STRs = (string []) values;
String [] xy = STRs [0]. Split (",");
P. x = integer. parseint (XY [0]);
P. Y = integer. parseint (XY [1]);
Return P;


}

@ Override
Public String converttostring (MAP context, object O ){
// Todo auto-generated method stub
Return O. tostring ();
}

}

Three registration methods:
I. Local: XXXAction-conversion.properties
1. P (attribute name) = Converter
Ii. Global: xwork-conversion.properties
1. com. XXX. XXX (Class Name) = Converter
Iii. Annotation
D) if you encounter very troublesome ing Conversion
I. Request. setattribute ();
Ii. Session

 

 

 

 

 

 

 

 

 

 

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.