Servlet实现与jsp效果相同的bean

方法:首先在http://commons.apache.org/上下载三个工具包,beanutils、collection、logging;

代码如下:BeanUtilities 类

import java.util.Map;


import javax.servlet.http.HttpServletRequest;


import org.apache.commons.beanutils.BeanUtils;


public class BeanUtilities {
public static void populateBean(Object formBean,HttpServletRequest request){
populateBean(formBean,request.getParameterMap());
}
public static void populateBean(Object bean,Map propertyMap){
try{
BeanUtils.populate(bean,propertyMap);
}
catch(Exception e){

}
}
}

Servlet类:

public class Submit extends HttpServlet {



public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


this.doPost(request, response);

}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println("  <BODY>");
InsurancesInfo info = new InsurancesInfo();
BeanUtilities.populateBean(info, request);
out.println("<ul>\n"+"<li>EmployeeId:"+info.getEmployeeID());
out.println("  </BODY>");

out.println("</HTML>");
out.flush();
out.close();
}

}

Bean类:

public class InsurancesInfo {
private String name;
private String employeeID;
private int numChilden;
private boolean isMarried;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmployeeID() {
return employeeID;
}
public void setEmployeeID(String employeeID) {
this.employeeID = employeeID;
}
public int getNumChilden() {
return numChilden;
}
public void setNumChilden(int numChilden) {
this.numChilden = numChilden;
}
public boolean isMarried() {
return isMarried;
}
public void setMarried(boolean isMarried) {
this.isMarried = isMarried;
}

}

html文件:

<!DOCTYPE html>
<html>
  <head>
    <title>test2.html</title>

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->


  </head>
  
  <body>
    <form action="servlet/Submit" method="post">
    name:<input type="text" name="name"/>
    id:<input type="text" name="employeeID"/>
    numChilden:<input type="text" name="numChilden"/>
    <input type="checkbox" name="married" value="true"/> Married?</checkbox>
    <center><input type="submit"/></center>
   
    </form>
  </body>
</html>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值