Simple understanding of SPRINGMVC's Handlerinterceptor (login example)

Source: Internet
Author: User
Tags java web

  • Abstract class

  • Package com.book.admin.interceptor;import java.util.arraylist;import java.util.list;import  java.util.regex.Pattern;import javax.servlet.http.HttpServletRequest;import  Javax.servlet.http.httpservletresponse;import org.slf4j.logger;import org.slf4j.loggerfactory;import  org.springframework.web.servlet.HandlerInterceptor;import  org.springframework.web.servlet.modelandview;/** *  *  @author  liweihan * */ public abstract class abstractinterceptor implements handlerinterceptor{private  Static logger logger = loggerfactory.getlogger (Abstractinterceptor.class);// Links that do not need to be intercepted protected static list<string> excludeactionlist = new arraylist <String> (Static {        excludeactionlist.add); ("^/(login| Static) (/)? (. +)? $ ");         excludeactionlist.add ("^/(Flush|test|site_map) (/)? (. +)? $ ");     //redis data flush         excludeactionlist.add ("^/app/(Flush|info.json|apkinfo.json) (/)?" (. +) ($ ");     //front-end Interface http://m.tv.sohu.com/app         Excludeactionlist.add ("^/(Hikeapp) (/)?" (. +) $ ");         //need to pull up the client's album Data access interface          excludeactionlist.add ("^/(COOPERATION|ACTIVITY|API|OPEN|MOBILE|MB) (/)?" (. +)? $ ");         excludeactionlist.add (" ^/(ACTIVITY|API|OPEN|MOBILE|MB) ( /)? (. +)? $ ");         excludeactionlist.add (" ^/(test) (/)? "(. +)?$");} Public boolean prehandle (httpservletrequest request,httpservletresponse response,  Object handler)  throws exception {//logger.debug (" ====== prehandle !"); /logger.info (" ======= uri:{} ", Request.getrequesturi ()); Request.setattribute (" URI ",  request.getrequesturi ());// In order to highlight the selected link for (string excludeurl : excludeactionlist)  {if (Pattern.matches (EXCLUDEURL,  request.getrequesturi ()))  {return true;}} Return innerprehandle (Request, response, handler);} Protected abstract boolean innerprehandle (httpservletrequest request,  Httpservletresponse response, object handler)  throws Exception;public void  Posthandle (Httpservletrequest request,httpservletresponse response, object handler, Modelandview modelandview)  throws exception {//logger.debug (" ====== postHandle  ! ");} Public void aftercompletion (httpservletrequest request,httpservletresponse response,  Object handler, exception ex) Throws exception {//logger.debug (" ======  aftercompletion ! ");}} 


    2. Permission filtering

    Package com.book.admin.interceptor;import java.util.arraylist;import java.util.list;import  java.util.regex.Pattern;import javax.servlet.http.HttpServletRequest;import  javax.servlet.http.httpservletresponse;import org.apache.commons.lang.stringutils;import  org.slf4j.logger;import org.slf4j.loggerfactory;import  org.springframework.beans.factory.annotation.autowired;import org.springframework.web.util.webutils; import com.book.core.model.adminfunctions;import com.book.core.model.adminright;import  com.book.core.model.user;import com.book.core.service.adminfunctionsservice;import  com.book.core.service.adminrightservice;import com.book.core.utils.constants;/** *  User Rights filtering   *  @author  liweihan * */public class FunctionsInterceptor extends  Abstractinterceptor{private static logger logger = loggerfactory.getlogger ( Functionsinterceptor.claSS); @Autowiredprivate  AdminRightService adminRightService; @Autowiredprivate   adminfunctionsservice adminfunctionsservice;//do not need to intercept the link after login protected static list<string>  excludeActionList = new ArrayList<String> ();static {         excludeactionlist.add ("^/(Index|admin/user|admin/myinfo) (/)?" (. +) ($ ");         excludeactionlist.add (" ^/(book/del|book/detail.json| Book/addorupdate) (/)? (.+)?$");} @Overrideprotected  boolean innerprehandle (httpservletrequest request,httpservletresponse  Response, object handler)  throws Exception {try {User user =  ( User)  webutils.getsessionattribute (Request, constants.admin_session_user_key);if  (user ==  null)  {response.sendredirect ("/login"); return false;} Find permissions for this user adminright adminright = adminrightservice.getobjbyuSername (User.getname ());if  (Adminright == null)  {return true;} list<adminfunctions> menus = null;if  (Adminright.getisadmin ()  == 1)  { Menus = adminfunctionsservice.getall ();  request.setattribute ("Menus",  menus); Request.setattribute ("ISAdmin",  adminright.getisadmin ()); return true;}  else {string right = adminright.getrights ();if  (StringUtils.isNotBlank (right))  {string[] rs = right.split (","); list<integer> listid = null;if  (rs != null && rs.length  > 0)  {listId = new ArrayList<Integer> (;for ) (int i =  0; i < rs.length; i++)  {if  (Stringutils.isnotblank (rs[i))  { Listid.add (Integer.valueof (Rs[i]);}}} Query Menus = adminfunctionsservice.getobjbyids (listId);} for (String excludeurl : excludeactionlist)  {if (Pattern.matches (Excludeurl, request.getrequesturi ()))  { Request.setattribute ("Menus",  menus); Request.setattribute ("ISAdmin",  adminright.getisadmin ()); return  true;}} Filter permissions, you cannot enter a URL to access if  (Menus != null && menus.size ()  > 0)  {for (Adminfunctions adminfunctions : menus)  {if  (Request.getrequesturi (). StartsWith (Adminfunctions.geturl ()))  {logger.info (" ====== request.getrequesturi (): {},table-url : {} ", Request.getrequesturi (), Adminfunctions.geturl ()), Request.setattribute (" menus ",  menus); Request.setattribute ("ISAdmin",  adminright.getisadmin ()); return true;}}} Response.sendredirect ("/login"); return false;}  catch  (exception e)  {logger.error (" ====== get adminright error!", e); E.printstacktrace ();} Return false;}}

       3. Login verification

    Package com.book.admin.interceptor;import java.net.urlencoder;import java.util.calendar;import  java.util.Date;import java.util.UUID;import javax.servlet.http.Cookie;import  javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;import  org.slf4j.logger;import org.slf4j.loggerfactory;import  org.springframework.beans.factory.annotation.autowired;import org.springframework.web.util.webutils; import com.book.core.model.persistentlogins;import com.book.core.model.user;import  com.book.core.service.persistentloginsservice;import com.book.core.service.userservice;import  com.book.core.utils.constants;import com.book.core.utils.cookieutil;import  com.book.core.utils.encryptionutil;/** *  Login verification blocker  *  @author  liweihan * */ Public class logininterceptor extends abstractinterceptor{private static logger  logger = loggerfactory.getlogger (Logininterceptor.class); @Autowiredprivate  PersistentLoginsService  Persistentloginsservice, @Autowiredprivate  UserService userService; @Overrideprotected  boolean  innerprehandle (httpservletrequest request,httpservletresponse response, object  Handler)  throws Exception {User user =  (User)  webutils.getsessionattribute ( Request, constants.admin_session_user_key);if  (user != null)  {//logged in Return true;}  else {//the value Cookie cookie = cookieutil.getcookie from the cookie (request,  Constants.rememberme_admin);if  (cookie != null)  {String cookieValue =  Encryptionutil.base64decode (Cookie.getvalue ()); String[] cvalues = cookievalue.split (":");if  (cvalues.length == 2)  {String  usernamebycookie = cvalues[0];//Get user name string uuidbycookie = cvalues[1];//get uUID value//query to the database for automatic login record Persistentlogins plogins  = persistentloginsservice.getobjbyuuid ( Uuidbycookie);if  (plogins != null)  {string savedtoken = plogins.gettoken () ;//Get Effective Time date savedvalidtime = plogins.getvalidtime ();D ate currenttime = new  date ();//If you are still within the validity period, record whether you can log in automatically if  (Currenttime.before (savedvalidtime))  {user u =  userservice.getuserbyname (Usernamebycookie);if  (u != null)  {Calendar calendar  = calendar.getinstance (); Calendar.settime (savedvalidtime);//  accurate to minute time string string timestring  = calendar.get (calendar.year)  +  "-"  + calendar.get (calendar.month) +  "-"  + calendar.get (Calendar.day_of_month)  +  "-" + calendar.get (Calendar.hour_of_day)  +  "-"  + calendar.get (Calendar.minute);//  ciphertext generated for verification string newtoken =  Encryptionutil.sha256hex (U.getname ()  +  "_"  + u.getpassword ()  +  "_" + timestring +  "_"  +  Constants.salt);//  checksum sha256 encrypted value, if not the same means that the user part of the information has been modified, need to re-login if  (savedtoken.equals (newtoken))  {// For increased security, the automatic login cookie value string uuidnewstring = uuid.randomuuid () is updated after each login. toString (); String newcookievalue = encryptionutil.base64encode (U.getname ()  +  ":"  +  uuidnewstring); Cookieutil.editcookie (Request, response, constants.rememberme_admin, newcookievalue, null) ;//Update Data plogins.setseries (uuidnewstring);p logins.setupdatetime (New date ()); Persistentloginsservice.updatebyobj (plogins);//Add users to the session, do not exit the browser only need to determine the session can be Webutils.setsessionattribute (request, constants.admin_session_user_key, u);//verification successful, this interception operation completed return true;}  else {//The User Information section is modified, delete the cookie and empty the record in the database Cookieutil.delcookie (Response, cookie); Persistentloginsservice.delobjbyid (Plogins.getid ());}}}  else {//  more effective than the savedDelete cookies and empty the records in the database Cookieutil.delcookie (Response, cookie);p Ersistentloginsservice.delobjbyid ( Plogins.getid ());}}} Try {response.sendredirect ("/login?src="  + urlencoder.encode (Request.getrequesturi (),  " UTF-8 "));}  catch  (exception e)  {logger.error (" ===== logininterceptor error ,url : {} {} ", Request.getrequesturl (), Request.getrequesturi (), e);}  return false;}}}

      Configuration of  4.spring-mvc-servlet.xml

    <?xml version= "1.0"  encoding= "UTF-8"? ><beans xmlns= "http://www.springframework.org/ Schema/beans "      xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance "      xmlns:mvc= "Http://www.springframework.org/schema/mvc"       xmlns:context= "Http://www.springframework.org/schema/context"      xsi:schemalocation= "         http://www.springframework.org/schema/beans           http://www.springframework.org/schema/beans/ spring-beans-3.0.xsd         http://www.springframework.org/ schema/context          http://www.springframework.org/ schema/context/spring-context-3.0.xsd         http:// www.springframework.org/schema/mvc         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd "><!--  Specify a package to automatically scan the  --><context:component-scan base-package= "Com.book.admin.controller"/&GT;&LT;MVC: annotation-driven/><!--  Part of the notes below: Emphasize that all requests go through the SPRINGMVC framework  -->    <mvc :d efault-servlet-handler/><!--  released a request to start with/static/ --><mvc:resources location= "/ static/" mapping="/static/** "/> <!--  When a method is completely to jump, we can omit the method, and write a configuration here on the line &LT;MVC: View-controller path= "/index"  view-name= "index"/><mvc:view-controller path= "/main"   View-name= "main"/><mvc:view-controller path= "/success"  view-name= "Success"/&GT;&NBSP;&LT;MVC: View-controller path= "/index"  view-name= "main"/><mvc:view-controller path= "/"   View-name= "main"/> <mvc:view-controller path= "/admin/myinfo"  view-name= "MyInfo"/>-- ><!-- <mvc:view-controlleR path= "/book"  view-name= "book"/> --><mvc:interceptors><bean class= " Com.book.admin.interceptor.LoginInterceptor "></bean><bean class=" Com.book.admin.interceptor.FunctionsInterceptor "></bean><!--  <mvc:interceptor>           <mvc:mapping path= "/test/number.do"/>           <bean class= " Com.host.app.web.interceptor.LoginInterceptor "/>      </mvc:interceptor >      --></mvc:interceptors><!--  Configure SPRINGMVC View resolver  -- ><bean id= "Viewresolver"  class= " Org.springframework.web.servlet.view.InternalResourceViewResolver "><property name=" suffix "  Value= ". jsp"/><property name= "prefix"  value= "/web-inf/views/"/></bean><!--  File Upload Parser    --><bean&Nbsp;id= "Multipartresolver"      class= " Org.springframework.web.multipart.commons.CommonsMultipartResolver ">     < Property name= "Maxuploadsize"  value= "100000"/> </bean></beans>

    Reference:

    Basics of Interceptors understand

    http://blog.csdn.net/sunp823/article/details/51694662


    Detailed information on interceptors

    http://jinnianshilongnian.iteye.com/blog/1670856


    Login examples of ideas to understand

    http://blog.51cto.com/983836259/1880284


    Regular expressions

    Http://www.cnblogs.com/sparkbj/articles/6207103.html


    The difference between a SPRINGMVC interceptor and a filter

    http://blog.csdn.net/xiaoyaotan_111/article/details/53817918


    Filters in the Java Web and the understanding of filter filter and Interceptor

    http://www.jianshu.com/p/39c0cfe25997


    Simple understanding of SPRINGMVC's Handlerinterceptor (login example)

    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.