restful是一种格式,具体来说,就是同一个请求,访问相同的内容,但是用不同的请求方式区分不同的操作。
查询所有信息 get方法,不带参数
查询单个信息 get方法, 带参数
插入信息, post方法,带参数
修改信息, put方法,带参数
删除信息, delete方法,带参数
控制方法
package org.hxut.rj1192.zyk;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class testful_test {
@RequestMapping(value = "/test_restful",method = RequestMethod.GET)
public String query_all()
{ System.out.println("查询所有用户信息");
return "sucess";
}
@RequestMapping(value = "/test_restful/id",method = RequestMethod.GET)
public String query_one(@PathVariable("id") String uid)
{ System.out.println("查询单个用户信息"+uid);
return "sucess";
}
@RequestMapping(value = "test_restful",method = RequestMethod.POST)
public String add_one(int id ,String username)
{
System.out.println("添加单个用户信息"+id+username);
return "sucess";
}
@RequestMapping(value = "test_restful",method = RequestMethod.PUT)
public String change_one(int id ,String username)
{ System.out.println("修改某个用户信息"+id+username);
return "sucess";
}
@RequestMapping(value = "test_restful",method = RequestMethod.DELETE)
public String del_one()
{ System.out.println("删除某个用户信息");
return "sucess";
}
}
前端页面
<!DOCTYPE html >
<html lang="en">
<head>
<meta charset="UTF-8">
<title>请求</title>
</head>
<body>
<a th:href="@{/test_restful}">查询所有用户信息</a>
<a th:href="@{/test_restful/11}">查询id为1的用户信息</a>
<form th:action="@{/test_restful}" method="post">
<input type="text" name="id">
<input type="text" name="username">
<button type="submit">插入单个用户信息</button>
</form>
<form th:action="@{/test_restful}" method="post">
<!-- DispatcherServlet源码 已经设置了拦截器,拦截所有请求,并将_method不为空的请求,转为_method的对应的请求(仅限于PUT DELETE)-->
<input type="hidden" name="_method" value="put">
<input type="text" name="id">
<input type="text" name="username">
<button type="submit">插入单个用户信息</button>
</form>
<form th:action="@{/test_restful}" method="post">
<input type="hidden" name="_method" value="DELETE">
<button type="submit">删除单个用户信息</button>
</form>
</body>
</html>
web.xml
就是所有的请求要给HiddenHttpMthodFilter过滤一遍,如果是post请求,且_method属性不为空,则会将请求类型转为_method属性的值,放行。如果不是post请求,且_method不为空,直接放行
<!-- 拦截所有请求,并交给hiddenhttpmethodfilter 检测否是post请求,且_method不为空,如果是,就将请求类型改为_method的值-->
<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>