首先看到该类:
@Controller
@RequestMapping("/three")
public class ThreeController {
@RequestMapping("/test")
public String test(int a, int b, Model model){
int c=a+b;
model.addAttribute("msg",c);
return "/test";
}
}
我们访问该资源时,输入的地址:
http://localhost:8080/three/test?a=1&b=2
因为该方法有参数a,b,所以我们需要在url中写入a和b的值。
什么是RestFul风格?
建议百度。
如果我们使用RestFul风格的话,就可以将url写成:
http://localhost:8080/three/test/1/2
也就是说,可以把 ?,&,=…这些都简化成 / 。
使用
关键词:@PathVariable
@Controller
@RequestMapping("/three")
public class ThreeController {
@RequestMapping("/test/{a}/{b}")
public String test(@PathVariable int a,@PathVariable int b, Model model){
int c=a+b;
model.addAttribute("msg",c);
return "/test";
}
}
优点:
简洁,高效,安全
扩张内容
我们可以通过在RequestMapping里面添加methd属性,来完成url的重载:
@Controller
@RequestMapping("/three")
public class ThreeController {
@RequestMapping(value = "/test/{a}/{b}",method = RequestMethod.GET)
public String test(@PathVariable int a,@PathVariable int b, Model model){
int c=a+b;
model.addAttribute("msg",c);
return "/test";
}
@RequestMapping(value = "/test/{a}/{b}",method = RequestMethod.POST)
public String test2(@PathVariable int a,@PathVariable int b, Model model){
int c=a+b;
model.addAttribute("msg",c);
return "/test";
}
}
上面的test的test2方法的内容和url是一样的,但是它会根据 发出的是get请求还是post请求来决定执行test还是test2。
也可以不写RequestMapping,改用 @GetMapping和 @PostMapping。
相关的注解还有:
- @DeleteMapping
- @PutMapping
- …