BeanUtils資料封裝工具類的使用
阿新 • • 發佈:2018-12-22
Java程式碼:
package com.java.domain; public class Person { private String name; private int age; private String gender; private String hobby; private String province; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getHobby() { return hobby; } public void setHobby(String hobby) { this.hobby = hobby; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } }
package com.java.servlet; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.BeanUtils; import com.java.domain.Person; public class ReceiveServlet extends HttpServlet { private static final long serialVersionUID = 1L; public ReceiveServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); // 接收愛好陣列 String[] hobby = request.getParameterValues("hobby"); // 把陣列轉位字串 String hobby1 = Arrays.toString(hobby); // 接受前臺引數 Map<String, String[]> map = request.getParameterMap(); Person person = new Person(); try { BeanUtils.populate(person, map); person.setHobby(hobby1); System.out.println(person.getName()); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } }
HTML程式碼:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>表單</title> </head> <body> <form action="../ReceiveServlet" method="post"> <table border="1"> <tr> <th> 姓名: <input type="text" name="name" /> </th> </tr> <tr> <th> 年齡: <input type="text" name="age" /> </th> </tr> <tr> <th> 性別: <input type="radio" value="女" name="gender" />女 <input type="radio" value="男" name="gender" />男 </th> </tr> <tr> <th> 愛好: <input type="checkbox" name="hobby" value="摔跤" />摔跤 <input type="checkbox" name="hobby" value="手辦" />手辦 <input type="checkbox" name="hobby" value="騎車" />騎車 <input type="checkbox" name="hobby" value="玩偶" />玩偶 </th> </tr> <tr> <th> 省份: <select name="province"> <option value="廣東省">廣東省</option> <option value="四川省">四川省</option> <option value="湖北省">湖北省</option> </select> </th> </tr> <tr> <th> <input type="submit" value="提交" /> </th> </tr> </table> </form> </body> </html>
專案圖片:
需要引用的lib裡的2個jar包