简单的springMVC登录拦截器

还在学习中,一个简单的spring MVC 登录拦截

spring配置如下:

 
        
            
            
                
                    
                    /login.html
                
            
        
    

如果有多个允许通过的请求时,可以使用list,用spring注入允许通过的uri这样更灵活

java代码如下:

package com.test.intercept;

import com.test.Userinfo;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by haocongshun on 2017/2/25.
 */
public class InterceptDemo implements HandlerInterceptor {
    private static Logger logger = Logger.getLogger(InterceptDemo.class);
    private List allowuri;
    /**
     * Handler执行之前调用这个方法,一般拦截在此处拦截
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * 是否允许通过@return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String uri = httpServletRequest.getRequestURI();
//        if(uri.contains("/login.html")){
//            return true;
//        }
//        如果你有多可允许通过的uri可以使用list在Spring中配置,更加灵活
        for(String auri : allowuri){
            if(auri.contains(uri)){
                return true;
            }
        }
        //检验session中是否有你需要的属性
        Userinfo userinfo = (Userinfo) httpServletRequest.getSession().getAttribute("userinfo");
        if(userinfo!=null){
            return true;
        }
        logger.info("被拦截的uri:"+uri);
        httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/admin/login.html");
        return false;
    }
    /**
     *Handler执行之后,ModelAndView返回之前调用这个方法
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    /**
     * Handler执行完成之后调用这个方法
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    public List getAllowuri() {
        return allowuri;
    }

    public void setAllowuri(List allowuri) {
        this.allowuri = allowuri;
    }

    public static Logger getLogger() {
        return logger;
    }

    public static void setLogger(Logger logger) {
        InterceptDemo.logger = logger;
    }
}

你可能感兴趣的:(java,java,web开发,spring,mvc,spring,mvc)