您的位置:首页 > 编程语言 > Java开发

spring常用注解使用讲解

2016-07-16 19:57 507 查看
spring常用注解使用讲解

本文讲述spring的几个常用的注解

@RequestMapping 

@RequestParam

@ResponseBody

@RequestBody

@Autowired

一、@RequestMapping 

RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。

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值,才能让该方法处理请求。


示例:


1.value  / method 示例

默认RequestMapping("....str...")即为value的值;

@Controller
@RequestMapping("/appointments")
public class AppointmentsController {

private AppointmentBook appointmentBook;

@Autowired
public AppointmentsController(AppointmentBook appointmentBook) {
this.appointmentBook = appointmentBook;
}

@RequestMapping(method = RequestMethod.GET)
public Map<String, Appointment> get() {
return appointmentBook.getAppointmentsForToday();
}

@RequestMapping(value="/{day}", method = RequestMethod.GET)
public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) {
return appointmentBook.getAppointmentsForDay(day);
}

@RequestMapping(value="/new", method = RequestMethod.GET)
public AppointmentForm getNewForm() {
return new AppointmentForm();
}

@RequestMapping(method = RequestMethod.POST)
public String add(@Valid AppointmentForm appointment, BindingResult result) {
if (result.hasErrors()) {
return "appointments/new";
}
appointmentBook.addAppointment(appointment);
return "redirect:/appointments";
}
}


value的uri值为以下三类:

A) 可以指定为普通的具体值;

B)  可以指定为含有某变量的一类值(URI Template Patterns with Path Variables);

C) 可以指定为含正则表达式的一类值( URI Template Patterns with Regular Expressions);

 example B)

@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable String ownerId, Model model) {
Owner owner = ownerService.findOwner(ownerId);
model.addAttribute("owner", owner);
return "displayOwner";
}


example C)

@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\d\.\d\.\d}.{extension:\.[a-z]}")
public void handle(@PathVariable String version, @PathVariable String extension) {
// ...
}
}



2 consumes、produces 示例

cousumes的样例:

@Controller
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) {
// implementation omitted
}


方法仅处理request Content-Type为“application/json”类型的请求。

produces的样例:

@Controller
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {
// implementation omitted
}


方法仅处理request请求中Accept头中包含了"application/json"的请求,同时暗示了返回的内容类型为application/json;

返回中文样例

@Controller
@RequestMapping(value = "/pets/{petId}",produces="text/html;charaset=UTF-8")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {
// implementation omitted
}


 3.params、headers 示例

params的样例:

@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {

@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue")
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
// implementation omitted
}
}


仅处理请求中包含了名为“myParam”,值为“myValue”的请求;

headers的样例:

@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {

@RequestMapping(value = "/pets", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com/")
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
// implementation omitted
}
}


仅处理request的header中包含了指定“Refer”请求头和对应值为“
http://www.ifeng.com/
”的请求;
二、@RequestParam

@RequestParam用于将请求参数区数据映射到功能处理方法的参数上。

[java] view
plain copy

public String requestparam1(@RequestParam String username)  

请求中包含username参数(如/requestparam1?username=zhang),则自动传入。

 

此处要特别注意:右击项目,选择“属性”,打开“属性对话框”,选择“Java Compiler”然后再打开的选项卡将“Add variable attributes to generated class files”取消勾选,意思是不将局部变量信息添加到类文件中,如图6-12所示:



 图6-12

当你在浏览器输入URL,如“requestparam1?username=123”时会报如下错误

Name for argument type [java.lang.String] not available, and parameter name information not found in class file either,表示得不到功能处理方法的参数名,此时我们需要如下方法进行入参:

 

[java] view
plain copy

public String requestparam2(@RequestParam("username") String username)  

 即通过@RequestParam("username")明确告诉Spring Web MVC使用username进行入参。

接下来我们看一下@RequestParam注解主要有哪些参数:

value:参数名字,即入参的请求参数名字,如username表示请求的参数区中的名字为username的参数的值将传入;

required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报404错误码;

defaultValue:默认值,表示如果请求中没有同名参数时的默认值,默认值可以是SpEL表达式,如“#{systemProperties['java.vm.version']}”。

 

[java] view
plain copy

public String requestparam4(@RequestParam(value="username",required=false) String username)   

 表示请求中可以没有名字为username的参数,如果没有默认为null,此处需要注意如下几点:

 

     原子类型:必须有值,否则抛出异常,如果允许空值请使用包装类代替。

     Boolean包装类型类型:默认Boolean.FALSE,其他引用类型默认为null。

 

[java] view
plain copy

public String requestparam5(  

@RequestParam(value="username", required=true, defaultValue="zhang") String username)   

          

表示如果请求中没有名字为username的参数,默认值为“zhang”。

 

 

如果请求中有多个同名的应该如何接收呢?如给用户授权时,可能授予多个权限,首先看下如下代码:

[java] view
plain copy

public String requestparam7(@RequestParam(value="role") String roleList)  

如果请求参数类似于url?role=admin&rule=user,则实际roleList参数入参的数据为“admin,user”,即多个数据之间使用“,”分割;我们应该使用如下方式来接收多个请求参数:

[java] view
plain copy

public String requestparam7(@RequestParam(value="role") String[] roleList)     



 

[java] view
plain copy

public String requestparam8(@RequestParam(value="list") List<String> list)      

 到此@RequestParam我们就介绍完了,以上测试代码在cn.javass.chapter6.web.controller. paramtype.RequestParamTypeController中。

三、@ResponseBody

作用: 

      该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。

使用时机:

      返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;

eg:返回json

@ResponseBody
@RequestMapping(value = "/GetAllBU", produces = "text/html;charset=UTF-8")
public String Get(){
List<MetaBuList> retBUList = new List<MetaBuList>();
String ret=JSON.toJSONString(retBUList);
return ret;
}四、@RequstBody

作用: 

      i) 该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上;

      ii) 再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。

使用时机:

A) GET、POST方式提时, 根据request header Content-Type的值来判断:
    application/x-www-form-urlencoded, 可选(即非必须,因为这种情况的数据@RequestParam, @ModelAttribute也可以处理,当然@RequestBody也能处理);
    multipart/form-data, 不能处理(即使用@RequestBody不能处理这种格式的数据);
    其他格式, 必须(其他格式包括application/json, application/xml等。这些格式的数据,必须使用@RequestBody来处理);

 

B) PUT方式提交时, 根据request header Content-Type的值来判断:

 
    application/x-www-form-urlencoded, 必须;
    multipart/form-data, 不能处理;
    其他格式, 必须;

说明:request的body部分的数据编码格式由header部分的Content-Type指定;
五、@Autowired

• 例如

         @Autowired

          private ISoftPMService softPMService;

       • 或者

       @Autowired(required=false)

       private ISoftPMService softPMService = new SoftPMServiceImpl();

      • 说明

     @Autowired 根据bean 类型从spring 上线文中进行查找,注册类型必须唯一,否则报异常。与@Resource 的区别在于,@Resource 允许通过bean 名称或bean 类型两种方式进行查找@Autowired(required=false) 表示,如果spring 上下文中没有找到该类型的bean 时, 才会使用new SoftPMServiceImpl();

@Autowired 标注作用于 Map 类型时,如果 Map 的 key 为 String 类型,则 Spring 会将容器中所有类型符合 Map 的 value 对应的类型的 Bean 增加进来,用 Bean 的 id 或 name 作为 Map 的 key。

  @Autowired 还有一个作用就是,如果将其标注在 BeanFactory 类型、ApplicationContext 类型、ResourceLoader 类型、ApplicationEventPublisher 类型、MessageSource 类型上,那么 Spring 会自动注入这些实现类的实例,不需要额外的操作。

上面第一个只是声明了一下对象,但是未对其进行初始化,但是添加了@Autowired,这样spring会自动搜索然后对其进行初始化,所以说注册类型必须唯一,不然会报异常,因为他是根据bean类型在上下文进行查找的,而且都要权限是private 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: