【SpringMVC入门系列】篇3:@RequestMapping & @RequestHeader & @CookieValue详解与REST风格请求

时间:2020-07-05 19:40:06   收藏:0   阅读:71

一、@RequestMapping

1.@RequestMapping

二、REST请求风格

我们平时使用的请求都是get请求后面加参数的形式,例如:

<a href="${pageContext.request.contextPath}/first?id=101&name=thinmoon">跳转</a>

REST风格请求

传统的CRUD操作我们一般使用以下形式:

http://localhost:8080/get.action?id=10  	  查询 get
http://localhost:8080/add.action              新增 post
http://localhost:8080/update.action           修改 post
http://localhost:8080/delete.action?id=10     删除 post

使用rest风格我们可以写成以下形式:

http://localhost:8080/goods/1		查询GET
http://localhost:8080/goods			新增POST
http://localhost:8080/goods			更新PUT
http://localhost:8080/goods/1		删除DELETE

可以看到,我们通过url直接定位到资源,然后利用请求方式的不同进行CRUD操作。

rest风格请求使用

假设我们有get请求如下:

<a href="${pageContext.request.contextPath}/first/1">跳转first</a>

我们可以在控制器中这样接收:

@RequestMapping("/first/{id}")
public String show(@PathVariable Integer id) {

    System.out.println(id);
    return "/first.jsp";
}

form表单put与delete请求

默认情况下Form表单是不支持PUT请求和DELETE请求的,spring3.0添加了一个过滤器HiddenHttpMethodFilter,可以将post请求转换为PUT或DELETE请求。

在web.xml中配置如下过滤器:

<!--配置HiddenHttpMethodFilter 实现rest风格请求-->
<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>

假如我们有以下form表单请求:注意要使用POST

<form action="${pageContext.request.contextPath}/rest" method="post">
    <%--定义一个隐藏表单 name值必须为_method value为请求方式--%>
    <input type="hidden" name="_method" value="put">
    <input type="text" name="name" value="Thinmoon">
    <input type="submit" value="提交">
</form>

我们在表单中定义一个隐藏表单,是我们程序可以使用put请求方式接收。

@RequestMapping(value = "/rest", method = RequestMethod.PUT)
public String show5(String name) {
System.out.println(name);
return "toAnother";
}

@RequestMapping("toAnother")
public String show6() {
return "redirect:first.jsp";
}

注入事项:

上面代码如果直接请求转发到jsp页面会发生405错误 JSPs only permit GET POST or HEAD**

解决方式:

三、@RequestHeader & @CookieValue

我们可以通过@RequestHeader和@CookieValue获取请求头与cookie信息

@RequestMapping("testHeader")
public String show7(@RequestHeader("Host") String host,
@RequestHeader("Referer") String referer,
@RequestHeader("Cookie") String cookie,
@CookieValue("JSESSIONID") String jsessionid) {
System.out.println(host);
System.out.println(referer);
System.out.println(cookie);
System.out.println(jsessionid);
return "first.jsp";
}
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!