springMVC自定義注解實現用戶行為驗證


最近在進行項目開發的時候需要對接口做Session驗證

1、自定義一個注解@AuthCheckAnnotation

@Documented
@Target(ElementType.METHOD)
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthCheckAnnotation {
    boolean check() default false;
}

2、定義一個相應的攔截器,在springMVC配置文件中進行配置

  攔截器:

  spring為我們提供了org.springframework.web.servlet.handler.HandlerInterceptorAdapter這個適配器,繼承此類,可以非常方便的實現自己的攔截器。可以根據我們的需要重寫preHandlepostHandle、afterCompletio方法。

  分別實現預處理、后處理(調用了Service並返回ModelAndView,但未進行頁面渲染)、返回處理(已經渲染了頁面)
    在preHandle中,可以進行編碼、安全控制等處理;
    在postHandle中,有機會修改ModelAndView;
    在afterCompletion中,可以根據ex是否為null判斷是否發生了異常,進行日志記錄。

public class AuthCheckInteceptor extends HandlerInterceptorAdapter {
    @Autowired
    UserInfoService userInfoService ;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        HandlerMethod methodHandler=(HandlerMethod) handler;
        AuthCheckAnnotation auth=methodHandler.getMethodAnnotation(AuthCheckAnnotation.class);
     //如果方法中添加了@AuthCheckAnnotation 這里的auth不為null
     //如果@AuthCheckAnnotation(check=false) 這里的auth為false,即不用進行攔截驗證,@AuthCheckAnnotation默認為前面定義的true  
if(auth!=null&&!auth.check()){ return true; } UserInfo user=(UserInfo)request.getSession().getAttribute(Constants.SESSION_USER); try { userInfoService.login(request, user); return true; } catch (Exception e) { request.getRequestDispatcher("login.do").forward(request, response); return false; } } }

  在springMVC.xml文件中添加攔截器

    <mvc:interceptors>
            <mvc:interceptor>
            <mvc:mapping path="/*.do"  />
            <bean  class="com.party.common.interceptor.AuthCheckInteceptor"/>        
        </mvc:interceptor>
    </mvc:interceptors>

3、在springMVC controller中使用實例

    @AuthCheckAnnotation(check=true)
    @RequestMapping("doLogin")
    @ResponseBody
    public Object doLogin(HttpServletRequest request,HttpServletResponse response){
        .......
        return RetMessage.toJson(responseBody);
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM