实例:
SpringMVCTest.java
-
//@PathVariable可以用来映射URL中的占位符到目标方法的参数中
-
@RequestMapping(
”/testPathVariable/{id}”)
-
public
String
testPathVariable
(@
PathVariable
(”id”) Integer id)
-
{
-
System.
out.println(
”testPathVariable:”+id);
-
return SUCCESS;
-
}
index.jsp
<a href="springmvc/testPathVariable/1">testPathVariablea>
示例:
- /order/1 HTTP GET :得到 id = 1 的 order
- /order/1 HTTP DELETE:删除 id = 1的 order
- /order/1 HTTP PUT:更新id = 1的 order
- /order HTTP POST:新增 order
HiddenHttpMethodFilter:浏览器 form 表单只支持 GET与 POST 请求,而DELETE、PUT 等 method 并不支持,Spring3.0 添加了一个过滤器,可以将这些请求转换为标准的 http 方法,使得支持 GET、POST、PUT 与DELETE 请求。
web.xml
-
-
-
<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>
SpringMVCTest.java
-
/*
-
* 如何发送PUT和DELETE请求
-
* 1.需要配置HiddenHttpMethodFilter
-
* 2.需要发送POST请求
-
* 3.需要发送POST请求时携带一个name="_method"的隐藏域,value值为DELETE或者PUT
-
*
-
* 在springmvc框架中通过@PathVariable注解来获取id值
-
* */
-
//get请求
-
@RequestMapping(
value=
"/testRest/{id}",method=RequestMethod.GET)
-
public
String
testRest
(@PathVariable Integer id)
-
{
-
System.
out.println(
"testRest Get"+id);
-
return SUCCESS;
-
}
-
-
//post请求
-
@RequestMapping(
value=
"/testRest",method=RequestMethod.POST)
-
public
String
testRest
()
-
{
-
System.
out.println(
"testRest POST");
-
return SUCCESS;
-
}
-
-
//delete请求
-
@RequestMapping(
value=
"/testRest/{id}",method=RequestMethod.DELETE)
-
public
String
testRestDelete
(@PathVariable Integer id)
-
{
-
System.
out.println(
"testRest DELETE"+id);
-
return SUCCESS;
-
}
-
-
//修改请求
-
@RequestMapping(
value=
"/testRest/{id}",method=RequestMethod.PUT)
-
public
String
testRestPut
(@PathVariable Integer id)
-
{
-
System.
out.println(
"testRest PUT"+id);
-
return SUCCESS;
-
}
index.jsp
-
<a href=
"springmvc/testRest/1"
>Test Rest Get
a>
<br/>
-
<form action=
"springmvc/testRest"
method
=
"post"
>
-
<input
type=
"submit"
value
=
"TestRest Post"
/>
-
form>
<br/>
-
<form action=
"springmvc/testRest/1"
method
=
"post"
>
-
<input
type=
"hidden"
name=
"_method"
value
=
"DELETE"
/>
-
<input
type=
"submit"
value
=
"TestRest DELETE"
/>
-
form>
<br/>
-
<form action=
"springmvc/testRest/1"
method
=
"post"
>
-
<input
type=
"hidden"
name=
"_method"
value
=
"PUT"
/>
-
<input
type=
"submit"
value
=
"TestRest PUT"
/>
-
form>
<br/>