自動封裝Servlet HttpServletRequest請求成為一個POJO對象


  自己寫了個小工具類,將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類型沒有問題,沒什么問題。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM