登录权限检查(SpringMVC)
如何实现登录权限检查?
使用session约定值的判断
实现方法:
1.采用Filter(过滤器)
2.采用拦截器
拦截器组件是SpringMVC特有组件。拦截器组件可以在Controller之前拦截;也可以在Controller之后拦截;还可以在JSP解析完毕给浏览器输出之前拦截。
实例:
A.创建相应拦截器类并实现HandlerInterceptor接口:
package com.day04test.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; //拦截器 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,则拦截 * (non-Javadoc) * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object) */ 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 true;//终止MVC后续流程 } } }
B.在applicationContext.xml中配置拦截器
<!-- 配置拦截器 --> <mvc:interceptors> <mvc:interceptor> <!-- 指明路径:拦截那些请求 --> <mvc:mapping path="/**"/> <!-- 放过那些请求 --> <mvc:exclude-mapping path="/tologin.do"/> <mvc:exclude-mapping path="/login3.do"/> <bean class="com.day04test.interceptor.LoginInterceptor"/> </mvc:interceptor> </mvc:interceptors>