1. 程式人生 > >Spring mvc登錄攔截器

Spring mvc登錄攔截器

gin tor 要求 session row 請求轉發 pin dispatch framework

自己實現的第一個Spring mvc登錄攔截器

題目要求:拒絕未登錄用戶進入系統,只要發現用戶未登錄,則將用戶請求轉發到/login.do要求用戶登錄

實現步驟:

1.在spring的配置文件中添加登錄攔截,如下:

spring-web.xml

<mvc:interceptors>
<!-- 配置登陸攔截器 -->
<mvc:interceptor>
<mvc:mapping path="/**"/> //攔截所有請求
<mvc:exclude-mapping path="/toLogin"/> //不攔截與登錄相關的請求

<mvc:exclude-mapping path="/login"/>
<mvc:exclude-mapping path="/static/**"/>//不攔截靜態
<bean class="com.hand.filter.LoginHandlerIntercepter"/>
</mvc:interceptor>
</mvc:interceptors>

註意:要使用mvc:exclude-mapping必須將xml文件的http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"改為http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"

2.實現攔截器

LoginHandlerIntercepter.java

public class LoginHandlerIntercepter implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
if (httpServletRequest.getSession().getAttribute("customer") != null) {
return true;
} else {
//沒有登陸,轉向登陸界面
httpServletRequest.getRequestDispatcher("/toLogin").forward(httpServletRequest, httpServletResponse);
return false;
}
}

@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 {

}
}

小結:這個攔截器還有許多不完善的地方,但是大概思路就是這樣

Spring mvc登錄攔截器