StringMVC做登录拦截
1:拦截类
package cn.sjt.ums.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class LoginInterceptor implements HandlerInterceptor{
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object obj, Exception err)
throws Exception {
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object obj, ModelAndView mav) throws Exception {
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object obj) throws Exception {
// 从session 里面获取用户ID
String userId = (String) request.getSession().getAttribute("userid");
// 判断如果没有取到用户ID,就跳转到登陆页面,提示用户进行登陆
if (userId == null || "".equals(userId)) {
response.sendRedirect("/login");
return false;
}
return true;
}
}
2:applicationContext-springmvc.xml的配置
<!-- 端口后加"/",跳转至登录页 -->
<mvc:view-controller path="/" view-name="redirect:/login" />
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<!-- 不需要拦截的配置 -->
<mvc:exclude-mapping path="/"/>
<mvc:exclude-mapping path="/login" />
<mvc:exclude-mapping path="/captcha-image" />
<mvc:exclude-mapping path="/user/inneruser/login" />
<mvc:exclude-mapping path="/css/**" />
<mvc:exclude-mapping path="/images/**" />
<mvc:exclude-mapping path="/js/**"/>
<bean class="cn.sjt.ums.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>