1.@PathVariable:路径上的占位符
利用占位符语法可以在任意路径的地方写一个{变量名}
,并且只能占一层路径。
@Controller
public class PathVariableController {
@RequestMapping("/user/{id}")
public String test01(@PathVariable("id")String id){
System.out.println("路径上的占位符:"+id);
return "success";
}
}
2.Rest风格URL
传统的请求方式:
查询1号图书:/getBook?id=1
删除1号图书:/deleteBook?id=1
添加1号图书:/updateBook?id=1
更改1号图书:/insertBook?id=1
Rest风格请求方式:表示对一个资源的增删改查用请求方式来区分
url地址的起名方式:/资源名/资源标识符
/book/1:以get方式提交--查询1号图书
/book/1:以put方式提交--更新1号图书
/book/1:以delete方式提交--删除1号图书
/book/1:以post方式提交--添加1号图书
问题:从页面上只能发起get,post请求,另外两个请求怎么发起?
首先,我们先写处理四种请求方式的方法:
@Controller
public class BookController {
@RequestMapping(value = "/book/{bid}",method = RequestMethod.DELETE)
public String deleteBook(@PathVariable("bid") Integer id){
System.out.println("删除了"+id+"号图书");
return "success";
}
@RequestMapping(value = "/book/{bid}",method = RequestMethod.POST)
public String addBook(@PathVariable("bid") Integer id){
System.out.println("添加了"+id+"号图书");
return "success";
}
@RequestMapping(value = "/book/{bid}",method = RequestMethod.PUT)
public String updateBook(@PathVariable("bid") Integer id){
System.out.println("更新了"+id+"号图书");
return "success";
}
@RequestMapping(value = "/book/{bid}",method = RequestMethod.GET)
public String getBook(@PathVariable("bid") Integer id){
System.out.println("查询了"+id+"号图书");
return "success";
}
}
下面想的是如何发起这四种请求方式??假如使用超链接和表单?
<form action="book/1" method="post">
<input type="submit" value="添加图书"/>
</form>
<a href="book/1">查询图书</a>
<a href="book/1">删除图书</a>
<a href="book/1">更新图书</a>
SpringMvc中有一个Filter,可以将普通的请求转化为规定形式的请求
下面到web.xml中来配置这个Filter:
<!--配置filter拦截所有请求-->
<filter>
<filter-name>methodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>methodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
配置好以后,如何发送其他类型的请求呢?
1.创建一个post
类型的表单
2.表单项中携带一个name=_method
类型的参数
3.这个_method的值value=delete/put
<a href="book/1">查询图书</a>
<form action="book/1" method="post">
<input type="submit" value="添加1号图书"/>
</form>
<form action="book/1" method="post">
<input name="_method" value="put"/>
<input type="submit" value="更新1号图书"/>
</form>
<form action="book/1" method="post">
<input name="_method" value="delete"/>
<input type="submit" value="删除1号图书"/>
</form>
出现这个问题是因为Tomcat版本高,会报错。如何解决?
在跳转页面success.jsp中:加入isErrorPage="true"
<%@ page contentType="text/html;charset=UTF-8"
language="java" isErrorPage="true" %>