美文网首页
使用反射将request中的请求封装到对象中

使用反射将request中的请求封装到对象中

作者: zxcvbnmzsedr | 来源:发表于2018-06-28 22:09 被阅读0次

    由于某些特殊原因不能够使用SpringMvc的自动封装去封装对象,故写了工具类,手动从HttpServletRequest中把属性注入到对象中

    private void requestToObject(HttpServletRequest request, Object object,Class objective) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
            // 递归调用
            if(objective.getSuperclass() != Object.class){
                requestToObject(request,object,object.getClass().getSuperclass());
            }
            for (Field field : objective.getDeclaredFields()) {
                Enumeration enumeration = request.getParameterNames();
                while (enumeration.hasMoreElements()) {
                    String ele = enumeration.nextElement().toString();
                    String fileName = field.getName();
                    if (ele.equals(fileName)) {
                        Method method = null;
                        try {
                            method = objective.getDeclaredMethod("set" + fileName.substring(0, 1).toUpperCase() + fileName.substring(1, fileName.length()), String.class);
                        } catch (NoSuchMethodException e) {
                            try {
                                method = objective.getDeclaredMethod("set" + fileName.substring(0, 1).toUpperCase() + fileName.substring(1, fileName.length()), Integer.class);
                            } catch (NoSuchMethodException e1) {
                                throw e1;
                            }
                        }
                        method.setAccessible(true);
                        method.invoke(object, request.getParameter(field.getName()));
                    }
                }
            }
        }
    

    相关文章

      网友评论

          本文标题:使用反射将request中的请求封装到对象中

          本文链接:https://www.haomeiwen.com/subject/kuonyftx.html