Java中基於HttpServlet的反射機制(封裝從view層頁面接收到的數據於實體對象中)

一、實體類

package com.qf.pojo;

public class UserInfo{
	private int id;
	private String name;
	private int age;
	private String pwd;
	
	public UserInfo() {
		super();
	}

	public UserInfo(int id, String name, int age, String pwd) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.pwd = pwd;
	}

	public int getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + id;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + ((pwd == null) ? 0 : pwd.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		UserInfo other = (UserInfo) obj;
		if (age != other.age)
			return false;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (pwd == null) {
			if (other.pwd != null)
				return false;
		} else if (!pwd.equals(other.pwd))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "UserInfo [id=" + id + ", name=" + name + ", age=" + age + ", pwd=" + pwd + "]";
	}
	
	
}
二、view層的頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="hellos" method="post">
	<pre>
		用戶序列:<input type="text" name="id"/>
		用戶姓名;<input type="text" name="name"/>
		用戶年齡:<input type="text" name="age"/>
		用戶密碼:<input type="text" name="pwd"/>
		<input type="submit" value="提交"/>
	</pre>
	</form>
</body>
</html>
三、基於HttpServlet的Java反射機制

package com.qf.util;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ReflectSetObject extends HttpServlet {
	
	protected static Object setObject(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		Object object = null;
		
		try {
			//通過反射獲取某個類的Class對象
			Class<?> class1 = Class.forName("com.qf.pojo.UserInfo");
			//通過無參構造new一個實體對象
			object =class1.newInstance();	

			String field = null;
			//獲得此類的所有聲明的字段,即包括public、private和protected,但是不包括父類的申明字段
			Field[] fields = class1.getDeclaredFields();
			
			//遍歷該類所有已申明的字段
			for (Field fiename : fields) {
				//獲取字段類型的Class對象
				Class<?> cType = fiename.getType();
				
				//獲取字段類型的名稱
				String fieldType = cType.getSimpleName();
				
				//獲取字段名稱
				field = fiename.getName();
				//截取第一個字母
				String first = field.substring(0, 1);
				//轉換成大寫
				String upper2First = first.toUpperCase();
				//替代成首字母大寫的新字符串
				String replaceFirst = field.replaceFirst(first, upper2First);
				
				//從view層頁面獲取屬性對應的值(注:view頁面的書寫規範是<input>標籤中的name屬性要和pojo類的屬性相一致)
				String parameter = req.getParameter(field);
				
				//判斷所得屬性的類型及是否爲空
				if ("String".equals(fieldType) && parameter != null && parameter.length() > 0) {
					//調用set方法
					Method method1 = class1.getMethod("set" + replaceFirst, String.class);
					//將所得的屬性對應值set進對象
					method1.invoke(object, parameter);

				}
				if ("int".equals(fieldType) && parameter != null && parameter.length() > 0) {
					Method method1 = class1.getMethod("set" + replaceFirst, int.class);
					int name = Integer.parseInt(parameter);
					method1.invoke(object, name);
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return object;
	}
}

四、測試的HttpServlet

package com.qf.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;

import com.qf.pojo.UserInfo;
@WebServlet("/hellos")
public class TestReflect extends HttpServlet{
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	
		UserInfo info = (UserInfo) ReflectSetObject.setObject(req, resp);
		System.out.println(info);
	}
}

注:此方法僅用於servlet開發項目中,獲取頁面數據封裝於對應實體類的方法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章