zoukankan      html  css  js  c++  java
  • Spring MVC基础知识整理➣拦截器和自定义注解

    概述

      Spring MVC中通过注解来对方法或者类进行动态的说明或者标注,类似于配置标识文件的属性信息。当标注的类或者方式被使用时候,通过提取注解信息来达到对类的动态处理。在 MVC中,我们常用的注解@Controller、 @RequestMapping等,通过设置注解里面的方法值来实现不同数据的处理方式。

      如@RequestMapping(value="/City",method=RequestMethod.GET),我们标注请求映射地址和请求的方式;通过解读这些属性信息,来实现内部不通的处理方式。

    自定义注解

      新建Annotation(注解),实例代码如下

    import java.lang.annotation.Documented;
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Inherited;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    
    @Documented //输出文档格式化
    @Inherited 
    @Target(ElementType.METHOD) //这是一个对方法的注解,还可以是包、类、变量等很多东西
    @Retention(RetentionPolicy.RUNTIME)//保留时间,一般注解就是为了框架开发时代替配置文件使用,JVM运行时用反射取参数处理,所以一般都为RUNTIME类型  
    public @interface AuthPassport {
        //是否启用验证信息
        boolean validate() default true;
        //权限等级编码
        String PowerCode() default "admin";
    }

      添加方法的注释类

    public class HelloWorldController    
    {
      @AuthPassport(validate=true,PowerCode="EveryOne") @RequestMapping(value={"/*","/say"},method=RequestMethod.GET) public ModelAndView China() { ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("message", "Hello World!"); modelAndView.setViewName("HelloWorld/CIndex"); return modelAndView; }
    }

      获取注解类信息

    import java.lang.reflect.Method;  
      
    public class TestThis {  
      
        public static void main(String[] args) throws Exception {  
            // 提取到被注解的方法Method,这里用到了反射的知识  
            Method method = Class.forName("HelloWorldController").getDeclaredMethod("China");  
            // 从Method方法中通过方法getAnnotation获得我们设置的注解  
            AuthPassport oneAnnotation = method.getAnnotation(AuthPassport.class);  
              
            // 得到注解的俩参数  
            System.out.println(oneAnnotation.validate());  
            System.out.println(oneAnnotation.PowerCode());  
        }  
    }

    拦截器

      针对MVC的数据请求,我们可以配置响应的Bean(拦截器)进行数据拦截,自定义拦截器需要继承HandlerInterceptorAdapter类,重写该类的三个方法(preHandle、postHandle、afterCompletion),其中afterCompletion响应之后触发的方法,preHandler响应之前处理方法,postHandle是标识响应中触发的方法。我们可以在preHandler里面进行数据的校验,比如权限的校验、登录信息的校验等信息的处理。HandlerInterceptorAdapter的源码:

    public interface HandlerInterceptor {  
        boolean preHandle(  
                HttpServletRequest request, HttpServletResponse response,   
                Object handler)   
                throws Exception;  
      
        void postHandle(  
                HttpServletRequest request, HttpServletResponse response,   
                Object handler, ModelAndView modelAndView)   
                throws Exception;  
      
        void afterCompletion(  
                HttpServletRequest request, HttpServletResponse response,   
                Object handler, Exception ex)  
                throws Exception;  
    }

    自定义拦截器如下

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import justin.com.comclass.AuthPassport;
    
    import org.springframework.web.method.HandlerMethod;
    import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; 
    
    public class AuthInterceptor extends HandlerInterceptorAdapter {
    
        @Override
        public boolean preHandle(HttpServletRequest request,
                HttpServletResponse response, Object handler) throws Exception {
            if(handler.getClass().isAssignableFrom(HandlerMethod.class))
            {
                AuthPassport authpassport=((HandlerMethod) handler).getMethodAnnotation(AuthPassport.class);//使用自定义注解
                if(authpassport==null || authpassport.validate()==false)
                {
                    return true;                        
                }
                else
                {
                    System.out.println("测试注解");
                    boolean IsValieData=request.isRequestedSessionIdValid();
                    //在这里实现自己的权限验证逻辑
                    if(!IsValieData)//如果验证成功返回true(这里直接写false来模拟验证失败的处理)
                        return true;
                    else//如果验证失败
                    {
                        //返回到登录界面
                        response.sendRedirect("../login/index");
                        return false;
                    }      
                }            
            }
            else
            {
                return true;
            }
        }        
    }

    在spring-servletconfig.xml 中配置拦截器信息

        <mvc:interceptors>  
            <!-- 如果不定义 mvc:mapping path 将拦截所有的URL请求 -->
            <bean class="justin.com.fileter.AuthInterceptor"></bean>
        </mvc:interceptors>  

    至此MVC自定义的拦截器整理完毕!

  • 相关阅读:
    mac Redis相关配置,安装,启动,环境的配置。
    MySQL设置global变量和session变量的两种方法详解
    关于MySQL的锁以及数据脏读,重复读,幻读的笔记。
    MySQL新增数据,存在就更新,不存在就添加(转帖加实测)
    selenium 的显示等待和隐式等待的区别(记录加强版)
    MySQL字段与表的注释。转帖
    mysql格式化日期(转帖)
    通过Python用pymysql,通过sshtunnel模块ssh连接远程数据库。
    java io流
    openID 无效
  • 原文地址:https://www.cnblogs.com/xibei666/p/6653805.html
Copyright © 2011-2022 走看看