1•SpringMVC默认支持的绑定类型有:
2•HttpServletRequest对象:通过request对象可以获取参数信息
3•HttpServletResponse对象:通过response对象可以处理响应信息
4•HttpSession对象:获取session中存储的对象
5•Model/ModelMap:Model是一个接口,ModelMap是一个接口的实现。作用是将模型数据填充到request域。
直接在controller中定义一个变量,但是此种传输方式有一个限制就是参数名和请求中的参数名必须保持一致,否则是接收不到数据的。
Controller : public void controllerTest(Integer id){}
request : http://localhost:8080/springMvcTest/controllerTest?id=2;
•使用@RequestParam进行参数绑定,在使用这个注解进行绑定的时候,参数名无需和请求中的参数名保持一致。
Controller : public void controllerTest(@RequestParam(value="id") Integer goods_id){}
@RequestParam(value="id") Integer goods_id 表示将请求中的id属性绑定到goods_id这个参数上
•传递对象参数
•要求页面中input标签的name属性值和controller的pojo形参中的属性名称一致,即可将页面中数据绑定到pojo
Controller : public void controllerTest(User user){}
实体类:
public class User{
private String name;
private String realName;
private String pwd;
}
jsp页面:
<form action="" method="post">
<input name="name" type="text"/>
<input name="realName" type="text"/>
......
</form>
/**
* 测试参数为HttpSession
* @param session
* @return
*/
@RequestMapping("/testSession")
public String testSession(HttpSession session){
session.setAttribute("message", "zhanghw--haha");
return "hello";
}
/**
* 测试参数为Model
* @param model
* @return
*/
@RequestMapping("/testString2")
public String testString2(Model model){
//传递数据到hello.jsp上
model.addAttribute("message", "Test String2");
//request.setAttribute("message", "Test String");
return "hello";//指定逻辑视图名,通过视图解析器解析为jsp物理路径
}
/**
* 测试简单参数
* @param id
* @return
*/
@RequestMapping("/testParameter")
public String testParameter(Integer id){
System.out.println(id);
return "hello";
}
/**
* 测试注解简单参数
* @param gid
* @return
*/
@RequestMapping("/testRequestParam")
public String testRequestParam(@RequestParam(value="id")Integer gid){
System.out.println(gid);
return "hello";
}
/**
* 测试对象参数
* @param user
* @return
*/
@RequestMapping("/testObjectParam")
public String testObjectParam(User user){
System.out.println(user.getName());
System.out.println(user.getRealName());
System.out.println(user.getPwd());
return "hello";
}
模拟用户注册,测试对象参数
<form action="${pageContext.request.contextPath}/testObjectParam.action" method="post">
用户名:<input type="text" name="name">
真实姓名:<input type="text" name="realName">
密码:<input type="password" name="pwd">
<input type="submit" value="注册">
</form><br>