Struts2 dynamic call + Servlet filter + struts2 interceptor, struts2servlet

Source: Internet
Author: User

Struts2 dynamic call + Servlet filter + struts2 interceptor, struts2servlet

On weekends, it's really hard to get bored ......

This article is based on the complete s2sh project. If you are not familiar with the construction of the s2sh project, please refer to the following articles:

In eclipse, the struts2 project is built based on tomcat-7.0.82. In eclipse, the struts2 project is built based on the Integrated spring + hibernate. The configuration of the S2SH project is simplified by using the full annotation method. The first simple explanation of the configuration file is as follows: configure the following three items in the s2sh project: 1. dynamic call of struts2:

If dynamic call is not configured, we can only call one default excute () method in one action. Every request calls a method requires an action, which will increase the development workload, therefore, this is just needed.

2. Servlet Filter

Servlet filters can be understood as an independent web component that intercepts requests and responses to view, extract, or operate on the data being exchanged between the client and the server in some way. Filters are Web Components that typically encapsulate some functions. These functions are important but not decisive for processing client requests or sending responses.

3. struts2 interceptor

The struts2 interceptor is its core. The interceptor allows us to complete some operations before or after the action and result are executed, such as permission verification. Unlogged users are not allowed to access certain resources.

Differences between filters and interceptors

The first filter is based on the basic operations of servlet. it is a local filter that can be filtered to all requested resources, packets, CSS, and other files. The Interceptor is based on struts2 and can only be filtered to the action Request Method.

Similar to each other, the implementation of both can be seen as modular and can be understood as a strategy of aop.

Configuration steps: Step 1: Configure struts2 dynamic call

The <struts> </struts> node in the struts. xml configuration file declares that struts2 supports dynamic calling and specifies the matching characters to be handed over to struts2 for processing. The Code is as follows:

<! -- Let struts2 support dynamic method call to call multiple methods in action with an exclamation point --> <constant name = "struts. enable. DynamicMethodInvocation" value = "true"/> <! -- All requests matching *. action and do are processed by struts2 --> <constant name = "struts. action. extension" value = "action, do"/>
Step 2: configure the servlet Filter

To configure the Filter, we need to implement the servlet Filter interface and its abstract methods: destroy (), doFilter (ServletRequest arg0, ServletResponse arg1, FilterChain arg2), and init (FilterConfig arg0 ), the three methods are initialization, filtering, and destruction. Then we need to go to the web. xml to declare the custom filter, because the web. xml is the servlet's first container. The custom filter code is as follows:

Package wjt.com. test. filter; import java. io. IOException; import javax. servlet. filter; import javax. servlet. filterChain; import javax. servlet. filterConfig; import javax. servlet. servletException; import javax. servlet. servletRequest; import javax. servlet. role; public class CharacterFilter implements Filter {@ Override public void destroy () {// TODO Auto-generated method stub} @ Override public void doFilter (ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {System. out. println ("filter... "); arg2.doFilter (arg0, arg1) ;}@ Override public void init (FilterConfig arg0) throws ServletException {// TODO Auto-generated method stub }}

The modified web. xml is as follows:

<? Xml version = "1.0" encoding = "UTF-8"?> <Web-app xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xsi: schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id = "WebApp_ID" version = "3.0"> <display-name> SSHDemo </display-name> <! -- Spring Listener Configuration starts --> <! -- Spring listener: provides instances (IOC) --> <context-param> <param-name> contextConfigLocation </param-name> <param-value> classpath: applicationContext. xml </param-value> </context-param> <listener-class> org. springframework. web. context. contextLoaderListener </listener-class> </listener> <! -- Filter invalid characters. The configuration must be at the beginning --> <filter-name> characterFilter </filter-name> <filter-class> wjt.com. test. filter. characterFilter </filter-class> <init-param> <param-name> encoding </param-name> <param-value> UTF-8 </param-value> </init- param> </filter> <filter-mapping> <! -- Specify filter ing --> <filter-name> characterFilter </filter-name> <url-pattern>/* </url-pattern> </filter-mapping> <! -- Submit the request path to struts for filtering --> <filter-name> struts2 </filter-name> <filter-class> org. apache. struts2.dispatcher. ng. filter. strutsPrepareAndExecuteFilter </filter-class> </filter> <filter-mapping> <filter-name> struts2 </filter-name> <url-pattern>/* </url-pattern> </filter-mapping> </web-app>

 

Step 3: configure the struts2 interceptor

Struts2 has multiple interceptor interfaces. The Root Interface also contains three Abstract METHODS: initialization, interception, and destruction. Here we inherit the abstract class MethodFilterInterceptor, the initialization and destruction methods have been implemented in this class. Therefore, you only need to implement the abstract method of the interception operation. Of course, if there are initialization and destruction operations, we can also define the implementation that overwrites the method of the parent class with the same name. The Code is as follows:

Package wjt.com. test. interceptor; import org. apache. struts2.ServletActionContext; import com. opensymphony. xwork2.ActionInvocation; import com. opensymphony. xwork2.interceptor. methodFilterInterceptor;/*** custom method interceptor ** @ author Together **/public class MethodInterceptor extends MethodFilterInterceptor {/*****/private static final long serialVersionUID = 1L; @ Override protected String doIntercept (ActionInvocation arg0) throws Exception {System. err. println ("Interceptor effective... "); String action = (String) ServletActionContext. getRequest (). getSession (). getAttribute ("action"); System. out. println ("action:" + action); StringBuffer requstPath = ServletActionContext. getRequest (). getRequestURL (); System. out. println ("requstPath:" + requstPath); System. err. println ("Interceptor ends... "); return arg0.invoke ();}}

Configure the struts. xml file to make the interceptor take effect. The configuration is as follows:

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE struts PUBLIC "-// Apache Software Foundation // DTD Struts Configuration 2.3 // EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <! -- This must be consistent with the struts2 version --> <struts> <! -- Notify Struts2 to use Spring to create objects during runtime --> <constant name = "struts. objectFactory" value = "spring"/> <! -- Let struts2 support dynamic method call to call multiple methods in action with an exclamation point --> <constant name = "struts. enable. DynamicMethodInvocation" value = "true"/> <! -- All matches *. action and do requests are all processed by struts2 --> <constant name = "struts. action. extension "value =" action, do "/> <package name =" default "namespace ="/"extends =" struts-default "> <interceptors> <! -- First define the interceptor --> <interceptor name = "myInterceptor" class = "wjt.com. test. interceptor. MethodInterceptor"> <! -- Specify the parameters that the system initializes to the interceptor --> <! -- <Param name = "hello"> Wu Jingtao </param> --> </interceptor> <! -- Add it to the interceptor stack you set --> <interceptor-stack name = "myStack"> <interceptor-ref name = "myInterceptor"> </interceptor-ref> <interceptor- ref name = "defaultStack"> </interceptor-ref> </interceptor-stack> </interceptors> <! -- Change the default interceptor of the system to its own default interceptor, and a system can only have one default interceptor, in this way, the interceptor stack will be applied to all actions by default --> <default-interceptor-ref name = "myStack"/> </package> </struts>

Configure the action Implementation class. If the request to the action Implementation class is processed by the custom interceptor, we need to add @ ParentPackage ("default") to it "), this annotation is added to the top of the action class name and exists as the first annotation of action.

Test:

The three configurations of the topic are complete. After the project is started and the action is requested, the configuration is successful as follows:

 

Only simple configuration is provided here. It is best for readers to use it in the early stage of understanding the principle. I have just graduated from the university, but I still have a deep understanding of the principle and have not yet reached the level of stating the principle, if there is anything unreasonable, please point it out.

Related Article

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.