美文网首页
SpringMVC注解

SpringMVC注解

作者: 剑客kb | 来源:发表于2018-07-17 09:52 被阅读0次

    RequestMapping

    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Mapping
    public @interface RequestMapping {
        String name() default "";
        @AliasFor("path")
        String[] value() default {};
        @AliasFor("value")
        String[] path() default {};
        RequestMethod[] method() default {};
        String[] params() default {};
        String[] headers() default {};
        String[] consumes() default {};
        String[] produces() default {};
    }
    
    • name表示这个注解的名称,
    • value和path可以共用;
    • method表示支持的RequestMethod的种类包括get,post等
    • params 表示指定request中必须包含某些参数值是,才让该方法处理。
    • headers指定request中必须包含某些指定的header值,才能让该方法处理请求
    • consumes表示指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
    • produces 表示返回内容的类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回
      当consumes或者produces不满足时,返回http403,不支持的媒体类型

    Autowired and Resource

    • Autowired 是Spring提供的注解,默认按类型注入,找不到或者找到俩个相同类型bean则报错,可以和@Qualifier一起搭配使用,表示找不到type则根据name查找
    @Autowired
    @Qualifier("userDao")
    
    • Resource默认按名称查找
      -- 指定了name则按name查找,找不到抛异常
      -- 指定了type按type查找,无需使用类似于 @Resource(type=Car.class) 的注释方式,因为 Bean 的类型信息可以通过Java 反射从代码中获取。
      -- 指定了name和type,则按按俩者寻找符合条件的唯一的bean,找不到报错
      -- 如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配

    @PathVariable

    将请求中的变量映射到方法参数上,同时还对变量支持正则表达式

     @RequestMapping(value = "/sayhello/{type:[a-z-]+}", method = {RequestMethod.GET}, consumes = MediaType.APPLICATION_JSON_VALUE,produces = MediaType.APPLICATION_JSON_VALUE)
        @ResponseBody
        public String say(@PathVariable String type, String word) {
            return type + word;
        }
    

    @RequestParam

    功能相当于request.getParameter("name"),有三个属性,value指定映射的字段名称,required=false表示该属性不是必传的,defaultValue可以指定该属性的默认值。当url有俩个word时,会默认把俩个word的value合并成一个String.
    当该注解使用在Map<String, String> or MultiValueMap<String, String>这些类型上时,就可以匹配所有的入参

    @RequestBody和@ResponseBody

    • @RequestBody是把request body里面的数据绑定到参数上
    • @ResponseBody是把返回类型写到HTTP response body
      俩者都使用系统默认的HttpMessageConverter进行解析,@RequestBody使用header部分的Content-Type的格式解析,如果没有,则报错,@ResponseBody根据Request对象的header部分的Accept属性(逗号分隔),逐一按accept中的类型,去遍历能处理的HttpMessageConverter,Accept属性为空,则默认按所有的MediaType类型去匹配。
        如果是application/x-www-form-urlencoded,则是否使用@RequestBody时为可选,也可以用@RequestParam,@ModelAttribute来处理.若是multipart/form-data,@RequestBody不能处理这种格式的数据;而其他的格式,必须使用@RequestBody来处理,包括application/json,application/xml.
        若是PUT方式提交的,也是根据Content-Type的值来判断.application/x-www-form-urlencoded这回是必须用@RequestBody来处理,而multipart/form-data,则同样还是不能处理;其他,也同样还是必须用@RequestBody来处理.

    相关文章

      网友评论

          本文标题:SpringMVC注解

          本文链接:https://www.haomeiwen.com/subject/zsfwpftx.html