码迷,mamicode.com
首页 > 其他好文 > 详细

自动封装Servlet HttpServletRequest请求成为一个POJO对象

时间:2014-08-07 02:58:58      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   java   os   io   for   

  自己写了个小工具类,将Servlet里面的HttpServletRequest请求封装成为一个POJO对象,可以复习一下Java的反射原理,开发中这个没什么用,毕竟都用MVC框架,框架都自带这种功能,而且更为强大,不过框架也应该是采用这种原理,通过这个也能对框架窥测一二。

  这是工具类:通过传入POJO的Class对象来自动封装一个POJO。

package com.xxx.xxx.util;

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

import javax.servlet.http.HttpServletRequest;

public class PackObject<T> {
    Class<T> c;

    public static <T> T getObject(HttpServletRequest request, Class<T> c) {

        T t = null;
        try {
            t = c.newInstance(); // 实例化参数对象
        } catch (InstantiationException e1) {
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            e1.printStackTrace();
        }

        @SuppressWarnings("rawtypes")
        Enumeration e = request.getParameterNames(); // 所有请求参数

        Method[] methods = c.getDeclaredMethods(); // 参数对象的所有方法

        // 根据对象的set方法的参数类型去将请求的值做相应转换
        while (e.hasMoreElements()) {
            String paramName = e.nextElement().toString();
            String setParamName = reverseParamName(paramName); //将参数名字转换成set方法名字,如:id 转换成 setId
            
            for (Method method : methods) {
                if (setParamName.equals(method.getName())) {
                    try {
                        Class<?> paramType = (method.getParameterTypes())[0]; //得到set方法参数类型
                        String value = request.getParameter(paramName); 
                        adapter(t, method, paramType, value); //通过适配器将值注入进POJO里面
                    } catch (IllegalArgumentException e1) {
                        e1.printStackTrace();
                    } catch (IllegalAccessException e1) {
                        e1.printStackTrace();
                    } catch (InvocationTargetException e1) {
                        e1.printStackTrace();
                    } catch (SecurityException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
        return t;
    }

    private static String reverseParamName(String paramName) {
        char firstChar = paramName.charAt(0);
        char toUpper = Character.toUpperCase(firstChar);
        String setParamName = "set" + String.valueOf(toUpper)
                + paramName.substring(1);
        return setParamName;
    }

    private static <T> void adapter(T t, Method method, Class<?> paramType,
            String value) throws IllegalAccessException,
            InvocationTargetException {
        if (paramType == String.class) {
            method.invoke(t, value);
        } else if (paramType == Integer.class || paramType == int.class) {
            method.invoke(t, Integer.parseInt(value));
        } else if (paramType == Long.class || paramType == long.class) {
            method.invoke(t, Long.parseLong(value));
        } else if (paramType == Boolean.class || paramType == boolean.class) {
            method.invoke(t, Boolean.parseBoolean(value));
        } else if (paramType == Short.class || paramType == short.class) {
            method.invoke(t, Short.parseShort(value));
        } else if (paramType == Float.class || paramType == float.class) {
            method.invoke(t, Float.parseFloat(value));
        } else if (paramType == Double.class || paramType == double.class) {
            method.invoke(t, Double.parseDouble(value));
        } else if (paramType == Character.class || paramType == char.class) {
            char[] cs = value.toCharArray();
            if (cs.length > 1) {
                throw new IllegalArgumentException("参数长度太大");
            }
            method.invoke(t, value.toCharArray()[0]);
        }
    }
}

  POJO类:

package com.xxx.xxx.util;

public class User {
    private int id;
    private String name;
    private String password;

    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 int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", password=" + password
                + "]";
    }

}

  Servlet:

package com.xxx.xxx.util;

import java.io.IOException;

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

@SuppressWarnings("serial")
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        User user = PackObject.getObject(request, User.class);
        System.out.println(user);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

  页面:分别输入id:123,name:Jay,password:Jolin

    <form action="UserServlet">
        id:<input name="id" /><br />
        name:<input name="name" /><br />
        password:<input name="password" type="password" /><br />
        <input type="submit" value="submit" />
    </form>

  结果:User [id=123, name=Jay, password=Jolin]

  只测了下int类型和String类型没有问题,没什么问题。

自动封装Servlet HttpServletRequest请求成为一个POJO对象,布布扣,bubuko.com

自动封装Servlet HttpServletRequest请求成为一个POJO对象

标签:style   blog   http   color   java   os   io   for   

原文地址:http://www.cnblogs.com/dreamroute/p/3896134.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!