利用commons-beanutil自写一个java工具类:
public class MapToBeanUtil { /* * 传入一个map和一个类型,通过类型创建变量,把map中的数据封装到javabean对象中,然后返回对象 */ public static <T> T toBean(Map map,Class<T>clazz ) { try { T bean = clazz.newInstance(); BeanUtils.populate(bean, map); return bean; } catch (Exception e) { throw new RuntimeException(e); } } }
再准备一个javabean:
public class User { private String name; private String password; private String sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public String toString() { return "Student [name=" + name + ", password=" + password + ", sex=" + sex + "]"; } }
jsp:
<body> <form action="<%=request.getContextPath() %>/RegistServlet" method="post"> 名称:<input type="text" name="name" /><br/> 密码:<input type="text" name="password" /><br/> 性别:<input type="text" name="sex" /><br/> <input type="submit" value="提交"/> </form> </body>
servlet:
public class RegistServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //输出bean的返回对象 System.out.println(MapToBeanUtil.toBean(request.getParameterMap(), User.class)); } }
时间: 2024-10-07 18:21:27