RESTful架构,就是目前最流行的一种互联网软件架构。它结构清晰、符合标准、易于理解、扩展方便,所以正得到越来越多网站的采用。
RESTful就是HTTP协议的四种形式的基本操作
GET:获取资源
POST:新建资源
PUT:修改资源
DELETE:删除资源
使用RESTful的配置要点
默认只能处理get和POST请求,而delete和put请求实际上是无法处理的
解决办法:可以通过一种方法将POST请求转换为put和delete请求
1、在web.xml中配置HiddenHttpMethodFilter过滤器
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2、页面的form表单中需要添加input的隐藏域,用于后端解析PUT和DELETE,如下:
<input type="hidden" name="_method" value="PUT"/>
<input type="hidden" name="_method" value="DELETE"/>
GET
from表单中method=get
/getById/${course.id}在路径后面直接跟上参数值,不在使用/getById?id=XX这种url类型风格
<form action="${pageContext.request.contextPath}/getById/${course.id}" method="get">
<button class="btn btn-primary btn-sm edit_btn" type="submit">
<span class="glyphicon glyphicon-pencil">编辑</span>
</button>
</form>
get请求使用@GetMapping,表示只有get请求才能访问
@GetMapping(value="/getById/{id}"):{×××}占位符,请求的URL可以是“/getById/1”或“/getById/2”,通过在方法中使用@PathVariable获取{×××}中的×××变量。
@PathVariable用于将请求URL中的模板变量映射到功能处理方法的参数上。
如果GetMapping中表示为"/ getById/{id}",id和形参名称一致,@PathVariable可以不用指定名称。
@GetMapping(value = "/getById/{id}")
public ModelAndView getById(@PathVariable(value = "id") int id){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("edit");
modelAndView.addObject("course",courseDAO.getById(id));
return modelAndView;
}
POST
form表单method=POST
<form class="form-horizontal" role="form" action="${pageContext.request.contextPath}/add" method="post">
POST请求使用@PostMapping,表示POST请求才能访问
@PostMapping(value = “/add”),pojo类型参数使用参数自动绑定
@PostMapping(value = "/add")
public String add(Course course){
courseDAO.add(course);
return "redirect:/getAll";
}
PUT
form表单的method依旧是POST,不过要在表单中添加隐藏域,用于说明这是一个put请求
<form class="form-horizontal" role="form" action="${pageContext.request.contextPath}/update" method="post">
<input type="hidden" name="_method" value="PUT"/>
put请求使用@PutMapping,表示put请求才能访问
@PutMapping(value = "/update")
public String update(Course course){
courseDAO.update(course);
return "redirect:/getAll";
}
DELETE
form表单的method也是POST,也需要在表单中添加隐藏域,用于说明这是一个delete请求
<form action="${pageContext.request.contextPath}/delete/${course.id}" method="post">
<input type="hidden" name="_method" value="DELETE"/>
delete请求使用@DeleteMapping,表示delete请求才能访问
@DeleteMapping(value = "/delete/{id}")
public String delete(@PathVariable(value = "id") int id){
courseDAO.deleteById(id);
return "redirect:/getAll";
}