Spring注解

1、@RestController
@Controller和@RestController都表示某个类可以接收HTTP请求,@RestController继承自@Controller,@RestController是@Controller和@ResponseBody的结合体,下边这两种方式等效:
@Controller
@ResponseBody
public class MyController { }


@RestController
public class MyRestController { }
2、@ResponseBody
该注解根据HTTP Request Header的Accept的内容,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区,返回数据是JSON或者XML时候使用
@RequestMapping(value = "/user/all", method = RequestMethod.GET)
public @ResponseBody List<User> listAllUsers() {
    return userService.findAllUsers();
}
3、@RequestBody
该注解根据HTTP Request Header的content-Type的内容,通过适当的HttpMessageConverter转换为JAVA类,当POST或者PUT的数据是JSON格式或者XML格式,而不是普通的键值对形式时使用
@RequestMapping(value="/user/create", method=RequestMethod.POST)
public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder){
    System.out.println("Creating User "+user.getName());
     
    if(userService.isUserExist(user)){
        System.out.println("A User with name "+user.getName()+" already exist");
        return new ResponseEntity<Void>(HttpStatus.CONFLICT);
    }
 
    userService.saveUser(user);
     
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
    return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
2、3解释参考 这篇文章

4、@RequestParam
(@RequestParam String name)同样可以用request.getParameter("name")这种方式获取数据,这里的name必须要和前台保持一致,@RequestParam可以用required参数来指定它的必须还是非必须的
@RequestMapping("testRequestParam")    
public String filesUpload(@RequestParam(value="name",required=false) int name), HttpServletRequest request) {    
    System.out.println(name);  
    int age = Integer.valueOf(request.getParameter("age"));  
    System.out.println(age);  
}  
5、@PathVariable
用于将请求URL中的模板变量映射到功能处理方法的参数上。
如果URL是http://localhost:8080/MyApp/user/1234/invoices?date=12-05-2013获取用户1234再2013年12月5号订票数controller如下
@RequestMapping(value="/user/{userId}/invoices", method = RequestMethod.GET)
public List<Invoice> listUsersInvoices(
            @PathVariable("userId") int user,
            @RequestParam(value = "date", required = false) Date dateOrNull) {
}
从3、4、5中可以看出,controller通过标签获取数据的方式有3种, @RequestParam可以传递数组例如:@RequestParam int[] ids;@RequestBody因为是对象也可以传递复杂的数据结构
6、@RequestMapping

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

method:指定请求的method类型, GET、POST、PUT、DELETE等;


consumes,produces;
consumes:指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;

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

源码:
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
	String name() default "";
	String[] value() default {};
	String[] path() default {};
	RequestMethod[] method() default {};
	String[] params() default {};
	String[] headers() default {};
	String[] consumes() default {};
	String[] produces() default {};
}
在@Target中有两个属性,分别为 ElementType.METHOD 和 ElementType.TYPE ,也就是说 @RequestMapping 可以在方法和类的声明中使用
可以看到注解中的属性除了 name() 返回的字符串,其它的方法均返回数组,也就是可以定义多个属性值,例如 value() 和 path() 都可以同时定义多个字符串值来接收多个URL请求

A:value和path属性作用相同,如果只有这一种则可以省略不写
@RequestMapping("/login")
public String login() {
	return "success";
}
带占位符的URL示例,请求的方法必须为GET,可以获取getDay/1,getDay/2等等
@RequestMapping(value="getDay/{day}", method = RequestMethod.GET)  
public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) {  
    return appointmentBook.getAppointmentsForDay(day);  
}  
B:method属性
method 主要用来定义接收浏览器发来的何种请求
@RequestMapping(path = "/login", method=RequestMethod.GET)
public String login() {
	return "success";
}


// 该方法将同时接收通过GET和POST方式发来的请求
@RequestMapping(path = "/login", method={RequestMethod.POST,RequestMethod.GET})
public String login() {
	return "success";
}
C:params属性
该属性表示请求参数,也就是追加在URL上的键值对,多个请求参数以&隔开
// 该方法将接收 /user/login 发来的请求,且请求参数必须为 username=kolbe&password=123456
@RequestMapping(path = "/login", params={"username=kolbe","password=123456"})
public String login() {
	return "success";
}
D:headers属性
该属性表示请求头
用于HTTP协义交互的信息被称为HTTP报文,客户端发送的HTTP报文被称为请求报文,服务器发回给客户端的HTTP报文称为响应报文,报文由报文头部和报文体组成。

请求头部(Request Headers):请求头包含许多有关客户端环境和请求正文的信息,例如浏览器支持的语言、请求的服务器地址、客户端的操作系统等。

响应头部(Rsponse Headers):响应头也包含许多有用的信息,包括服务器类型、日期、响应内容的类型及编码,响应内容的长度等等。
Request Headers
    Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
    Accept-Encoding:gzip, deflate, sdch
    Accept-Language:zh-CN,zh;q=0.8
    Cache-Control:max-age=0
    Connection:keep-alive
    Cookie:JSESSIONID=210075B5E521CWE3CDE938076295A57A
    Host:localhost:8080
    Upgrade-Insecure-Requests:1
    User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93
	
// 表示只接收本机发来的请求
@RequestMapping(path = "/login", headers="Host=localhost:8080")
public String login() {
	return "success";
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值