SpingMVC常见标签整理

org.springframework.web.bind.annotation这个包中注解如下图,该包中的注解的作用是绑定参数和方法,比如@CookieValue是将前端的Cookie值和目标方法的参数绑定. @RequestParam 和 @ PathVariable 也是绑定 请求的参数 和 url 路径中的值!

 

1、@RequestMapping

RequestMapping是一个用来处理请求地址映射的注解,将URL和目标方法绑定起来. 可用于类或方法上。用于类上,表示类中的所有响应请求的方法 都是以该地址作为父路径,类和方法共同组成的字符串才是一个完整的url.

@Target({java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping{
  String[] value() default {};
  
  RequestMethod[] method() default {};
  
  String[] params() default {};
  
  String[] headers() default {};
  
  String[] consumes() default {};
  
  String[] produces() default {};
}

RequestMapping注解有六个属性,下面我们把她分成三类进行说明(下面有相应示例)。

1、 value, method;

value:     指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);

method:  指定请求的method类型, GET(查)、POST(增)、PUT(改)、DELETE(删)等;

2、consumes,produces

consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;

produces:    指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;

3、params,headers

params: 指定request中必须包含某些参数值是,才让该方法处理。

headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。

2、@PathVariable

这个注解用来修饰handler类  方法参数的,被修饰的参数会将url 中的参数赋值给参数,方法内部就可以使用了.

//只能修饰参数
@Target({java.lang.annotation.ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PathVariable
{
   String value() default "";
}

用于将请求URL中的模板变量映射到功能处理方法的参数上,即取出uri模板中的变量作为参数。如:

public class TestController {  
     @RequestMapping(value="/user/{userId}/roles/{roleId}",method = RequestMethod.GET)  
     public String getLogin(@PathVariable("userId") String userId,  
         @PathVariable("roleId") String roleId){  
         System.out.println("User Id : " + userId);  
         System.out.println("Role Id : " + roleId);  
         return "hello";  
     }  
     @RequestMapping(value="/product/{productId}",method = RequestMethod.GET)  
     public String getProduct(@PathVariable("productId") String productId){  
           System.out.println("Product Id : " + productId);  
           return "hello";  
     }  
   //还可以用正则表达式
     @RequestMapping(value="/javabeat/{regexp1:[a-z-]+}",  
           method = RequestMethod.GET)  
     public String getRegExp(@PathVariable("regexp1") String regexp1){  
           System.out.println("URI Part 1 : " + regexp1);  
           return "hello";  
     }  
}

 3、@RequestParam

根据请求参数来进行参数绑定 .分为get 请求和post请求    

1. get请求通过url直接获取参数名,就可以在目标方法的参数中绑定数据.

2.  如果是ajax 中的get 或 post 请求,可以通过前端的参数名来获取参数.

     如果是form表单,则可以通过标签中的name 属性作为参数的名. 

该注解只能修饰参数. 有三个参数,  value 参数名,   required 这个参数是否是必须的.   defultVaule 默认值.

4、@CookieValue

客户端进行的每一次请求都会将cookie值带到后端.可以通过这个标签将cookie的key作为@cookieValue的值,用来标注参数,这样完成参数的赋值.

5、@ModelAttribute(重要)

@Target({java.lang.annotation.ElementType.PARAMETER,java.lang.annotationElementType.METHOD}) //修饰参数和方法
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ModelAttribute{
       String value() default "";
}

该注解 标注 在  参数 和 方法  . 绑定在 这个注解的对象,可以在 request 作用域中使用,也就是在一次请求中可以使用 这个对象, 如果想在整个session 中使用,则要用@SessionAttribute

1. 当我们请求 /myTest/sayHello.do 的时候使用 @ModelAttribute 标记的方法会先执行,然后把它们返回的对象存放到模型中。最终访问到 sayHello 方法的时候

@Controller
@RequestMapping ( "/myTest" )
public class MyController {
   //首先执行,hello 是model 的key 返回值 是这个model 的value..以下 同理
    @ModelAttribute ( "hello" )
    public String getModel() {
       System. out .println( "-------------Hello---------" );
       return "world" ;
    }
   //首先执行
    @ModelAttribute ( "intValue" )
    public int getInteger() {
       System. out .println( "-------------intValue---------------" );
       return 10;
    }

    @RequestMapping ( "sayHello" )
  //参数被@ModelAttribute标注的参数都会被赋值.在目标方法中可以使用
public void sayHello( @ModelAttribute ( "hello" ) String hello, @ModelAttribute ( "intValue" ) int num, @ModelAttribute ( "user2" ) User user, Writer writer, HttpSession session) throws IOException { writer.write( "Hello " + hello + " , Hello " + user.getUsername() + num); writer.write( " " );
    //session域中并没有值,ModelAttribute作用域只是在request域中 Enumeration enume
= session.getAttributeNames(); while (enume.hasMoreElements()) writer.write(enume.nextElement() + " " ); }    //首先执行 @ModelAttribute ( "user2" ) public User getUser(){ System. out .println( "---------getUser-------------" ); return new User(3, "user2" ); } }

 如果想把@ModelAttribute ( "key" )中的值放到Seeion中,只需要在这个类上加上@SessionAttribute("里面放的是@ModelAttribute的key").就可以把request域放到Session域中.

还有一些其他的使用地方,如下

1

  public class HelloWorldController {  
  
        @ModelAttribute  // abc 是请求参数的名
        public void populateModel(@RequestParam String abc, Model model) {  
           model.addAttribute("attributeName", abc);  
        }  
  
        @RequestMapping(value = "/helloWorld")  
        public String helloWorld(在这里面,可以将@ModelAttribute的值写进去啊) {  
           return "helloWorld";  
        }  
    }

2

public Account addAccount(@RequestParam String number) {  
       return accountManager.findAccount(number);  
}  

 这种情况,model属性的名称没有指定,它由返回类型隐含表示,如这个方法返回Account类型,那么这个model属性的名称是account。
    这个例子中model属性名称有返回对象类型隐含表示,model属性对象就是方法的返回值。它无须要特定的参数。

3

public class HelloWorldController {  
  
        @RequestMapping(value = "/helloWorld.do")  
        @ModelAttribute("attributeName")  
        public String helloWorld() {  
             return "hi";  
} 

 这时这个方法的返回值并不是表示一个视图名称,而是model属性的值,视图名称由RequestToViewNameTranslator根据请求"/helloWorld.do"转换为逻辑视图helloWorld。
    Model属性名称有@ModelAttribute(value=””)指定,相当于在request中封装了key=attributeName,value=hi。

6、@SessionAttribute

用法比较简单,就是标注在类上,就可以把目标方法参数Map中的值,比如

@SessionAttributes(value={"names"},types={Integer.class})
@Controller
public class Test {

    @RequestMapping("/test")
    public String test(Map<String,Object> map){
        map.put("names", Arrays.asList("caoyc","zhh","cjx"));
        map.put("age", 18);
        return "hello";
    }
}

本来这个map 是request域的,现在成了session域

@ModelAttribute中的值放到Seeeion域中上面已介绍.

7.@RequestBody

将目标方法参数和Content-Type 中的数据绑定起来.

@Target({java.lang.annotation.ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestBody
{
  boolean required() default true;
}

客户端发送一个请求,请求头中 Content-Type : application/json , application/xml 表示请求的数据 是一个json串或者xml . 并非Accept-type是json或者xml 

这个时候springMVC 就可以通过这个注解将请求来的 json 或者xml 和相应的Bean进行绑定,这个时候需要定义一个bean ,和josn 中的key 要一样,才能完成绑定. 

它是通过使用HandlerAdapter 配置的 MessageConverters来解析post data body,然后绑定到相应的bean上的。这个注解的使用需要HttpMessageConverter 来完成json 到 bean 之间的转换.

8.@RequestHeader

感觉和CookieValue一样,将RequestHeader中的值赋给目标方法参数.

9.@ResponseBody

该注解标注类和方法.

@Target({java.lang.annotation.ElementType.TYPE, java.lang.annotation.ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ResponseBody {

}

1.标注方法的时候,会将返回值转成josn或xml 

@RequestMapping("/testResponseBody")
@ResponseBody
public Person testResponseBody() {
        Person p = new Person();
        p.setName("xiaohong");
        p.setAge(12);
       //返回值,放到这个  HttpResponse 中content中  
        return p;
}

2 .@ResponseBody又可以加在类上,表示该类中的所有方法都加有@ResponseBody,很方便。另一种方式是使用@RestController注解在类上,作用等于@Controller与@ResponseBody同时加在类上,这也是最方便的一种方式。要让@ResponseBody在类上也起作用,需要在springmvc配置文件中加上<mvc:annotation-driven />这一行配置才可以。而@ResponseBody使用在方法上,则不用添加该配置也可以使用。也就是说springmvc默认只支持@ResponseBody在方法上使用,不支持在类上的使用。

原文地址:https://www.cnblogs.com/stevehu1231/p/7828305.html