先上controller的代码
@RequestMapping(path="/user/{id}",method=RequestMethod.POST)
public String add(@PathVariable String id,Model model) {
System.out.println("新建id为"+id+"的学生");
model.addAttribute("hello", "add");
return "hello";
}
@RequestMapping(path="/user/{id}",method=RequestMethod.DELETE)
public String delete(@PathVariable String id,Model model) {
System.out.println("删除id为"+id+"的学生");
model.addAttribute("hello", "add");
return "hello";
}
@RequestMapping(path="/user",method=RequestMethod.DELETE)
public String deleteAll(Model model) {
System.out.println("删除全部的学生");
model.addAttribute("hello", "deleteall");
return "hello";
}
@RequestMapping(path="/user/{id}",method=RequestMethod.PUT)
public String updat(@PathVariable String id,Model model) {
System.out.println("更新id为:"+"的学生");
model.addAttribute("hello", "update");
return "hello";
}
@RequestMapping(path="/user/{id}",method=RequestMethod.GET)
public String get(@PathVariable String id,Model model) {
System.out.println("获得id为:"+"的学生");
model.addAttribute("hello", "get");
return "hello";
}
@RequestMapping(path="/user",method=RequestMethod.GET)
public String getall(Model model) {
System.out.println("获得所有的学生");
model.addAttribute("hello", "getall");
return "hello";
}
jsp的form表单只支持post,get请求,因此对于其他请求方式,我们需要使用 并配置org.springframework.web.filter.HiddenHttpMethodFilter
jsp代码如下:
<body>
form action="/user/1" method="post"
<form action="${pageContext.request.contextPath}/user/1" method="post">
<input type="submit"/>
</form>
<br/>
form action="${pageContext.request.contextPath}/user" method="get"
<form action="${pageContext.request.contextPath}/user" method="get">
<input type="submit"/>
</form>
<br/>
form action="${pageContext.request.contextPath}/user/1" method="get"
<form action="${pageContext.request.contextPath}/user/1" method="get">
<input type="submit"/>
</form><br/>
form action="${pageContext.request.contextPath}/user/1" method="put"
<form action="${pageContext.request.contextPath}/user/1" method="post">
<input type="hidden" name="_method" value="put" />
<input type="submit"/>
</form><br/>
</body>
接着配置web.xml添加filter
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<servlet-name>spring</servlet-name>
</filter-mapping>
spring为你的DispatcherServlet的名称。
接下来表单提交的put请求就会到达正确的controller。但是接下来你会发现spring mvc无法返回正确的视图.例如上述的update方法无法正确的返回到hello.jsp。这时
这里三种解决办法
1.如果你是用的是tomcat8,把它换成tomcat7
2.将forward换成redirect
3.自己手动写一个Filter来包装HttpRequest中的getMethod()方法