一、 实体參数
前面我们知道使用注解@RequestParam能够获得參数的值,那么如今提交一个表单怎么获得当中的值了。你能够说能够使用request.getParameter("")获得,是的这样的方法确实能获得。那么如今假设表单有100个參数了。我们不会一个一个的去获得然后在set到model中,那样显得非常麻烦。事实上springmvc能直接把值一一相应到model中。以下来看下样例:
package com.ztz.springmvc.model; public class Users { private String name; private String password; private Roles roles; //省略get set方法 //重写toString()方便測试 @Override public String toString() { return "Users [name=" + name + ", password=" + password + ", roles=" + roles + "]"; } }
package com.ztz.springmvc.model; public class Roles { private int id; private String name; //省略get set方法 //重写toString()方便測试 @Override public String toString() { return "Roles [id=" + id + ", name=" + name + "]"; } }
package com.ztz.springmvc.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.ztz.springmvc.model.Users; @Controller @RequestMapping("/user") public class UsersController { @RequestMapping(value="/getparams",method=RequestMethod.POST) private String findAll(Users users){ System.out.println(users); return "users"; } }
<form action="${basePath}user/getparams" method="post"> <label>username:</label><input type="text" name="name"/><br/> <label>密 码:</label><input type="password" name="password"/><br/> <label>编 号:</label><input type="text" name="roles.id"/><br/> <label>角色名:</label><input type="text" name="roles.name"/><br/> <input type="submit" value="提 交"/> </form>页面输入值,点击提交,控制台输出结果:
Users [name=test, password=password, roles=Roles [id=11, name=admin]]
二、 ServletAPI
以下来看springmvc里面怎么用ServletAPI,事实上非常好用的,看下样例:
@Controller @RequestMapping("/user") public class UsersController { @RequestMapping(value="/getparams",method=RequestMethod.POST) private String findAll(Users users,HttpServletRequest request, HttpSession session,HttpServletResponse response){ //放到request作用域 request.setAttribute("users", users); //放到session session.setAttribute("session", "session"); //输出cookie response.addCookie(new Cookie("res", "response123")); return "users"; } }表单的JSP还是前面的那个不变。来看下提交成功,转发到新的JSP页面:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>用户信息</title> </head> <body> <h3>${users}</h3> <h3>${session}</h3> </body> </html>点击提交,看下结果: