前台传给后台的参数有时是不固定的,有些参数可能有,有些可能没有,比如获取定位的gps,有的用户有开gps,就有gps参数,有些没有,就没有gps参数,因此,我想让这些参数成为可选的,如果没有传入,则可能填充一个默认值。
在springMVC中,有相应的方法处理参数,根据版本的划分,大致可分为3类:
spring4.1+和jdk1.8以上的运行环境使用Optional,将参数可选化
spring3.0+的运行环境使用defaultValue设定默认值
spring2.5+的运行环境用if判断是否需要给参数注入默认值
我们以springMVC(版本:4.3.10)自带的hello world例子说明,如下,controller接收前台(index.html)传来的name参数,打印到greeting.html界面上
- index.html
<!DOCTYPE HTML>
<html>
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>Get your greeting <a href="/greeting_fourpointone">spring4.1以上--没有参数</a></p>
<p>Get your greeting <a href="/greeting_fourpointone?name=wen">spring4.1以上--带参数</a></p>
<p>Get your greeting <a href="/greeting_threepointzero">spring3.0以上--没有参数</a></p>
<p>Get your greeting <a href="/greeting_threepointzero?name=wen">spring3.0以上--带参数</a></p>
<p>Get your greeting <a href="/greeting_twopointfive">spring2.5以上--没有参数</a></p>
<p>Get your greeting <a href="/greeting_twopointfive?name=wen">spring2.5以上--带参数</a></p>
</body>
</html>
- GreetingController .java
package wen.hello;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class GreetingController {
//spring4.1+和jdk1.8以上的运行环境
@RequestMapping("/greeting_fourpointone")
public String greeting_spring_version_fourpointone(@RequestParam("name") Optional<String> name, Model model) {
model.addAttribute("name", name);
return "greeting";
}
//spring3.0+的运行环境
@RequestMapping("/greeting_threepointzero")
public String greeting_spring_version_threepointzero(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
return "greeting";
}
//spring2.5+的运行环境
@RequestMapping("/greeting_twopointfive")
public String greeting_spring_version_twopointfive(@RequestParam(value = "name", required = false) String name, Model model) {
if (name == null) {
name = "world";
}
model.addAttribute("name", name);
return "greeting";
}
}
- greeting.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>
- 运行
- 在浏览器输入:http://localhost:8080/ 测试