Controller的使用
Controller | 处理http请求 |
---|---|
@RestController | Spring4之后新加的注解,原来json需要@ResponseBody配合@Controller |
@RequestMapping | 配置url映射 |
thymeleaf了解一下即可,现在的开发方式都是前后端分离的。
@RestController等同于@Controller和@ResponseBody
如果希望访问 http://127.0.0.1:8080/hi 和 http://127.0.0.1:8080/hello 都可以访问到 /hello 接口。在这里需要写成集合。
@RequestMapping(value = {"/hello","hi"},method = RequestMethod.GET)
@RequestMapping还有一种使用方式是给整个类使用。
package com.fiona;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/hello")
public class HelloController {
@Autowired
private GirlProperties girlProperties;
@RequestMapping(value = "/say",method = RequestMethod.GET)
public String say() {
return girlProperties.getCupSize();
}
}
如果要使用除Get以外的其他方式,常用的是Get和Post。改成post请求
@RestController
@RequestMapping("/hello")
public class HelloController {
@Autowired
private GirlProperties girlProperties;
@RequestMapping(value = "/say",method = RequestMethod.POST)
public String say() {
return girlProperties.getCupSize();
}
}
浏览器访问 http://127.0.0.1:8080/hello/say 报405。使用postman选择post方法进行请求。
不写请求方式,Get和Post均可访问到,但不推荐。为了安全起见。
@RequestMapping(value = "/say")
@PathVariable | 获取url中的数据 |
---|---|
@RequestParam | 获取请求参数的值 |
@GetMapping | 组合注解 |
@RestController
@RequestMapping("/hello")
public class HelloController {
@RequestMapping(value = "/say/{id}",method = RequestMethod.GET)
public String say(@PathVariable("id") Integer id) {
return "id:"+id;
}
}
浏览器访问 http://127.0.0.1:8080/hello/say/23
显示 id:23
@RestController
@RequestMapping("/hello")
public class HelloController {
@RequestMapping(value = "/{id}/say",method = RequestMethod.GET)
public String say(@PathVariable("id") Integer id) {
return "id:"+id;
}
}
浏览器请求 http://127.0.0.1:8080/hello/100/say
显示 id:100
@RestController
@RequestMapping("/hello")
public class HelloController {
@RequestMapping(value = "/say",method = RequestMethod.GET)
public String say(@RequestParam("id") Integer id) {
return "id:"+id;
}
}
浏览器请求 http://127.0.0.1:8080/hello/say?id=50
显示 id:50
@RequestParam(“id”)引号里面的名字要和浏览器的变量名一致,但后面但id可以不叫id,取其他名字也可以。
@RestController
@RequestMapping("/hello")
public class HelloController {
@RequestMapping(value = "/say",method = RequestMethod.GET)
public String say(@RequestParam("id") Integer myId) {
return "id:"+myId;
}
}
浏览器请求 http://127.0.0.1:8080/hello/say?id=111
显示 id:111
假如不传id
给id设定一个默认值为0
@RestController
@RequestMapping("/hello")
public class HelloController {
@RequestMapping(value = "/say",method = RequestMethod.GET)
public String say(@RequestParam(value = "id" ,required = false , defaultValue = "0") Integer id) {
return "id:"+id;
}
}
可以使用
@GetMapping(value = "/say")
代替
@RequestMapping(value = "/say",method = RequestMethod.GET)
还有 @PostMapping @PutMapping这样的组合书写。