spring boot 拦截器登录判断及跳转

1.使用teymeleaf及属性

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.cache=false //禁止缓存,用于开发
spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.encoding=UTF-8

2.拦截器(通过session的属性name判断是否登录,登录放行,未登录记下原来的后缀路径在preurl中,然后重定向到登录页面,就是域名了,request.getRequestURL()完整路径,request.getRequestURI()后缀路径,tempContextUrl是域名,response.sendRedirect()重定向

public class Interceptor1 implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception{
        HttpSession session=request.getSession();
        Object ob=session.getAttribute("name");
        if (ob!=null) {
            return true;
        }
        session.setAttribute("preurl",request.getRequestURI());
        StringBuffer url = request.getRequestURL();
        String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).append("/").toString();
        response.sendRedirect(tempContextUrl);
        return false;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler,ModelAndView model) throws Exception{
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                            Object handler,Exception ex) throws Exception{
    }
}

3.注册拦截器(拦截所有路径,除了/login和静态资源和注册)

@SpringBootApplication
@EnableCaching
public class Application implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry){
        InterceptorRegistration ir=registry.addInterceptor(new Interceptor1());
        ir.addPathPatterns("/**");
        ir.excludePathPatterns("/login","/js/**","/html/**","/image/**");
    }
}

4登录controller(我这里没验证,返回原来路径或者ok)

@RequestMapping("/login")
@ResponseBody
public String bbb(String name, String password, HttpSession session){
    session.setMaxInactiveInterval(1*60);  //设置过期时间以秒为单位,会自动刷新
    System.err.println(name+' '+password);
    session.setAttribute("name",name);
    session.setAttribute("password",password);
    Object ob=session.getAttribute("preurl");
    if (ob!=null) {
        return ob.toString();
    }
    return "ok";
}

5前端处理(根据data跳转到对应的路径)

$.post("/login",
       {
           name:$("#a").val(),
           password:$("#b").val()
       },
       function(data){
           if (data!='ok') {
               window.location.href = 'http://' + location.host + data;
           }
           else window.location.href = 'http://' + location.host + '/main';
       }
)

猜你喜欢

转载自blog.csdn.net/weixin_43245707/article/details/85095482
今日推荐