1)前端post数据过来,key和val键值对会有很多,这个时候往后端进行插值的时候,最好将这些键值对转换成对象进行处理。
使用common-beanutils 来将前端传递过来的map直接转换成对象。
依赖jar包:
前端代码的name属性要和后端bean对象属性一致!
1 <h1>测试POST</h1> 2 <form action="/bean" method="post"> 3 <input type="text" name="username">用户名字 4 <input type="password" name="passowrd">用户密码 5 <button type="submit">提交</button> 6 </form> 7 </body> 8 </html>
后端代码:
1 package jd.com.bean_test; 2 3 import org.apache.commons.beanutils.BeanUtils; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.annotation.WebServlet; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 import java.io.IOException; 11 import java.util.Map; 12 13 @WebServlet(name = "Servlet_Bean") 14 public class Servlet_Bean extends HttpServlet { 15 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 16 //只能针对post请求 不乱码。 17 request.setCharacterEncoding("utf-8"); 18 Map<String,String[]> data=request.getParameterMap(); 19 User user_obj=new User(); 20 try { 21 BeanUtils.populate(user_obj,data); 22 }catch (Exception ex){ 23 ex.printStackTrace(); 24 throw new RuntimeException("转换出问题!"); 25 } 26 System.out.println(user_obj); 27 28 29 } 30 31 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 32 33 } 34 }
1 package jd.com.bean_test; 2 3 public class User { 4 private String username; 5 private String passowrd; 6 public User(){} 7 8 public void setUsername(String username) { 9 this.username = username; 10 } 11 12 public void setPassowrd(String passowrd) { 13 this.passowrd = passowrd; 14 } 15 16 public String getUsername() { 17 return username; 18 } 19 20 public String getPassowrd() { 21 return passowrd; 22 } 23 24 @Override 25 public String toString() { 26 return username+" "+passowrd; 27 } 28 }