基于反射自动将请求信息封装成JavaBean实例

大家有需要自取

工具类SimpleBeanConvertor

public class SimpleBeanConvertor {

    private static Logger logger = Logger.getLogger(SimpleBeanConvertor.class);

    public static <T> T convert(HttpServletRequest request, Class<T> targetType) throws InstantiationException, IllegalAccessException, InvocationTargetException, ParseException, UnsupportedTypeException {
        // 获取所有请求参数
        Map<String,String[]> params = request.getParameterMap();
        // 创建JavaBean实例,new User();
        T target = targetType.newInstance();
        // 获取JavaBean中所有方法
        Method[] allMethods = targetType.getMethods();
        if (allMethods != null && allMethods.length > 0){
            for (Method method : allMethods){
                if (method.getName().startsWith("set")){// 仅处理
                    Class[] args = method.getParameterTypes();// 获取参数列表
                    if (args.length == 1){
                        // 获取set方法对应的请求参数:setName -> name
                        String paramName = method.getName().substring(3,4).toLowerCase() + method.getName().substring(4);
                        if (params.containsKey(paramName)){
                            try {
                                Object value = parseValue(params.get(paramName),args[0]);
                                method.invoke(target,value);
                            } catch (ParseException e){
                                logger.debug("参数转换错误",e);
                                e.printStackTrace();
                                throw e;
                            }
                        }else if (Boolean.class == args[0] || boolean.class == args[0]){
                            // 如果是boolean,不存在表示false
                            method.invoke(target,false);
                        }
                    }
                }
            }
        }
        return target;
    }

    /**
     * 将数组类型的数据进行转换
     *
     * @param values
     * @param type
     * @param <T>
     * @return
     * @throws ParseException
     */
    private static <T> Object parseValue(String[] values, Class<T> type) throws ParseException {
        T[] targetArr = null; // String[] targetArr ["Java", "C#", "Spring"] ; int[] targetArr [1, 2, 5]
        // 判断是否为数组类型
        if (type.isArray()) {
            // 获取到数组内容的类型
            Class componentType = type.getComponentType();
            targetArr = (T[]) Array.newInstance(componentType, values.length);
            for (int i = 0; i < values.length; i++) {
                targetArr[i] = (T) parseValue(values[i], componentType);
            }
        } else {
            // 将单个参数转换处理
            return parseValue(values[0], type);
        }
        return targetArr;
    }

    /**
     * 将String类型的参数值转换为相关属性的类型
     *
     * @param value 要转换的数据
     * @param type 对应的类型
     * @return
     */
    private static Object parseValue(String value, Class type) throws ParseException {
        if (value == null) {
            return null;
        }
        if (String.class == type) {
            return value;
        }
        if (boolean.class == type || Boolean.class == type) {
            if ("".equals(value) || "false".equals(value) || "0".equals(value)) {
                return false;
            }
            return true;
        }
        if (Date.class == type) {
            return new SimpleDateFormat("yyyy-MM-dd").parse(value);
        }
        if (char.class == type || Character.class == type) {
            return value.charAt(0);
        }
        if (int.class == type || Integer.class == type) {
            return Integer.valueOf(value); // value = "1" --> 1
        }
        if (long.class == type || Long.class == type) {
            return Long.valueOf(value); // value = "1" --> 1L
        }
        if (float.class == type || Float.class == type) {
            return Float.valueOf(value); // value = "1" --> 1F
        }
        if (double.class == type || Double.class == type) {
            return Double.valueOf(value); // value = "1" --> 1D
        }
        if (byte.class == type || short.class == type) {
            try {
                // byte | Byte -> Byte
                type = Class.forName("java.lang." + type.getName().substring(0, 1).toUpperCase() + type.getName().substring(1));
                if (type.getName().startsWith("java.lang.") || type.getName().startsWith("java.math.")) {
                    try {
                        // long l = new Long("9"); // 9
                        // 获取参数类型的构造函数(带一个String参数)
                        return type.getConstructor(String.class).newInstance(value);
                    } catch (Exception e) {
                        throw new UnsupportedTypeException(e);
                    }
                }
            } catch (ClassNotFoundException | UnsupportedTypeException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

自定义异常UnsupportedTypeException

public class UnsupportedTypeException extends Exception{

    public UnsupportedTypeException(){
        super("不支持的类型转换");
    }
    public UnsupportedTypeException(Throwable e){
        super("不支持的类型转换",e);
    }
}

使用示例



import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;

@WebServlet("/test")
public class TestServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        this.doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        try{
            // SimpleBeanConvertor.convert将请求req对象中的请求参数,在调用User实体类中的相关set方法后,赋值给User实体类中相关属性
            User user = SimpleBeanConvertor.convert(req,User.class);
            System.out.println(user);
        } catch (UnsupportedTypeException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值