springmvc 登录拦截
首先写一个拦截器 实现HandlerInterceptor接口
package com.xiepanpan.ecps;
import com.xiepanpan.ecps.model.TsPtlUser;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* describe: 用户登录拦截器
*
* @author xiepanpan
* @date 2018/11/15
*/
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
TsPtlUser user = (TsPtlUser) request.getSession().getAttribute("user");
if (user==null) {
String path = request.getContextPath();
response.sendRedirect(path+"/user/toLogin.do");
//拦截
return false;
}else {
//放行
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 {
}
}
然后在springmvc.xml中配置
<?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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
<context:component-scan base-package="com.xiepanpan.ecps.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/shop/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 拦截器拦截配置-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/user/login/**"/>
<bean class="com.xiepanpan.ecps.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
</beans>
路径为/user/login开头的所有url都被拦截 完成。