springmvc学习笔记二REST风格的URL

**

web.xml

配置 org.springframework.web.filter.HiddenHttpMethodFilter: 可以把 POST 请求转为 DELETE 或 POST 请求
**

<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>

**

jsp:

**
< form action=“springmvc/testRest/1” method=“post”>
< input type=“hidden” name="_method" value=“PUT”/>
< input type=“submit” value=“TestRest PUT”/>
</f orm>

<form  action="springmvc/testRest/1" method="post">
	<input type="hidden" name="_method" value="DELETE"/>
	<input type="submit" value="TestRest DELETE"/>
</form>
<br><br>

<form  action="springmvc/testRest" method="post">
	<input type="submit" value="TestRest POST"/>
</form>
<br><br>

<a href="springmvc/testRest/1">Test Rest Get</a>

**

controller:

**

/**
 * Rest 风格的 URL. 以 CRUD 为例: 新增: /order POST 修改: /order/1 PUT update?id=1 获取:
 * /order/1 GET get?id=1 删除: /order/1 DELETE delete?id=1
 * 
 * 如何发送 PUT 请求和 DELETE 请求呢 ? 1. 需要配置 HiddenHttpMethodFilter 2. 需要发送 POST 请求
 * 3. 需要在发送 POST 请求时携带一个 name="_method" 的隐藏域, 值为 DELETE 或 PUT
 * 
 * 在 SpringMVC 的目标方法中如何得到 id 呢? 使用 @PathVariable 注解
 * 
 */
@RequestMapping(value = "/testRest/{id}", method = RequestMethod.PUT)
public String testRestPut(@PathVariable Integer id) {
	System.out.println("testRest Put: " + id);
	return SUCCESS;
}

@RequestMapping(value = "/testRest/{id}", method = RequestMethod.DELETE)
public String testRestDelete(@PathVariable Integer id) {
	System.out.println("testRest Delete: " + id);
	return SUCCESS;
}

@RequestMapping(value = "/testRest", method = RequestMethod.POST)
public String testRest() {
	System.out.println("testRest POST");
	return SUCCESS;
}

@RequestMapping(value = "/testRest/{id}", method = RequestMethod.GET)
public String testRest(@PathVariable Integer id) {
	System.out.println("testRest GET: " + id);
	return SUCCESS;
}

/**
* @RequestParam 来映射请求参数. value 值即请求参数的参数名 required 该参数是否必须. 默认为 true
* defaultValue 请求参数的默认值
*/
@RequestMapping(value = “/testRequestParam”)
public String testRequestParam(
@RequestParam(value = “username”) String un,
@RequestParam(value = “age”, required = false, defaultValue = “0”) int age) {
System.out.println("testRequestParam, username: " + un + ", age: "
+ age);
return SUCCESS;
}

/**
* 了解: 映射请求头信息 用法同 @RequestParam
*/
@RequestMapping("/testRequestHeader")
public String testRequestHeader(
@RequestHeader(value = “Accept-Language”) String al) {
System.out.println("testRequestHeader, Accept-Language: " + al);
return SUCCESS;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值