编写 HandlerInterceptor 的实现类:
import com.ft.emedical.tool.CommonUtil; import com.ft.emedical.tool.Constant; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; 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; /** * @Author Bill * @Version 1.0, 2017-1-11 * @See * @Since com.and.erp.common.interceptor * @Description: TODO */ public class IndexInterceptor implements HandlerInterceptor { /*@Autowired private S_PlatformService s_PlatformService;*/ private static Log log = LogFactory.getLog(IndexInterceptor.class); @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { // TODO Auto-generated method stub } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { // TODO Auto-generated method stub } @Override public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception { arg1.setHeader("Access-Control-Allow-Headers", "X-Requested-With, accept, content-type, exception"); arg1.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH"); arg1.setHeader("Access-Control-Allow-Credentials", "true"); arg1.setHeader("Access-Control-Allow-Origin", arg0.getHeader("Origin"));//前段项目的域 HttpSession session = arg0.getSession(true); // 从session 里面获取用户名的信息 Object sysUser = session.getAttribute(Constant.USER_SESSION_KEY); Object appUser = session.getAttribute(Constant.APPUSER_KEY); // 判断如果没有取到用户信息,就跳转到登陆页面,提示用户进行登陆 if (CommonUtil.isBlank(sysUser) && CommonUtil.isBlank(appUser)) { log.error("身份过期,重新登录"); arg1.sendRedirect(arg0.getContextPath() + "/toLogin.do"); return false; } return true; } }
设置拦截范围,在spring的xml配置文件中添加(不解释了,大概看可以看明白):
<mvc:interceptors> <mvc:interceptor> <!-- 拦截所有请求 --> <mvc:mapping path="/*" /> <mvc:mapping path="/*/*" /> <mvc:mapping path="/*/*/*" /> <mvc:mapping path="/*/*/*/*" /> <!-- 不拦截的请求 --> <mvc:exclude-mapping path="/toLogin.do" /> <mvc:exclude-mapping path="/toIndex.do" /> <mvc:exclude-mapping path="/login.do" /> <mvc:exclude-mapping path="/toNoPri.do" /> <mvc:exclude-mapping path="/toSameData.do" /> <mvc:exclude-mapping path="/hh.do" /> <mvc:exclude-mapping path="/system/user/toupdatepwd.do" /> <mvc:exclude-mapping path="/api/*" /> <mvc:exclude-mapping path="/api/*/*" /> <mvc:exclude-mapping path="/api/*/*/*" /> <!-- 拦截器对应的实现类 --> <bean class="com.ft.emedical.common.interceptor.IndexInterceptor" /> </mvc:interceptor> </mvc:interceptors>然后启动完成拦截器配置