Struts2 notes (2)--struts value/jump/interceptor/annotations, etc.

Source: Internet
Author: User

How to accept the parameters of the page passed in 1.action
第一种情况:(同名参数) 例如:   通过页面要把id=1 name=tom age=20这三个参数传给action 1.action里面定义三个成员变量id name age,这个三个变量的名字一定要和所传变量的名字一致. 2.提供get/set方法 3.将来页面把这三个参数传过来的时候,struts2框架会自动的帮我们把这个三个参数值放action中的三个属性里面.(同时还做了类型的转换) 注意:这个工作其实是由defaultStack这个拦截器栈里面的拦截器来完成了. 传值完成之后,我们只要在execute方法中去直接使用就可以了,不需要做其他事情.第二种情况:(域模型)在接收到页面传值的时候,还可以让struts2框架直接帮我们把这些接收到的值封装到一个javabean对象里面. 1.action中定义一个User类型的变量user,User类中有三属性值,id name age,同时User类中还有get/set方法 2.action中给这个user属性提供get/set方法 3.页面向action传值的时候,参数的名字要写成user.id=1  user.name=tom  user.age=20 将来接收到这个参数值以后,struts2框架会帮我们去创建一个User对象,并且把所传参数的三个值封装到对象的三个属性里面,最后把这个封装好的对象放到action的user属性中第三种情况:(模型驱动)    class TestAction implements ModelDriven<User>{        @Override        public User getModel() {            if(user == null){                user= new User();            }            return user;        }    }
How to jump in 2.action
<result name="" type="">..</result>name属性指的是跳转的名字(默认值success),也就是action返回的字符串type属性指的是跳转的类型(默认值dispatcher),常用到的跳转类型有已下四种:

Internal jump
Dispatcher (action->jsp)
Jump from inside a server inside an action to a page. This is the default value for the Type property.

chain(action->action)   从一个action里面服务器内部跳转到另一个action中.   <result type="chain">methodTest1</result>   或者:    <result type="chain">        <param name="method">方法名</param>        <param name="actionName">action名</param>        <param name="namespace">命名空间</param>    </result>

External jump
Redirect (action->jsp)
From within an action, the client redirects to a page.
/success.jsp

redirectAction(action->action)   从一个action里面客户端重定向到另一个action里面   1.同一个package下面的action跳转:   /test下面的action跳转到/test下面的action   <result type="redirectAction">methodTest1</result>   或者   <result type="redirectAction">    <param name="actionName">methodTest1</param>    <param name="namespace">/test</param>   </result>   2.不同的俩个package下面的action跳转   /test下面的action跳转到/user下面的action  <result type="redirectAction">    <param name="actionName">mytest</param>    <param name="namespace">/user</param>  </result>
3. Configure a global jump.
<global-results>    <result name="success">/success.jsp</result>    <result name="error">/error.jsp</result></global-results> 作用:  将来在其他任何action中,如果有需要返回success字符串跳转到success.jsp或者返回error字符串跳转到error.jsp的时候,就不需要在单独定义,因为已经把这个俩个跳转定义成了全局的跳转,对当前package里面的所有action都起作用.同时还可以在某一个action中再重新定义一下这个俩个跳转,这个时候全局跳转就不会对这个action起作用了.
4. Configure the default action in the package
<default-action-ref name="methodTest1"></default-action-ref>作用:如果地址栏中访问到了当前package下面一个不存在的action的时候,正常情况下是会直接报错的,错误信息显示这个action找不到,但是我们一旦配置了这个默认的action之后,那么再去访问一个不存在的action就不会报错了,而是直接就去访问这个默认的action.这个默认的action需要我们在当前package里面定义出来,并且在<default-action-ref>标签中引用一下.注意:访问某个package下面action的时候有几种错误的情况:   1.action找不到   2.action找到了但是action对应的类找不到.   3.action找到了,对应的类找到了,但是在类中要执行的方法没找到。   4.action找到了,对应的类找到了,类中要执行的方法找到了,但是方法返回的字符串在<result>标签中没有定义.   5.action找到了,对应的类找到了,类中要执行的方法找到了,方法返回的字符串在<result>标签也定义了出来,但是要跳转的页面没有找到.
5. Transfer values from action to page
In action, you can still use the request, session, application to the page as before in the servlet, and in addition, there are two unique ways of passing the value in the action: Valuestack Actioncontext1.valuestack is an interface: Com.opensymphony.xwork2.util.ValueStack Actioncontext is a class: Com.opensymphony.xwork2.ActionContext We can use these two types of objects to take the values from the action to the page. 2. On the page, we can see the value of the action passed to the page by a struts2 tag. : <s:debug/> page Introduction Tag library: <% @taglib uri= "/struts-tags" prefix= "s"%>3. When the current action jumps, the struts2 frame automatically puts the actio The N objects themselves are placed in the two objects Valuestack and Actioncontext, <s:property value= "Customer.username"/> Then struts2 the frame and then pass the two objects to the page, So we can just go through the two objects on the page and get the values we put in. (In the Debug tab of the page, you can see that the struts framework puts the action inside the two objects) 4. In addition to the struts framework automatic values such as Valuestack and Actioncontext, we can also manually put values inside these two objects. (In the Execute method, you get the two objects and you can put values in it.)   5. How to get Valuestack and Actioncontext object to get Actioncontext object: Actioncontext ac = Actioncontext.getcontext ();    Get Valuestack object: Valuestack vs = Ac.getvaluestack (); 6. Put values into the Actioncontext object to the active value in AC and vs: Ac.put (string,object);   Ac.put ("Hello", "World"); Put a value in the Valuestack object: User user = new USer (); Vs.push (user);    7.ValueStack features (value stack) 1. After we put an object in VS, we can't get the object from this vs, but we can get the property and the property value directly inside the object. 2. When you take a value from VS, it is taken from the property name in VS, and gets the value of the property value column. (The VS view in Debug can look at these columns) so if we pass a value to the page through VS, we can't just put the value in VS, because it doesn't, we should put the value in an object's property, and then put the object in VS,    At this point, you can get the properties of this object through VS, which is the value we want to pass. 3. Each time the browser sends a new request, a new Valuestack object is generated, and the last Valuestack object is lost and cannot be found.    (similar to the characteristics of the request object previously studied) 4. Each time a new Valuestack object is created, the object is placed inside the Actioncontext. 8.ActionContext features 1. When the value is placed in the AC, it is stored in the form of a key-value, and the key is a string type.    Value is the object type, and the value is obtained by key. The 2.struts framework defaults to a large number of objects (data) stored in this object, including request, session, application, Valuestack, parameters, etc. 3. Each request creates a new Actioncontext object (the address value of the AC is printed each time it is requested) 9. Note: When using VS and AC values, use the server internal jump mode.

The client sends a request to the ACTION,STRUTS2 framework to create two objects:
Valuestack objects and Actioncontext objects, the STRUTS2 framework places the currently executing action object into the Valuestack object and the Actioncontext object, while the action executes the jump. The Debug tab in the page can be used to put the action object inside the two objects. So eventually we can get the property value (Get/set method) from the action by Valuestack object or Actioncontext object on the page.

6. Accessing the Web element in action (Request session application)

1. In the STRUTS2 framework, each of these three objects has two types: the original type map type (This object is in Actioncontext)

2. Original type: (refers to the type of object previously used in the servlet)
HttpServletRequest Request
HttpSession session
ServletContext Application
Map Type:
Map

7. Get the value of the action passed in the page

There are two things that need to be used in the page-value approach provided by the STRUTS2 framework: STRUTS2-Frame tags, ognl expressions
Note: We can also use JSP built-in object values that have been evaluated using the JSTL tag +el expression.
The values that can be used in STRUTS2:
1.jsp built-in object values
2.jstl label +el expression value
3.struts2 label +OGNL expression
Note: The OGNL expression can only be written in the struts2 tag attribute, in this case we first use a struts2 tag: the function of this tag is to output a value to the page.
For example:

1) taking values from Valuestack and Actioncontext

 1. Take the value from the Valuestack. Note that the value in this Value property, name, is actually the ONGL expression//This represents a property value from Valuestack named name <s:property value= "name"/> <s: Property value= "User"/> <s:property value= "user.id"/> <s:property value= "User.Name"/> Note: from Valuestack   When taking a value, if there are two identical values in the Valuestack, we can only fetch the top value (the top value in VS in the Debug tab) (in fact, the way to take the value of special processing or can be taken to the following property value) 2. From the Actioncontext. To use the OGNL expression, pass the key in AC to take the value relative to. When you take a value, you need to add a symbol: # <s:property value= "#action. Name"/><br> <s:property value= "#msg"/><br> <s :p roperty value= "#user"/><br> <s:property value= "#user. Id"/><br> <s:property value= "# User.Name "/><br> <s:property value=" #user. Age "/><br> parameters 3.ActionContext, attr, Request, session, application and other key values.   (These are all keys in AC) the value of the parameters corresponds to the parameters transmitted by the client. The receiving client came with a parameter value named name <s:property value= "#parameters. Name"/><br>//Get the value in Request <s:property value= "# Request. MyName "/><br>//Get the value in session  <s:property value= "#session. MyName "/><br>//Get the value in application <s:property value=" #application.   MyName "/><br>//default from request, session, appliction in order to take the value, take the direct output, do not take even. <s:property value= "#attr. MyName "/><br>

2) You can also use the previous method to extract values from the request, session, and application.
Note: If we use the request through key to fetch value, will first in request inside, request inside find not to valuestack inside. Because Valuestack is also placed in the request by default. But the session and the application do not have the same characteristics as the request.

Using JSP script code to take a value
<%=request.getattribute ("name")%>
<%=session.getattribute ("name")%>
<%=application.getattribute ("name")%>

Use the EL expression to take a value:

    ${requestScope.MyName }    ${requestScope.name }     ${sessionScope.MyName }     ${applicationScope.MyName }     ${MyName }     ${name }
Interceptors in the 8.STRUT2 Framework (Interceptor)

1. What is an interceptor (interceptor)
Interceptors are a Java class that is provided in the STRUT2 framework.
Effect: 1. Can intercept requests to access an action
2. Add a new rich feature to this action (upload, parameter Auto-Receive, type auto-convert, etc.) after configuration, indicate which interceptor to intercept which action or action, So that the interceptor will intercept our action. Each interceptor can add a new function to our action.

2. How interceptors (Interceptor) work
A. Class with an interceptor (struts2 frame comes with or a class that we define ourselves)
B. Configure the Interceptor class in the configuration file.
C. Indicate which or which action the interceptor will intercept.
D. The client sends a request to access an action that is intercepted by the interceptor
E. This request is intercepted by the STRUTS2 filter first, which checks if the request is the action of the request, and if it is an action, then checks whether the action is intercepted by a defined interceptor, If so, give this request to the interceptor to handle it.

3. How to customize an interceptor
The STRUTS2 framework has written a number of interceptors (in Struts2 's core jar package) and also configures these interceptors in the configuration file (in Struts-default.xml).
In addition, we can write our own interceptors.

  To write an interceptor, first implement an interface: Com.opensymphony.xwork2.interceptor.Interceptor For example: public class Myinterceptor implements INTERCEP        tor{public void Destroy () {System.out.println ("in Destory () of Myinterceptor");        } public void, init () {System.out.println ("in Init () of Myinterceptor"); }//Intercept to access action when calling this method public String intercept (Actioninvocation ai) throws Exception {Syste            M.out.println ("before ...");  Ai.invoke () is actually helping us to invoke the method that will be executed in action, such as the return value of the Execute Method//ai.invoke () is actually the string s that is returned by the method in the action:            Ai.invoke ();            System.out.println ("After ...");        return s; }} and then configure the Interceptor class in the Struts.xml file: <interceptors> <interceptor name= "Myinterceptor" class= "com.briup  . Web.interceptor.MyInterceptor "></interceptor> </interceptors> finally indicate which action the interceptor works on: <action Name= "MyTest" > <result>/index.jsp</result> <interceptor-ref name= "myinterceptor" ></interceptor-ref> </action> 

4. Interceptor Stack
When the current action needs to be intercepted by multiple interceptors, normally we need to refer to the multiple interceptors to be used in this action, but we can use an interceptor stack to contain the interceptors and then refer to the interceptor stack directly in action.
1. An interceptor stack can contain multiple interceptors
2. An interceptor stack can also contain other interceptor stacks
3. Define the Interceptor or interceptor stack to be in the tag
For example:

    <interceptors>        <Interceptor name= "myinterceptor" class=" Com.briup.web.interceptor.MyInterceptor "></Interceptor>        <interceptor-stack name="Mystack">            <!--This is an interceptor of our own definition--            <interceptor-ref name="Myinterceptor"></interceptor-ref>            <!--This is an interceptor defined in the Struts-default.xml file--            <interceptor-ref name="params"></interceptor-ref>            <!--This is one of the interceptor stacks defined in the Struts-default.xml file--            <interceptor-ref name="Basicstack"></interceptor-ref>        </interceptor-stack>      </interceptors>
5. Default Interceptor/Interceptor stack in a package, we can declare an interceptor or interceptor stack as a default interceptor/interceptor stack: All actions in the package will be intercepted by this default interceptor/interceptor stack. For example: Mystack is an interceptor or interceptor stack <default-interceptor-ref name= "Mystack" ></default-interceptor-ref> Note: In general, I Any action written by them will be intercepted by a stack of interceptors called Defaultstack, which contains more than 10 interceptors, These interceptors provide a lot of functionality to our action. Because we write all the package is directly or indirectly inherited a Struts-default.xml file named Struts-default,   In the Struts-default package, the interceptor stack, called Defaultstack, is configured as a default interceptor stack, so our packages inherit this configuration, and all our actions are normally intercepted by Defaultstack. But if we once indicated that an action was intercepted by an interceptor/interceptor stack that we wrote, the action would not be intercepted by defaultstack. So we can declare it proactively in action. This action is intercepted by Defaultstack, or the Defaultstack is added to our custom interceptor stack (the interceptor stack can contain the interceptor stack) between the 6.package inheritance we can define a package specifically, In this package we only do the interceptor/interceptor Stack definition: <!--in this package, we only define interceptors/interceptor stacks---<package name= "Myinter" extends= "struts-def Ault "namespace="/"> <interceptors> <interceptor name=" Myinterceptor "class=" com.briup.web.intercept Or. Myinterceptor "></interceptor> <intErceptor-stack name= "Mystack" > <interceptor-ref name= "myinterceptor" ></interceptor-ref> <!--This is an interceptor stack defined in the Struts-default.xml file--<interceptor-ref name= "Defaultstack" ></interceptor- Ref> </interceptor-stack> </interceptors> <!--declaring the default interceptor/Interceptor Stack--<!--all actions in the current package will be the Mystack interceptor-<!--all of the actions in the other packages of the current package will also be intercepted by this mystack-<default-interceptor-ref name= "Mysta CK "></default-interceptor-ref> </package> then we can get other packages to inherit our Myinter package, so     The action in the other package will be intercepted by the default interceptor stack Mystack in our Myinter package. Note: It is important to ensure that the action is at least intercepted by defaultstack the interceptor stack. 7. Note: Only one interceptor is defined in the Struts.xml, and the interceptor is not initialized and destroyed. The STRUTS2 framework can be used to initialize the interceptor after it has been referenced in action, but it cannot be destroyed, and if it is to be destroyed, it is necessary to refer to the interceptor in an interceptor stack.
9. Comparison of interceptors (interceptor) and filters (filter)
 相同点:   1.都是一种java类   2.都能拦截客户端发给服务器端的请求   3.拦截到请求之后都可以做一些相应的处理,最后还可以把这个请求放行.   4.都需要实现各自相应的接口以及在相应的配置文件中配置. 不同点:   1.拦截器(interceptor)是struts2框架中的定义的,过滤器(filter)是web里面的对象,是J2EE标准里面定义的.   2.拦截器(interceptor)只会拦截器访问action的请求,过滤器(filter)能够拦截所有请求.   3.拦截器(interceptor)定义在struts.xml文件中,过滤器(filter)定义在web.xml文件中.   4.拦截器(interceptor)对象的创建、调用、销毁是struts2框架负责的,过滤器(filter)对象的创建、调用、销毁服务器负责的.我们自己定义的filter能不能拦截Struts2框架中的action  1.可以拦截  2.需要在web.xml文件中把我们自己的filter配置在struts2的filter的上面才可以.  因为web.xml文件中filter配置的先后顺序控制filter起作用的顺序,同时如果struts的filter先拦截到访问action的请求后,不会把这个请求交给下面的filter,而是交给了他它内部的拦截器(interceptor)了,但是如果我们自己filter拦截到请求之后,还是依然会交给下一个filter,也就是交给struts2的filter.
Struts2 annotation Method (Annotation)
1. Introduction of the jar package Struts2-convention-plugin-2.3.4.12.struts.xml <constant name= "that supports the development of STRUTS2 framework annotations"    Struts.convention.action.suffix "value=" action "/>2.struts2 use annotation development need to follow some specifications: 1) Action must inherit the Actionsupport parent class; 2) The package name where the action is located must end with action.    3.package-info.java @Namespace ("/") @ParentPackage ("Struts-default") package com.briup.action.manager;    Import Org.apache.struts2.convention.annotation.Namespace; Import org.apache.struts2.convention.annotation.parentpackage;3.action commonly used annotations: Namespace annotation 1. By defining the @Namespace on Actionclass ("/custom") 2. Define @org by Package-info.java. Apache.struts2.convention.annotation.Name    Space ("/custom") package com.example.actions; Action Annotation 1.    @Action (interceptorrefs={@InterceptorRef ("Validation"), @InterceptorRef ("Defaultstack")})        2. Chain @Action ("foo") public String foo () {return ' bar ';      } @Action ("Foo-bar") public String Bar () {      return SUCCESS;    } Result Annotation 1. Globally, the entire class can access 2. Local, a method can access the @Results ({@Result (name= "Failure", location= "fail.jsp") }) public class HelloWorld extends Actionsupport {@Action (value= "/different/url", results={@Result (name= "succ ESS ", location=" http://struts.apache.org ", type=" redirect ")}) public String execute () {return S        uccess; }} can pass parameters: results={@Result (name= "Success", type= "Httpheader", params={"status", "5 XX "," ErrorMessage "," Internal Error "})}

Struts2 notes (2)--struts values/jumps/interceptors/annotations, etc.

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.