3.SpringMvc-RestFul API
概念
Restful 表述性状态传递,简单来说 就是一种更简洁的URL风格,通过URL中的名词确定要什么(操作哪些表),通过请求的Method 确定做什么。
-
查询用户: http://localhost:8080/xxx/user/1 GET 查询
-
查询多个用户: http://localhost:8080/xxx/users GET
-
新增用户: http://localhost:8080/xxx/user POST
-
http://localhost:8080/xxx/user/1 PUT 修改
-
删除用户:http://localhost:8080/xxx/user/1 DELETE 删除
HTTP请求的方式包括四种,通常用于以下功能
get请求 用于 查询
post请求 用于 做添加
put请求 用于 修改
delete请求 用于删除。
HTTP协议支持上述的四种请求方式,
1.HTML语言本身不支持 DELETE 和 PUT请求,既在form中 method="delete(put)"无效
2.Js的AJAX是支持 PUT 和 DELETE请求的
1.GET请求
表单中 请求方式method 使用 GET,Controller中的方法上 使用
RequestMapping("...",method ="RequestMethod.GET")
或者是 GetMapping("...")
@RequestMapping("/hello",method ="RequestMethod.GET)
public String hello(Model model){
model.addAttribute("msg","hello,SpringMVC");
return "hello";
}
2.POST请求
表单中 method使用 POST,Controller中
可以使用 PostMapping
@RequestMapping("/hello",method ="RequestMethod.POST)
public String hello(Model model){
model.addAttribute("msg","hello,SpringMVC");
return "hello";
}
3.Put请求
由于HTML本身并不支持 PUT请求
所以 表单中 请求方式 设置为 post
1 在表单中 添加隐藏域 <input type="hidden" name="_method" value="PUT" />
2 在web.xml中 配置 springmvc提供的 额外请求方式的过滤器
HiddenHttpMethodFilter
3 在Controller 中使用
PutMapping 注解在方法上
ps:由于tomcat 7以后的版本,对jsp页面跳转方式 更为严格,所以当跳转页面是一个jsp页面时,不能使用post
处理方式:
1.把页面的跳转方式 修改为重定向
2.在jsp的 page指令中 加入 isErrorPage="true"
3.换成tomcat 7
@RequestMapping("/user/{id}/{username}",method ="RequestMethod.PUT)
public String path01(@PathVariable("id") Integer id,@PathVariable("username") String name){
System.out.println(id);
System.out.println(name);
return "/index.jsp";
}
4.Delete请求:
同上 把隐藏域的value 改成Delete
注解使用 DeleteMapping
@RequestMapping("/user/{id}",method ="RequestMethod.DELETE)
public String path01(@PathVariable("id") Integer id){
System.out.println(id);
return "/index.jsp";
}
作者:涛哥
链接:https://ltbk.net/back/spring_family/springmvc/article/902.html
文章版权归作者所有,未经允许请勿转载。