spring boot 攔截器登入判斷及跳轉
阿新 • • 發佈:2018-12-27
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';
}
)