1.传参问题
1.1 url中拼接传参
/**
* 需求:
* 测试一下不同参数展示不同的数据:
* 请求路径: http://localhost:8123/test/ajaxList 不带参数时,显示3条数据
* http://localhost:8123/test/ajaxList?type=2 带参数 type=2时 显示2条数据
* http://localhost:8123/test/ajaxList?type=1 带参数 type=1时 显示1条数据
* @param httpServletRequest
* @param type
* @return
*/
@RequestMapping("/ajaxList")
@ResponseBody
public List<ValueTest> test1(HttpServletRequest httpServletRequest,@RequestParam(required = false, defaultValue="0") Integer type){
try{
if (type == 1){
List<ValueTest> list = new ArrayList<>();
list.add(new ValueTest("2020年",451L,"系列1"));
return list;
}else if (type == 2){
List<ValueTest> list = new ArrayList<>();
list.add(new ValueTest("2013年",352L,"系列1"));
list.add(new ValueTest("2014年",303L,"系列1"));
return list;
}
List<ValueTest> list = new ArrayList<>();
list.add(new ValueTest("2021年",451L,"系列1"));
list.add(new ValueTest("2013年",352L,"系列1"));
list.add(new ValueTest("2014年",303L,"系列1"));
return list;
}catch(Exception e){
return null;
}
}
知识点: @RequestParam注解用于接收请求url中拼接的参数,其中属性值的含义是:
required = false 参数可以不传;
defaultValue="0" 不传参数时,设置默认值,默认值为0;
1.2 路径参数
- 路径参数类似请求参数,但没有key部分,只是一个值。例如下面的URL: http://localhost:9090/showUser/spring
- 其中的spring是表示用户的密码字符串。在Spring MVC中,spring被作为路径变量用来发送一个值到服务器。Sping 3以后Spring 3以后支持注解@PathVariable用来接收路径参数。
- 为了使用路径变量,首先需要在RequestMapping注解的值属性中添加一个变量,该变量必须放在花括号之间,例如:@RequestMapping(value= “/showUser/{pwd}”) 然后在方法签名中加上@PathVariable注解。
- 具体代码如下:
@RequestMapping(value= "/showUser/{pwd}")
public String testPathVariable(@PathVariable(name="pwd") String password, Map<String, Object> model){
model.put("pwd", password);
return "showUser";
}
运行结果:
- 可以在请求映射中使用多个路径变量。例如,下面定义了userId和orderId两个路径变量。@RequestMapping(value= “/showUser/{userId}/{orderId}”);