实现:利用@PathVariable注解,通过占位符方式,让方法参数的值对应绑定到一个URL模板变量上
@Controller public class RestfulController { @RequestMapping("/hello/{a}/{b}") public String restful(@PathVariable int a,@PathVariable int b, Model model){ int res = a+b; model.addAttribute("msg","结果为:"+res); return "hello"; } }
扩展:
注意:默认走到是GET--->相当与@GetMapping
其他的还有,@PostMapping,@PutMapping,@DeleteMapping,使用相应的注解就能实现相应提交方式,
最后达到,同一个url却能实现不同功能,或者说跳转到不同的页面
package com.king.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; @Controller public class RestfulController { @GetMapping("hello/{a}/{b}") public String restful(@PathVariable int a,@PathVariable int b, Model model){ System.out.println("成功了"); int res = a+b; model.addAttribute("msg","结果为:"+res); return "hello"; } @PostMapping("hello/{a}/{b}") public String restfull(@PathVariable int a,@PathVariable int b, Model model){ System.out.println("成功了"); int res = a+b; model.addAttribute("msg","结果为:"+res); return "hello"; } @DeleteMapping("hello/{a}/{b}") public String restfulll(@PathVariable int a,@PathVariable int b, Model model){ System.out.println("成功了"); int res = a+b; model.addAttribute("msg","结果为:"+res); return "hello"; } }
restful风格优点:简洁,高效,安全(不会再url中暴漏参数 )