超实用的公共方法——form表单的数据自动注入JavaBean

长时间的工作中我发现,把页面中输入框的数据放入一个VO(JavaBean)中,一般都是调用如:

bean.setName(request.getParameter("name"));

此类的代码一大堆,实在是累啊,后来一想还是字个公共方法吧,一劳永逸,无论是什么样的JavaBean,只要调一下这个公共方法就可以把对应的值自动set 到JavaBean中,代码如下:

我们先写个页面:

 

<% @ page language = " java "  contentType = " text/html; charset=GBK "
    pageEncoding
= " GBK " %>
<! DOCTYPE html PUBLIC  " -//W3C//DTD HTML 4.01 Transitional//EN "   " http://www.w3.org/TR/html4/loose.dtd " >
< html >
< head >
< title > Insert title here </ title >
</ head >
< body >
< form action = " /MyTaglib/MethodTest " >
flo:
< input name = " flo " >< br >
bool:
< input name = " bool " >< br >
dou:
< input name = " dou " >< br >
String:
< input name = " str " >< br >
count:
< input name = " count " >< br >
< input type = " submit " />
</ form >
</ body >
</ html >

上面的JSP代码中有几个输入框,他们对应着JavaBean中的成员变量,如下:

 

package  bean;

public   class  MyJavaBean  {
    
private int count;
    
private String str;
    
private double dou;
    
private float flo;
    
private boolean bool;
    
public int getCount() {
        
return count;
    }

    
public void setCount(int count) {
        
this.count = count;
    }

    
public String getStr() {
        
return str;
    }

    
public void setStr(String str) {
        
this.str = str;
    }

    
public double getDou() {
        
return dou;
    }

    
public void setDou(double dou) {
        
this.dou = dou;
    }

    
public float getFlo() {
        
return flo;
    }

    
public void setFlo(float flo) {
        
this.flo = flo;
    }

    
public boolean isBool() {
        
return bool;
    }

    
public void setBool(boolean bool) {
        
this.bool = bool;
    }

    
public String toString(){
        
return "int :"+count+" " +
                    
"float :"+flo+" " +
                        
"double :"+dou+" " +
                                
"String :"+str+" " +
                                        
"boolean :"+bool;
    }


}

这个类中我重写了toString()主法,用于测试数据。下面是一个Servlet用于接收页面传过来的数据,然后调用我们的公共方法:

 

package  servlet;

import  java.io.IOException;

import  javax.servlet.ServletException;
import  javax.servlet.http.HttpServlet;
import  javax.servlet.http.HttpServletRequest;
import  javax.servlet.http.HttpServletResponse;

import  util.PubFunc;
import  bean.MyJavaBean;

public   class  MethodTest  extends  HttpServlet  {

    
/**
     * Destruction of the servlet. <br>
     
*/

    
public void destroy() {
        
super.destroy(); // Just puts "destroy" string in log
        
// Put your code here
    }


    
/**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * 
@param request the request send by the client to the server
     * 
@param response the response send by the server to the client
     * 
@throws ServletException if an error occurred
     * 
@throws IOException if an error occurred
     
*/

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

        doPost(request,response);
        
    }


    
/**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * 
@param request the request send by the client to the server
     * 
@param response the response send by the server to the client
     * 
@throws ServletException if an error occurred
     * 
@throws IOException if an error occurred
     
*/

    
public void doPost(HttpServletRequest request, HttpServletResponse response)
            
throws ServletException, IOException {
        PubFunc p
=new PubFunc();
        MyJavaBean bean
=(MyJavaBean) p.setProperties(MyJavaBean.class,request);
        System.out.println(bean);
        
    }


    
/**
     * Initialization of the servlet. <br>
     *
     * 
@throws ServletException if an error occurs
     
*/

    
public void init() throws ServletException {
        
// Put your code here
    }


}

接下来就是我们的公共方法了,就是上面调用的setProperties(Class,HttpServletRequest)方法,代码如下:

 

package  util;

import  java.lang.reflect.Method;
import  java.util.Enumeration;

import  javax.servlet.http.HttpServletRequest;

public   class  PubFunc  {
    
public Object setProperties(Class c,HttpServletRequest request){
        
//得到所有的请求参数
        Enumeration<String> enums=request.getParameterNames();
        Object o
=null;
        
try {
            o 
= c.newInstance();
        }
 catch (InstantiationException e1) {
            
// TODO Auto-generated catch block
            e1.printStackTrace();
        }
 catch (IllegalAccessException e1) {
            
// TODO Auto-generated catch block
            e1.printStackTrace();
        }

        
//从JavaBean中得到所有的方法
        Method[] methods=c.getDeclaredMethods();
        String tem1
="";
        
while(enums.hasMoreElements()){
            tem1
=(String)enums.nextElement();
            
if(tem1!=null&&!"".equals(tem1)){
                String methodName
="set"+tem1.substring(0,1).toUpperCase();
                
if(tem1.length()>1){
                    methodName
+=tem1.substring(1);
                }

                
for(int i=0;i<methods.length;i++){
                    
if(methodName.equals(methods[i].getName())){
                        Method method
=methods[i];
                        
if(method.getParameterTypes()[0]==String.class){
                            String param
=null2String(request.getParameter(tem1));
                            
try {
                                method.invoke(o, 
new Object[]{param});
                            }
 catch (Exception e) {
                                
// TODO Auto-generated catch block
                                System.out.println("注入值时出错");
                            }

                            
                        }
else if(method.getParameterTypes()[0]==int.class){
                            String param
=null2Zero(request.getParameter(tem1));
                            Integer intParam
=null;
                            
try {
                                intParam 
= Integer.valueOf(param);
                            }
 catch (NumberFormatException e1) {
                                intParam
=new Integer(0);
                            }

                            
try {
                                method.invoke(o, 
new Object[]{intParam});
                            }
 catch (Exception e) {
                                
// TODO Auto-generated catch block
                                System.out.println("注入值时出错");
                            }

                            
                        }
else if(method.getParameterTypes()[0]==float.class){
                            String param
=null2Zero(request.getParameter(tem1));
                            Float floatParam
=null;
                            
try {
                                floatParam 
= Float.valueOf(param);
                            }
 catch (NumberFormatException e1) {
                                floatParam
=new Float(0.0F);
                            }

                            
try {
                                method.invoke(o, 
new Object[]{floatParam});
                            }
 catch (Exception e) {
                                
// TODO Auto-generated catch block
                                System.out.println("注入值时出错");
                            }

                            
                        }
else if(method.getParameterTypes()[0]==double.class){
                            String param
=null2Zero(request.getParameter(tem1));
                            Double doubleParam
=null;
                            
try {
                                doubleParam 
= Double.valueOf(param);
                            }
 catch (NumberFormatException e1) {
                                doubleParam
=new Double(0);
                            }

                            
try {
                                method.invoke(o, 
new Object[]{doubleParam});
                            }
 catch (Exception e) {
                                
// TODO Auto-generated catch block
                                System.out.println("注入值时出错");
                            }

                            
                        }
else if(method.getParameterTypes()[0]==boolean.class){
                            String param
=null2String(request.getParameter(tem1));
                            
if(!"true".equals(param)){
                                param
="false";
                            }

                            Boolean booleanParam
=Boolean.valueOf(param);
                            
try {
                                method.invoke(o, 
new Object[]{booleanParam});
                            }
 catch (Exception e) {
                                
// TODO Auto-generated catch block
                                System.out.println("注入值时出错");
                            }

                            
                        }

                        
break;
                    }

                    
                }

            }

            
            
        }

        
return o;
    }

    
private String null2Zero(String str){
        
if(str==null||"".equals(str.trim())){
            
return "0";
        }

        
return str.trim();
    }

    
private String null2String(String str){
        
if(str==null){
            
return "";
        }

        
return str.trim();
    }


}

这个方法支持五种类型:int ,float,double,boolean,String,其实自己可以定义更多的类型,不过一般的都够用了,而且时间有限。
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值