登录拦截器的使用
spring中登录拦截器的使用
步骤1:实现接口:
public methodName implements HandlerInterceptor(){}
步骤2:
配置spring:
步骤3:
如果不是在spring的主配置文件中配置上面的代码,需要在spring中引入包
1:实现接口
package com.business.system.common; 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; public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { HttpSession session = httpServletRequest.getSession(); Object business = session.getAttribute("business"); String requestURI = httpServletRequest.getRequestURI(); if(business==null){ System.out.println("没有登录,无法访问requestURI="+requestURI); httpServletResponse.sendRedirect("/business/loginPage"); return false; }else { System.out.println("登陆成功"); 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 { } }
2:在spring中配置拦截操作
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <mvc:exclude-mapping path="/business/*"/> <bean class="com.business.system.common.LoginInterceptor"/> </mvc:interceptor> </mvc:interceptors> </beans>