在Spring4之后,增加了@RestController 这个属性,用来返回json类型的数据,这个注解就相当于是@Controller 和@ ResponseBody 这个注解的结合。
1、注解:@PathVariable
在路径中获取值;
Controller 中编码:
package com.dist.tr.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@ResponseBody
@RequestMapping("/index")
public class IndexController {
@RequestMapping(value = "/{id}/fun",method = RequestMethod.GET)
public String fun(@PathVariable("id") Integer id){
return "id:"+ id;
}
}
运行结果:
可以看见,在路径中我们把id赋值为100的时候,我们从路径中获取到了这个id的值。
2、注解@RequestParam
@PathVariable是restful的风格,如果是普通的在方法名之后加上: ?参数=value 这一种,就用注解@RequestParam
Controller中编码:
package com.dist.tr.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
/**
* Created by Administrator on 2018/3/18.
*/
@Controller
@ResponseBody
@RequestMapping("/index")
public class IndexController {
@RequestMapping(value = "/fun")
public String fun2(@RequestParam("id") Integer myId){
return "id:"+ myId;
}
}
在这儿要知道,方法中@RequestParam(“id”)的id和后面的参数id不指同一个东西,id指实际路径后面的参数的值,譬如地址栏的那个100,而myId 指的是方法中一个参数
运行结果:
如果希望给这个id设置一个默认的值,防止得不到值的时候报空。或者是否默认传参(true传false不传),那么就可以这样写:
@RequestMapping(value = "/fun",method = RequestMethod.GET)
public String fun2(@RequestParam(value = "id",defaultValue = "100",required = false) Integer myId){
return "id:"+ myId;
}
如果在这儿不给id值的话,它就会默认为0;
3、@PostMapping/@GetMapping
如果感觉@RequestMapping里面的属性太多,就可以这两个注解去代替,不难猜到,他就是提交的方式和RequestMapping注解的结合。