SPRINGMVC Interceptor Use

Source: Internet
Author: User

Source Address

Interceptor Interceptor

The interceptor is the first door of the URL request, and all requests go through the interceptor before interceptor entering controller ;
Below, an annotation method is used to intercept all requests that require login to be initiated and redirect illegal requests to the login interface

Basic configuration of XML files
<!--配置拦截器, 多个拦截器,顺序执行 --><mvc:interceptors>    <mvc:interceptor>        <!-- 匹配的是url路径, 如果不配置或/**,将拦截所有的Controller -->        <mvc:mapping path="/**" />        <!--resource不拦截-->        <mvc:exclude-mapping path="/asset/**"/>        <mvc:exclude-mapping path="/assets/**"/>        <!--聊天室websocket不拦截-->        <mvc:exclude-mapping path="/sockjs/websocket"/>        <mvc:exclude-mapping path="/websocket"/>        <bean class="com.iss.blog.interceptor.AccessControlInterceptor"/>    </mvc:interceptor>    <!-- 当设置多个拦截器时,先按顺序调用preHandle方法,然后逆序调用每个拦截器的postHandle和afterCompletion方法 --></mvc:interceptors><!-- 静态资源访问(不拦截此目录下的东西的访问)  --><mvc:resources location="/asset/"  mapping="/asset/**" /><mvc:resources location="/assets/"  mapping="/assets/**" />

Key implementationsHandlerInterceptorAdapter

Public abstract class Abstractinterceptor extends Handlerinterceptoradapter {/** * have publicpage annotations * @param h Andlermethod * @return */protected Boolean ispublicpage (Handlermethod handlermethod) {if (Handlermetho        D==null) return false;        Publicpage publicpage = handlermethod.getmethodannotation (Publicpage.class);        if (publicpage!=null) {return true;    } return false; }/** * Whether a request is AJAX request * @param request * @return */protected Boolean isajaxrequest (httpservletreques        T request) {String RequestType = Request.getheader ("X-requested-with");            if ("XMLHttpRequest". Equals (RequestType)) {System.out.println ("is AJAX request");        return true;            }else{System.out.println ("is not AJAX request");        return false;     }}} public class Accesscontrolinterceptor extends Abstractinterceptor {/** * The following paragraph refers to a piece of article, because the original text is not found, so the reference link is not affixed * Called before the business processor processes the request * if return false * from the current interceptor executes all interceptors aftercompletion (), and then exits the interceptor chain * If True * executes the next interceptor until the Some interceptors are executed. * Then execute the intercepted controller * and then enter the Interceptor chain, * go back from the last interceptor to execute all posthandle () * and then go backwards from the last interceptor to execute all a  Ftercompletion () */@Override public boolean prehandle (HttpServletRequest request, httpservletresponse response, Object handler) throws Exception {if (handler instanceof Handlermethod &&ispublicpage ((handlermethod) ha        Ndler)) {return true;            } if (no login) {PrintWriter out = Response.getwriter ();            Out.append ("{' ResultCode ': 1012, ' resultmessage ': ' Wrong Request '}"); if (!isajaxrequest (Request)) {//Here the request is forwarded to the login interface Request.getrequestdispatcher ("/login"). Forward (req            Uest, response);        } return false;    }else return true; /** * After the business processor processes the request execution, the actions performed before the view is generated * can include data in the Modelandview, such as whenFormer time */@Override public void Posthandle (HttpServletRequest request, httpservletrespons E response, Object handler, Modelandview Modelandview) throws Exception {}/** * in dis Patcherservlet is called after fully processing the request, can be used to clean up resources, etc. * * When an interceptor throws an exception, all interceptors are executed back from the current Interceptor aftercompletion () */@Override Publi c void Aftercompletion (HttpServletRequest request, httpservletresponse response, Object Han Dler, Exception ex) throws Exception {}}

Definitions of annotations

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface PublicPage {    String value() default "";}

This way, in addition to the @RequestMapping @PublicPage representative, so that the route does not need to log on can be requested, otherwise you need to log in to request to
For example, login page:

@PublicPage@RequestMapping("/login")public  String loginPage(){    return "frontend/account/login";}
Must be an AJAX request to be accessible

SPRINGMVC Interceptor Use

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.