對於註解的使用這裏就不在多介紹,直接上代碼了!java
先新建一個註解文件:web
@Target({ElementType.TYPE,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface AccessRequired { String value() default ""; }
而後再新建一個攔截器文件.這裏咱們實現的是HandlerInterceptor攔截器,關於該攔截器以及其餘攔截器的知識,本身百度谷歌補充吧。spring
public class LoginInterceptor implements HandlerInterceptor { protected Logger log= Logger.getLogger(getClass()); @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { } @Override public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception { HandlerMethod handlerMethod = (HandlerMethod)handler; Method method = handlerMethod.getMethod(); AccessRequired annotation = method.getAnnotation(AccessRequired.class); if(null != annotation){ String value = annotation.value(); if(value.length()==0){ return true; } String sessionValue = (String)req.getSession().getAttribute(value); if(null != sessionValue){ return true; }else{ log.warn("session.getAttribute("+value+") is null",new Exception("無權限登陸 ")); resp.sendRedirect("login"); } } //沒有註解經過攔截 return true; } }
3.配置SpringMVC的配置文件,springmvc.xml.
api
<!-- 配置攔截器--> <bean id="loginInterceptor" class="com.infowall.interceptor.LoginInterceptor"></bean> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/mvc/**"/> <ref bean="loginInterceptor"/> </mvc:interceptor> </mvc:interceptors>
<mvc:interceptors>這個標籤是用來配置攔截器的,使用mvc標籤,須要在xml文件中添加mvc的schame
spring-mvc
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
注意問題:session
若是你使用了<mvc:resources mapping="/resources/**" location="/resources/" />來配置靜態資源,那麼配置如上攔截器的時候就要使用使用了全局攔截/**,不然會攔截靜態資源拋出ResourceHttpRequestHandler cannot be cast to HandlerMethod異常.mvc
辦法一:加上攔截路徑前綴app
<mvc:mapping path="/path/**" />ide
<!-- 這裏使用一個path前置,如api,不然會攔截靜態資源 -->post
辦法二:在自定義攔截器中使用instanceof 過濾ResourceHttpRequestHandler 類型.
還有在寫攔截器的時候,注意導入的class,
import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView;
否則,導入錯的類,也會包異常。
4.在你的controller的方法上,類上使用@@AccessRequired(value="查詢的key")。
@RequestMapping("/success") @AccessRequired(value="userName") public String success(){ return "success"; }
提示:推薦能使用servlet規範中的過濾器Filter實現的功能就用Filter實現,由於HandlerInteceptor只有在Spring Web MVC環境下才能使用,所以Filter是最通用的、最早應該使用的。如登陸這種攔截器最好使用Filter來實現。