0%

springmvc注解的使用

springmvc注解的使用

@RequestMapping

地址映射,可以用在类和方法上,其path支持Ant表达式,用*来表示匹配任意字符,用**来表示统配任意路径,用?来匹配单个字符

1
@RequestMapping(path="/user/*/1")

如果一个请求有多个@RequestMapping能够匹配,通常是更具体的匹配会作为处理此请求的方法

@PathVariable

基于REST风格的API,可以在URI地址上拼接参数

如:get/{id}

@PathVariable中的value值要设置为和地址栏中一致,如@PathVariable(“id”)

@RequestParam

可以接收拼接在地址栏中的参数

如: get?id=1&name=张三

1
@RequestParam("id") int id,@RequestParam("name") String name

@RequestHeader

可以获取请求头参数

@CookieValue

可以绑定请求中的cookie值

@CookieValue(“JSESSIONID”) String sessionId

@SessionAttribute

默认情况下Spring MVC将模型中的数据存储到request域中,当一个请求结束后,数据就失效了,如果要跨页面使用,那么需要使用到session,那么可以使用@SessionAttributes和@SessionAttribute来进行操作

1
2
3
4
5
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface SessionAttributes

@SessionAttributes注解用于类上,就可以使得模型中的数据存储一份到session域中

通过@SessionAttributes存储到session的数据,可以使用三种方式取出

  • 使用session.getAttribute取出
  • 也可以使用Model来获取,model.getAttribute (Model中会存储@SessionAttributes中的参数和@ModelAttribute标识的方法的结果)
  • 也可以直接使用@SessionAttribute来标识参数进行获取
1
2
3
4
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SessionAttribute

@SessionAttribute注解作用于参数上,用于将HttpSession中的属性读出

@InitBinder

用在方法上,说明该方法会注册多个转化器,用来个性化地将HTTP请求参数转化为对应的java对象,如转化为日期类型、浮点类型、JavaBean等

1
2
3
4
5
6
7
8
9
@InitBinder
protected void initBinder(WebDataBinder binder){
binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
}

@RequestMapping("/date")
public void printDate(Date d){
System.out.println(d);
}

@ModelAttribute

可以放到方法上或者参数上,它将方法参数或方法返回值绑定到命名中的Model属性中,然后将其公开给Web视图。如果我们在方法级别使用它,则表明该方法的目的是添加一个或多个模型属性。另一方面,当用作方法参数时,它表示应从模型中检索参数。如果不存在,我们应该首先实例化它,然后将其添加到Model中。一旦出现在模型中,我们应该填充所有具有匹配名称的请求参数的参数字段

1
2
3
4
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ModelAttribute

方法上

标记在方法上,会在每一个@RequestMapping标注的方法前执行,如果有返回值,则自动将该返回值加入到ModelMap中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@ModelAttribute
public void before(@RequestParam("id") String id, Model model){
// 方法返回值为void,所以需要手动添加到model中
model.addAttribute("id",id);
}


@ModelAttribute("name")
public String beforeWith(@RequestParam("name") String name, Model model){
// 将返回结果放入到model中
return name;
}

@RequestMapping("/modelAttributeTest")
public String test(Model model){
Map<String, Object> stringObjectMap = model.asMap();
return "id:"+stringObjectMap.get("id")+",name:"+stringObjectMap.get("name");

}

参数上

标记在方法的参数上,会将客户端传递过来的参数按名称注入到指定对象中,并且会将这个对象自动加入ModelMap中,便于View层使用

1
2
3
4
5
6
7
@RequestMapping("/modelAttributeTest2")
public String testParam(Model model,@ModelAttribute("pass") String pass){
Map<String, Object> stringObjectMap = model.asMap();
return "id:"+stringObjectMap.get("id")+",name:"+stringObjectMap.get("name")
+",pass:"+stringObjectMap.get("pass");

}

欢迎关注我的其它发布渠道