Spring MVC 学习笔记 2《请求和参数绑定》

版权声明:大家好,我是笨笨,笨笨的笨,笨笨的笨,转载请注明出处,谢谢! https://blog.csdn.net/jx520/article/details/87490795


来到这里我们已经完成了 SpringMVC 环境搭建,本篇我们只关注具体的使用。

@Controller 声明控制器Bean

Spring 扫描到此注解会为它创建 Bean

@RequestMapping 请求映射到方法

@Controller
@RequestMapping(value = "/test")
public class testController {

	@RequestMapping(value = "/666")
	public String test1() {
		return "test1";
	}
}

将请求映射到控制器的具体方法上,可以在控制器类上使用,也可以在控制器方法上使用。
连起来就是完整路径:http://localhost:80/项目名/test/hello

RequestMapping 属性

属性有多个值时:@RequestMapping(属性= {值1, 值2, 值3} )

属性 说明 举例
value(path) 指定请求URL,可以多个。支持 ANT 风格路径 ,参考 测试代码 AntPathMatcherTests
只有此属性时可以简写为 @RequestMapping(“alias”)
@RequestMapping(value=“alias”)
method 指定请求方式,GET、POST、PUT、DELETE。。。;(默认Get请求)
简化版注解:@GetMapping @PostMapping @PutMapping @DeleteMapping。。。
@RequestMapping(method = RequestMethod.GET)
consumes 请求内容类型(Content-Type)对的上就响应,例如application/json, text/html; @RequestMapping(consumes = “application/json”)
produces 指定返回的内容类型和字符编码,仅当request请求头中的(Accept)类型中包含该指定类型才返回;produces=“application/json” 可以用注解 @ResponseBody 代替 @RequestMapping(produces = “application/json”)
params 指定 request 中参数条件。“param1”, “!param2”, “param3=666”, "param4!=4"
分别要求带 param1,不带 param2 和 param3 值必须等于666,param4不等于4
@RequestMapping(params={“param1”, “!param2”,“param3=666”,“param4!=4”})
headers 请求中必须包含某些指定的header值,才响应。headers 比 consumes 作用范围大 @RequestMapping(headers=
“Referer=https://blog.csdn.net/jx520”)

Ant风格和带{xxx}占位符的URL

@RequestMapping不仅支持标准的URL,还支持Ant风格和带{xxx}占位符的URL

  • 最长匹配原则:越长的越优先匹配,其实就是详细的优先。

映射使用以下规则匹配url:

通配符 说明
? 匹配任意字符
* 匹配任意字符
** 匹配路径中的目录
{spring:[a-z]+} 匹配正则 [a-z]+ 并将结果付给变量spring
  • 例子
URL 匹配
com/t?st.jsp 匹配 com/test.jsp, com/tast.jsp, com/txst.jsp
com/*.jsp 匹配 com 目录下的所有 .jsp 文件
com/**/test.jsp 匹配 com 任意子目录下的 test.jsp
org/springframework/**/*.jsp 匹配 org/springframework/ 任意子目录下的所有 .jsp 文件
org/**/servlet/bla.jsp 匹配 org/springframework/servlet/bla.jsp
and org/springframework/testing/servlet/bla.jsp
and org/servlet/bla.jsp
com/{filename:\w+}.jsp 匹配 com/test.jsp 并且将 test 赋给 filename

@RequestParam 参数绑定

就是定义请求参数方法形参的映射规则。

public String demo3(@RequestParam(value="请求参数名",defaultValue="默认值") String "方法形参") 
属性 说明
value 绑定请求参数名。请求参数名与形参名不一致时做映射
defaultValue 默认值
required 是否必填。true丨false 默认true。必填简写:String demo(@RequestParam String name)

请求参数绑定

1 无参数

http://localhost/demo

	@RequestMapping(value = "/demo")
	public String demo(Map<String,Object> dateMap) {
		System.out.println("无参数请求");
		dateMap.put("name", "demo");
		dateMap.put("age", "0");
		return "index";
	}

2 请求的参数名与形参名对应

  • 特点:DispactherServlet 在调用单元方法时会根据单元方法的形参名去获取此次请求的 Request 对象中的请求数据,并将获取的数据作为实参传递给控制器方法。
  • 优点:DispactherServlet 会根据形参的类型将请求数据强制转换。

http://localhost/demo2?name=笨笨笨&age=108

	@RequestMapping("/demo2")
	public String demo2(String name, int age, Map<String,Object> dateMap) {
		System.out.println("前端请求参数名与形参名对应:"+name+"-"+age);
		dateMap.put("name", name);
		dateMap.put("age", age);
		return "index";
	}

3 请求参数名与控制器方法的形参名不一致

	@RequestMapping("/demo3")
	public String demo3(@RequestParam(value="nameAlias",defaultValue="笨笨")String name,
			@RequestParam(value="ageAlias",required=true)int age,
			Map<String,Object> dateMap) {
		
		System.out.println("请求参数名与控制器方法的形参名不一致 @RequestParam 来也 :"+name+"-"+age);
		dateMap.put("name", name);
		dateMap.put("age", age);
		return "index";
	}

4 自定义对象类型

  • 自定义对象属性名与前端 name 相同的就会被赋值
  • 如果自定义对象 User有引用属性UserInfo,则前端 name的形式为 userInfo.nickName
<form action="demo4" method="post">
	<input name="userId" value="100" /><br>
	<input name="userName" value="jx520" /><br>
	<input name="userInfo.nickName" value="笨笨" /><br>
	<input name="nickName" value="笨笨" /><br>
	<input type="submit" value="Save" />
</form>
@RequestMapping("demo4")
public String test(User user, String nickName) {
	System.out.println(user.getUserId());
	System.out.println(user.getUserName());
	// 下面两个nickName 效果一样
    System.out.println(user.getUserInfo.getNickName());
    System.out.println(nickName);
    return "index.jsp"
}

5 数组、列表参数

常用于多选。

  • 数组:在控制器方法声明String数组类型的形参,形参名为请求参数名。

http://localhost/demo5a?name=笨笨&age=888&hobbyId=x&hobbyId=y&hobbyId=z

	@RequestMapping("/demo5a")
	public String demo3(String name,int age,String[] hobbyId, Map<String,Object> dateMap) {
		System.out.println("请求发来数组参数 :"+name+"-"+age + Arrays.toString(hobbyId));
		dateMap.put("name", name);
		dateMap.put("age", age);
		dateMap.put("hobbyId", Arrays.toString(hobbyId));
		
		return "index";
	}
  • 列表:在控制器方法中声明ArrayList<String>集合,并使用@RequestParam("请求参数名")映射。

http://localhost/demo5b?name=笨笨&age=998&hobby=u&hobby=v&hobby=w

	@RequestMapping("/demo5b")
	public String demo3(String name,int age,@RequestParam("hobby")ArrayList<String> hobby, Map<String,Object> dateMap) {
		System.out.println("请求发来列表参数 :"+name+"-"+age + hobby.toString());
		dateMap.put("name", name);
		dateMap.put("age", age);
		dateMap.put("hobby", hobby.toString());
		return "index";
	}

6 URL占位符参数

  • 传统方式请求地址及数据用?分割
  • Restful格式的请求,数据就是地址的一部分 http://localhost:80/project/demo6/笨笨/18

@PathVariable

http://localhost/demo6/笨笨/9527

	@RequestMapping("/demo6/{name}/{age}")
	public String demo6(@PathVariable String name, @PathVariable int age, Map<String,Object> dateMap) {
		System.out.println("URL占位符参数 :"+name+"-"+age);
		dateMap.put("name", name);
		dateMap.put("age", age);
		return "index";
	}

http://localhost/demo6b/笨/3306

	@RequestMapping("/demo6b/{aa}/{bb}")
	public String demo6b(@PathVariable("aa")String name, @PathVariable("bb")int age, Map<String,Object> dateMap) {
		System.out.println("URL占位符参数 :"+name+"-"+age);
		dateMap.put("name", name);
		dateMap.put("age", age);
		return "index";
	}

@RequestBody 用前端传来的数据注入对象

	@RequestMapping("/login.do")
    @ResponseBody
    public Object login(@RequestBody User loginUuser, HttpSession session) {
        user = userService.checkLogin(loginUser);
        session.setAttribute("user", user);
        return new JsonResult(user);
    }

参考资料

超详细 Spring @RequestMapping 注解使用技巧

猜你喜欢

转载自blog.csdn.net/jx520/article/details/87490795
今日推荐