Java中基于HttpServlet的反射机制(封装从view层页面接收到的数据于实体对象中)

1 篇文章 0 订阅
1 篇文章 0 订阅

一、实体类

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开发项目中,获取页面数据封装于对应实体类的方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值