package com.test.classobject;
import java.io.IOException;
import java.lang.reflect.Field;
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.test.pojo.Student;
/**
* Servlet implementation class AddStudentServlet
*/
@WebServlet("/AddStudentServlet")
public class AddStudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AddStudentServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
Class clazz=Student.class;
Field[] arr= clazz.getDeclaredFields();
Student student=new Student();
//遍历student对象中的所有的字段
for(Field field:arr)
{
String name= field.getName();//获得当前字段的名称 依次获得sid sname age
String value=request.getParameter(name);//根据字段名称获取表单中对应元素的值
//response.getWriter().println(field.getGenericType().toString());
try {
field.setAccessible(true);//设置当前字段可以访问
//将值存入student对象中对应的字段
if(field.getGenericType().toString().equals("int"))
field.set(student, Integer.parseInt(value));
else if(field.getGenericType().toString().equals("class java.lang.String"))
field.set(student, value);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
response.getWriter().println(student.getSid()+","+student.getSname()+","+student.getAge());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
<%@ 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="AddStudentServlet" method="post">
<Pre>
学号:<input type='text' name='sid' />
学生名称:<input type='text' name='sname' />
年龄:<input type='text' name='age' />
<input type='submit' name='sub' value='添加' />
</Pre>
</form>
</body>
</html>
文章来源地址https://www.toymoban.com/news/detail-593814.html
文章来源:https://www.toymoban.com/news/detail-593814.html
到了这里,关于javaee 反射应用之一,获得对象的字段信息的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!