使用session進行約定值判斷
實現方法:
1.採用filter
2.採用攔截器
攔截器
簡介:是Spring mvc特有組件
作用:
1.可以在controller之前攔截;
2.可以在controller之後攔截;
3.可以在jsp解析完畢給瀏覽器輸出之前攔截;
攔截器使用方法
首先編寫一個攔截器組件(實現HandlerInterceptor接口)
在約定方法中添加插入的邏輯
在applicationContext.xml中配置
LoginInterceptor 攔截器組件代碼:
public class LoginInterceptor implements HandlerInterceptor{
//請求處理完畢,輸出之前
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System.out.println("--afterCompletion--");
}
//Controller之後
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
System.out.println("--postHandle--");
}
//Controller之前 false:攔住了
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object arg2) throws Exception {
System.out.println("--preHandle實現登錄檢查--");
HttpSession session = request.getSession();
//獲取登錄成功後放置的用戶信息
String name = (String)session.getAttribute("username");
if(name != null){
//登陸過
return true;//繼續執行mvc後續流程
}else{
//未登錄或登錄失效
response.sendRedirect("tologin.do");
return false;//終止mvc後續流程
}
}
}
applicationContext中配置
<!-- 配置攔截器 -->
<mvc:interceptors>
<mvc:interceptor>
<!-- 攔截哪些請求 -->
<mvc:mapping path="/**"/>
<!-- 放過哪些請求 -->
<mvc:exclude-mapping path="/tologin.do"/>
<mvc:exclude-mapping path="/login3.do"/>
<bean class="org.tarena.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>