RequestMapping注解用于映射url到控制器类或一个特定的处理程序方法。可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
首先是作用的地方
//RequestMapping作用于方法上
//请求的url:http://127.0.0.1 / 项目名 / h1
@Controller
public class ControllerDemo {
@RequestMapping("/h1")
public String hello1(Model model){
model.addAttribute("msg","HelloSpringMVC");
return "to";
}
}
作用在类上
//请求的url:http://127.0.0.1 / 项目名/hello / h1
@Controller
@RequestMapping("/hello")
public class ControllerDemo {
@RequestMapping("/h1")
public String hello1(Model model){
model.addAttribute("msg","HelloSpringMVC");
return "to";
}
}
可以指定处理 HTTP 请求的方法
GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE
使用方法
@RequestMapping(value = "/h1",method = RequestMethod.GET)
不过存在几个方法的变体
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
重点是get方法,因为默认的get方式,提交的参数会显示在url路径上,非常不安全
@Controller
public class ControllerDemo {
@RequestMapping("/h1")
public String hello1(int a,int b,Model model){
int res=a+b;
model.addAttribute("msg",""+a+"+"+b+"="+res);
return "to";
}
}
所以通常会使用Restful风格的提交方式 @PathVariable用于显示地将url映射参数到方法参数
@Controller
public class ControllerDemo {
@RequestMapping(value = "/h1/{a}/{b}",method = RequestMethod.GET)
public String hello1(@PathVariable int a,@PathVariable int b,Model model){
int res=a+b;
model.addAttribute("msg",""+a+"+"+b+"="+res);
return "to";
}
}