默认支持的类型
HttpServletRequest
HttpServletResponse
HttpSession
基本类型
@Controller
@RequestMapping
public class ShowtimeController {
@RequestMapping("/baseType")
@ResponseBody
public String baseType(int age) {
return "age:"+age;
}
}
访问结果如图:
在代码中设置的参数为int类型,此时若在访问时不加参数如:http://localhost:8080/baseType,则访问出错,结果如图:
因此,当某个参数必输时,可以对代码作如下修改,加上@RequestParam(“age”):
@RequestMapping("/baseType")
@ResponseBody
public String baseType(@RequestParam("age")int age) {
return "age:"+age;
}
@RequestParam(“age”)是告诉访问者,age是必输字段,此时如果在访问时没有该值则结果如图:
defaultValue的用法:默认值,如果请求中没有同名参数,则使用该默认值
@RequestMapping("/baseType")
@ResponseBody
public String baseType(@RequestParam(defaultValue="1")Integer age) {
return "age:"+age;
}
访问结果如图:
包装类
@Controller
@RequestMapping
public class ShowtimeController {
@RequestMapping("/baseType")
@ResponseBody
public String baseType(Integer age) {
return "age:"+age;
}
}
这里参数age的数据类型为Integer,这时在访问时,如果不加参数,不会报错,其结果如图:
数组
@RequestMapping("/array")
@ResponseBody
public String array(Integer[] age) {
StringBuffer out = new StringBuffer();
for (Integer item : age) {
out.append(item).append("--");
}
return out.toString();
}
访问结果如图:
简单pojo的参数绑定
@RequestMapping("/pojo")
@ResponseBody
public Showtime pojo(Showtime showtime) {
System.out.println(">>>>"+showtime.getUsername());
return showtime;
}
访问结果如图:
包装类型pojo绑定
如以下代码所示,在实体类Showtime中有实体类pojo
public class Showtime {
private Pojo pojo;
private String username;
private String address;
}
public class Pojo {
private String tel;
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
}
访问结果如下:
参考资料:本博文内容参考慕课网Geely老师的SpringMVC数据绑定入门,链接为:http://www.imooc.com/learn/558