方式1:
接受传递普通的数据:
jsp页面传值
<form method="post" action="${pageContext.request.contextPath}/user/hello1.action"> <input type="text" name="username"> <br/> <input type="submit" value="提交"/> </form>
控制器接受传递过来的参数
@Controller @RequestMapping(value = "/user", method = RequestMethod.POST) //可以限制访问的方式 只有post的请求才能进入 public class HelloAction {
@RequestMapping("/hello1.action") //springmvc是通过方法的参数方式传递参数的,所以它可以实现单例的 public String hello(Model model, HttpServletRequest request, HttpServletResponse response,String username) throws Exception{ System.out.println("传递过来的username:"+username); model.addAttribute("messsage","注解实现springmvc"); return "hello"; } }
方式2:
Bean封装传递过来的参数 编写一个Bean,Bean中的字段与 参数字段一一对应即可 springmvc会自动封装。
注意日期类型的封装 需要通过@InitBinder的注解方式来处理
jsp
<form method="post" action="${pageContext.request.contextPath}/user/hello1.action"> <input type="text" name="username"> <br/> <input type="submit" value="提交"/> </form>
实体bean
package com.cn.controllers; public class User { private String username; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public String toString() { return "User{" + "username=‘" + username + ‘\‘‘ + ‘}‘; } }
控制器
@Controller @RequestMapping(value = "/user", method = RequestMethod.POST) //可以限制访问的方式 只有post的请求才能进入 public class HelloAction {
//时期类型转换器
@InitBinder protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { //参数类型:将String转成什么类型的字节; binder.registerCustomEditor( Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true)); }
@RequestMapping("/hello1.action") //springmvc是通过方法的参数方式传递参数的,所以它可以实现单例的 public String hello(Model model, User user) throws Exception{ System.out.println(user.getUsername()); return "hello"; } }
SpringMvc 封装传递参数的方式 和限制访问的方式Post?Get?..
原文:https://www.cnblogs.com/gaoSJ/p/13031207.html