前言

Github:https://github.com/HealerJean

博客:http://blog.healerjean.com

1、拦截器实现简单登录功能

1.1、登录controller

将登陆后的信息放到session中去,因为一次登录的话,session是不会变的,因为已经和我们的服务器产生了联系


package com.healerjean.moudle;

import com.healerjean.Exceptions.AppException;
import com.healerjean.bean.ResponseBean;
import com.healerjean.utils.ExceptionLogUtils;
import com.healerjean.utils.wechat.WeChatBusinessNoUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;


@Controller
@Slf4j
@Api(hidden = true,description = "登录控制器")
public class LoginController {


    @RequestMapping("login")
    @ResponseBody
    public ResponseBean login(String username, String password, HttpServletRequest request){

        try {
            if (StringUtils.equals(username,"healerjean") && StringUtils.equals(password,"password")){
                request.getSession().setAttribute("healerjean","healerjean");
                return ResponseBean.buildSuccess();
            }else {
                return ResponseBean.buildFailure();
            }
        }catch (AppException e){
            ExceptionLogUtils.log(e, this.getClass());
            return ResponseBean.buildFailure(e.getCode(),e.getMessage());
        } catch (Exception e) {
            ExceptionLogUtils.log(e, this.getClass());
            return ResponseBean.buildFailure(e.getMessage());
        }
    }


    @RequestMapping("loginError")
    @ResponseBody
    public ResponseBean loginError(){
        return ResponseBean.buildFailure("请登录");
    }

}


1.2、拦截器进行拦截

package com.healerjean.config.interceptor;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


public class SessionInterceptor implements HandlerInterceptor {

    private final String[] NO_FILTER_PAGES = {"/","/login"};


    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String uri = httpServletRequest.getRequestURI();
        for (String c : NO_FILTER_PAGES){
            if (c.equals(uri)){
                return true;
            }
        }
        HttpSession session = httpServletRequest.getSession();
        if (session.getAttribute("healerjean") == null){
            invalidate(httpServletRequest,httpServletResponse);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }


    private void invalidate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().invalidate();
        String ajax = request.getHeader("X-Requested-With");
        if (StringUtils.equals(ajax,"XMLHttpRequest")) {
            //设置登陆超时header
            response.addHeader("sessionout","true");
        } else {
            response.sendRedirect("/loginError");
        }
    }

}


1.3、拦截器配置

package com.healerjean.config;

import com.healerjean.config.interceptor.SessionInterceptor;
import com.healerjean.config.interceptor.UrlInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.annotation.Resource;

/**
 *  登录认证拦截器
 * 作者:  HealerJean
 * 日期:  2018/11/8 下午3:57.
 * 类描述: 
 */

@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {


    @Resource
    private UrlInterceptor urlInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SessionInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("/healerjean/hui/**")
                .excludePathPatterns("/healerjean/taokeData/uploadExcel/**")
                .excludePathPatterns("/loginError")  ;


        super.addInterceptors(registry);
    }



}

ContactAuthor