Spring Interceptor's Notes

Source: Internet
Author: User
Tags log log


The main contents of this article are as follows
What the interceptor can do.
What can interceptors do?
Logging: Logging For information monitoring, information statistics, calculation of PV (Page View) and so on.
Permission check: such as login detection;
Performance monitoring: Sometimes the system in a certain period of time inexplicably slow, through the interceptor before entering the processor to record the start time, after processing, record the end time,
In order to get the processing time of the request (if there is a reverse proxy, such as Apache can be automatically recorded);
General behavior: Read the cookie to get user information and put the user object into the request, so as to facilitate the subsequent use of the process, as well as extracting locale, theme information, etc.
Interceptors can be implemented as long as multiple processors are needed.
Opensessioninview: such as Hibernate, when entering the processor open session, after completion of the session closed.
The interceptor Nature is also AOP (aspect-oriented programming), meaning that all features that conform to crosscutting concerns can be put into the interceptor implementation.



How to Achieve 
1 Interceptor Interface


Public interface Handlerinterceptor {  
    boolean prehandle (  
            httpservletrequest request, HttpServletResponse Response,   
            Object handler)   
            throws Exception;  

    void Posthandle (  
            httpservletrequest request, httpservletresponse response,   
            Object handler, Modelandview Modelandview)   
            throws Exception;  

    void Aftercompletion (  
            httpservletrequest request, httpservletresponse response,   
            Object handler, Exception ex )  
            throws Exception;  
}   


Prehandle: Preprocessing callback method, implementation of processor preprocessing (such as login check), the third parameter is the response of the processor (such as the controller implementation of our previous chapter);
Return value: True indicates continuation of the process (such as invoking the next interceptor or processor);
False indicates a process interruption (such as a login check failure) and does not continue to invoke other interceptors or processors, at which point we need to generate a response via response;



Aftercompletion: The entire request is processed by the callback method, that is, the callback when the view is rendered, such as in performance monitoring where we can record the end time and output consumption time, and some resource cleanup, similar to the finally in Try-catch-finally, But only the aftercompletion of the Interceptor that Prehandle returns true in the processor execution chain is called.



2 configuration File Settings


<mvc:resources mapping= "/resources/**" location= "/resources/" ></mvc:resources>  
<!--    
Register "global" interceptor beans to the apply to all registered handlermappings.  
Each inteceptor must implement the Org.springframework.web.servlet.HandlerInterceptor or  
Org.springframework.web.context.request.WebRequestInterceptor interface  
-  
<mvc:interceptors>  
    <mvc:interceptor>  
        <mvc:mapping path= "/**"/>  
        <mvc:exclude-mapping path= "/css/**"/>  
        <mvc:exclude-mapping path= "/js/**"/>  
        <mvc:exclude-mapping path= "/images/**"/>  
        < Bean class= "Com.fpx.common.auth.mgt.framework.interceptor.ContextInterceptor"/>  
    </mvc:interceptor >  
</mvc:interceptors>  


Or


<mvc:interceptors>  
    <!--using beans to define a interceptor, directly defined under the Mvc:interceptors root interceptor will intercept all requests--  
    <bean class= "Com.host.app.web.interceptor.AllInterceptor"/>  
    <mvc:interceptor>  
        <mvc: Mapping path= "/test/number.do"/>  
        <!--defined below Mvc:interceptor the representation is blocked for a specific request---  
        <bean class= " Com.host.app.web.interceptor.LoginInterceptor "/>  
    </mvc:interceptor>  


Or


<bean xmlns = "http://www.springframework.org/schema/beans" id = "authenticateInterceptor"
          class = "com.javaplus.castle.authenticate.AuthenticateInterceptor">
        <property name = "uncheckUrls">
            <list>
                <value> / index </ value>
                <value> / doLogin </ value>

            </ list>
        </ property>
    </ bean>
<!-Register DefaultAnnotationHandlerMapping
         If <mvc: annotation-driven /> or <annotation-driven /> is used it will be registered automatically
         DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter
         These two beans, so there is no chance to inject it with interceptors property, you can not specify the interceptor.
        Of course, we can manually configure the above two beans without using <mvc: annotation-driven /> to inject interceptors into the interceptors attribute. ->

  <beans: bean class = "org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        <beans: property name = "interceptors">
            <beans: list>
                <beans: ref bean = "authenticateInterceptor" />
                <!-<beans: ref bean = "logInterceptor" />->
            </ beans: list>
        </ beans: property>
    </ beans: bean>
`` <servlet>
    <servlet-name> airman </ servlet-name>
    <servlet-class> org.springframework.web.servlet.DispatcherServlet </ servlet-class>
    <init-param>
      <param-name> contextConfigLocation </ param-name>
      <param-value>
        classpath: spring / springmvc.xml
      </ param-value>
    </ init-param>
    <load-on-startup> 1 </ load-on-startup>
  </ servlet>
  <servlet-mapping>
    <servlet-name> airman </ servlet-name>
    <url-pattern> / </ url-pattern> block all
  </ servlet-mapping>
<!-This part is a new feature added in 3.0. Adding this tag will tell spring that this is a local resource file and will not be treated as an action. If you do not add this configuration reference js and css will not be able to load->
     <resources mapping = "/ resources / **" location = "/ resources /" />
     <resources mapping = "/ ext-4.2.1.883 / **" location = "/ ext-4.2.1.883 /" />
     <resources mapping = "/ common / **" location = "/ common /" />
     <resources mapping = "/ CAdminLte / **" location = "/ CAdminLte /" />
     <view-controller path = "/" view-name = "redirect: / index" />



Implementation code of the Interceptor




public class AuthenticateInterceptor extends HandlerInterceptorAdapter {

private static final Logger LOGGER = LoggerFactory.getLogger (AuthenticateInterceptor.class);
private List <String> uncheckUrls;
public void setUncheckUrls (List <String> uncheckUrls) {
    this.uncheckUrls = uncheckUrls;
}

@Override
 public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    HttpSession session = request.getSession ();
    String contextPath = request.getContextPath ();
    String requestURI = request.getRequestURI ();
    LOGGER.info ("RequestURI:" + requestURI);
    for (String url: uncheckUrls) {
        if (requestURI.startsWith (contextPath + url)) {
            return true;
        }
    }

    // Get login user information
    Account human = (Account) session.getAttribute (CastleSecurityManager.CURRENT_USER);
    if (human == null) {
        // Jump to login page
        LOGGER.info ("human == null RequestURI:" + requestURI);
        response.sendRedirect ("redirect: / index");

        return false;
    }
    return true;
}
}

@Controller
public class LoginController {

Log log = LogFactory.getLog (this.getClass ());

@Autowired (required = false)
private IUserService userService;

@RequestMapping (value = "/ index")
public String logincheck (HttpServletRequest request, HttpServletResponse response, ModelAndView mv) {
    HttpSession session = request.getSession ();
    Account human = (Account) session.getAttribute (CastleSecurityManager.CURRENT_USER);
    if (human == null) {
        return "login";
    } else {
        return "index"; // Return to jsp
    }
}

@RequestMapping (value = "/ doLogin")
public ModelAndView doLogin (HttpServletRequest request, HttpServletResponse response, @RequestParam Map <String, Object> conditions, ModelAndView mv) {
    HttpSession session = request.getSession ();
    String account = String.valueOf (conditions.get ("account"));
    String pwd = String.valueOf (conditions.get ("pwd"));
    Account user = userService.checkLogin (account, pwd);
    if (user == null) {
         mv.setViewName ("login");
        mv.addObject ("errorMessage", "Incorrect username or password");
        return mv;
    }
    session.setAttribute (CastleSecurityManager.CURRENT_USER, user);
    }



Other points

redirect: / index is returned to the requestmapping request
view-name = ”index” is in jsp
getRequestDispatcher is an internal server jump. The address bar information does not change. It can only jump to a webpage in a web application.
sendRedirect is a page redirect, the address bar information changes, you can jump to any

if (controller instanceof UserLogin) {
Object user = request.getSession (). GetAttribute ("user");
if (user == null) {
log.debug (“———– Not logged in access Jump back to login page —-”);
request.getRequestDispatcher ("/ home / loginUI"). forward (request, response);
return false;
}
}

    HttpSession session = httpServletRequest.getSession ();
    SysUser user = (SysUser) session.getAttribute ("loginsucess");
    if (user! = null) {
        return true;
    }
    // Execution here indicates that there is no session and interception is required
    httpServletRequest.getRequestDispatcher ("/ WEB-INF / jsp / login.jsp"). forward (httpServletRequest, httpServletResponse);
    return false;
public boolean preHandle (HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
boolean flag = false;
String url = request.getRequestURL (). ToString ();
// Do not intercept the path defined above
for (String str: IGNORE_URL) {
if (url.contains (str)) {
flag = true;
break;
}
}
if (! flag) {
User user = (User) request.getSession (). GetAttribute ("users");
if (user! = null)
Flag = true;
Else
Response.sendRedirect ("/ login.jsp");
Return false;
}
return true;
}

   request.getRequestDispatcher ("/ third? name = jay"). forward (request, response);
   Or
   request.getRequestDispatcher ("third? name = jay"). forward (request, response);
   Or
   this.getServletContext (). getRequestDispatcher ("/ third? name = jay"). forward (request, response);
response.sendRedirect ("http://www.baidu.com");




This article refers to the following articles



Http://www.mamicode.com/info-detail-400138.html



Getrequestdispatcher and Sendredirect differences
http://weidongke123-126-com.iteye.com/blog/1461526



Using Interceptor interceptors in SPRINGMVC
http://elim.iteye.com/blog/1750680



SPRINGMVC Common Configuration Instructions
http://blog.csdn.net/strivezxq/article/details/45457067



The difference between spring interceptor and filter
http://blog.csdn.net/zqlsnow/article/details/52946826



SPRINGMVC Interceptors (Resource and Rights Management)
http://blog.csdn.net/tonytfjing/article/details/39207551



Spring MVC Interceptor and the detailed
Http://www.cnblogs.com/yangzhilong/p/3725849.html



Spring Interceptor (with fuzzy matching and no block address configuration code)
Http://www.cnblogs.com/fdzfd/p/5715699.html


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.