您的位置:首页 > 移动开发

springMVC笔记系列(4)——RequestMapping映射特定params和headers

2016-12-02 11:35 429 查看
说明:本文章的内容转载至:https://my.oschina.net/happyBKs/blog/412521

如有侵权的地方,请联系本人,本人将会立即删除!

RequestMapping除了可以映射 特定 value返回值、请求method方法外,还可以对http请求的所有header进行映射。

这样看来,http请求的各个部分都可以进行请求的条件限定来完成 请求向物理视图的映射。

value对应请求的url中的部分。

method对应请求方法。



本文将介绍的是报文头的条件限定和get请求参数的限定。

控制器的get请求参数的限定和头的限定,如下代码的handle2和handle3方法:

package com.happyBKs.springmvc.handlers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@RequestMapping("/c3")
@Controller
public class RMHandler {

@RequestMapping(value="/success",method=RequestMethod.POST)
public String handle()
{

return "successrm";
}

@RequestMapping(value="rq1",params={"username","age=20","!pwd"})
public String handle2()
{
return "age20world";
}

@RequestMapping(value="rq2",headers={"Host=localhost:8080"})
public String handle3()
{
return "age20world";
}
}


请求页面:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
1<br/>
<a href="c3/rq1?username='happyBKs'&age=19">happyBKs age=19</a><br/>
<a href="c3/rq1?age=20">nousername age=20</a><br/>
<a href="c3/rq1?username='happyBKs'&age=20&pwd='hhhh'">happyBKs age=20 pwd</a><br/>
<a href="c3/rq1?username='happyBKs'&age=20">happyBKs age=20</a><br/>

<br/>
2<br/>
<a href="c3/rq2">go</a><br/>

</body>
</html>


结果:

不想啰嗦了。5个链接点击之后的结果。













总结一下:

@RequestMapping(value="rq1",params={"username","age=20","!pwd"})
public String handle2()
{
return "age20world";
}


控制器里面的handle2()方法的 @RequestMapping(value=”rq1”,params={“username”,”age=20”,”!pwd”}) 上面限制了,参数必须有 username,age,但是不能有pwd ,并且age的值必须是20。否则将不能映射该方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring mvc