简介:访问Servlet跳转到jsp显示班级,点击不同班级调取数据库相应的学员信息,以表格形式显示。
服务器:Tomcat
JDBC使用之前的随笔的方法
访问班级显示的Servlet:
package cn.hrh.clazzList; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ShowClazz extends HttpServlet { private static final long serialVersionUID = 3989966239821421177L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); request = new SelectDB().selectClazz(request); //携带着班级集合信息请求转发到jsp request.getRequestDispatcher("classlist.jsp").forward(request, response); } } public HttpServletRequest selectClazz(HttpServletRequest request) { String SQL = "select * from t_clazz;"; Connection conn = DB_Conn.openDB(); PreparedStatement ps = null; ResultSet rs = null; List<Clazz> clazzList = new ArrayList<Clazz>(); Clazz clazz = null; try { ps = conn.prepareStatement(SQL); rs = ps.executeQuery(); while (rs.next()) { //利用反射每次查询到一条数据便构建一个实体 clazz = new Clazz(); //依次绑定查询到的结果集中包含班级编号,班级名,归属地 clazz.setId(rs.getInt(1)); clazz.setClazzName(rs.getString(2)); clazz.setClazzLocation(rs.getString(3)); //把每次得到的实体存储到集合中 clazzList.add(clazz); } //将集合绑定到request中 request.setAttribute("clazzList", clazzList); } catch (SQLException e) { e.printStackTrace(); } finally { DB_Conn.closeDB(conn, ps, rs); } return request; }
班级显示JSP:
<%@page import="cn.hrh.clazzList.Clazz"%> <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>班级列表</title> </head> <body> <ul> <!-- 提取request作用域中存储的班级集合,遍历 --> <c:forEach items="${requestScope.clazzList}" var="clazz"> <!-- 按照不同的班级给url中绑定对应的班级编号,用于后续查询数据库中对应班级学生,同时提取集合中的班级名显示在页面中 --> <li><a href="showstudent?clazzno=${clazz.id }">${clazz.clazzName }</a></li> </c:forEach> </ul> </body> </html>
效果:
点击对应的班级便会跳转到学生显示的Servlet
学生表格Servlet:
public class ShowStudent extends HttpServlet { private static final long serialVersionUID = 4296651983747427811L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); String clazzno = request.getParameter("clazzno"); request = new SelectDB().selectStudent(request, clazzno); //携带需要的数据请求转发 request.getRequestDispatcher("studentlist.jsp").forward(request, response); } } public HttpServletRequest selectStudent(HttpServletRequest request,String clazzno) { String SQL = "select distinct * from t_student where clazz_id = ?;"; Connection conn = DB_Conn.openDB(); PreparedStatement ps = null; ResultSet rs = null; List<Student> studentList = new ArrayList<Student>(); try { ps = conn.prepareStatement(SQL); ps.setInt(1, Integer.parseInt(clazzno)); rs = ps.executeQuery(); while (rs.next()) { //反射获得实体 Class<? extends Student> clazz = Student.class; //获得实例 Object clazzInstanc = clazz.newInstance(); ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 0; i < rsmd.getColumnCount(); i++) { //获得字段名 String colName = rsmd.getColumnName(i + 1); //获得结果集中的对应行数据 Object colValue = rs.getObject(i + 1); //反射获得对应字段名的属性对象 Field stuField = clazz.getDeclaredField(colName.toLowerCase()); //获得对应属性的set方法 Method stuMethod = clazz.getDeclaredMethod(creatSetter(colName), stuField.getType()); //传递对象和参数调用对应方法赋值 stuMethod.invoke(clazzInstanc, colValue); } //将每次获得的对象添加到集合 studentList.add((Student) clazzInstanc); } //对象集合绑定到request中 request.setAttribute("studentList", studentList); } catch (Exception e) { e.printStackTrace(); } return request; } public String creatSetter(String colName) { String setMethod = "set" + colName.substring(0, 1).toUpperCase() + colName.substring(1); return setMethod; }
学生表格JSP:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ page import="cn.hrh.clazzList.Student"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>学生列表</title> </head> <body> <table border=1> <tr> <td>ID</td><td>StudentName</td><td>StudentAge</td><td>StudentGender</td><td>StudentPhone</td><td>Clazz_ID</td> </tr> <!-- 遍历学生集合 --> <c:forEach items="${requestScope.studentList }" var="item"> <tr> <!-- 利用EL取得对应的值 --> <td>${item.id }</td><td>${item.studentname }</td><td>${item.studentage }</td><td>${item.studentgender }</td><td>${item.studentphone }</td><td>${item.clazz_id }</td> </tr> </c:forEach> </table> <button type="button" onclick="javascript:window.location.href=‘studentadd.jsp‘">学员添加</button> </body> </html>
效果图(假设查询java班):
添加学员Servlet:
public class StudentAdd extends HttpServlet { private static final long serialVersionUID = 1529395767721242677L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); int isSuccess = new InsertStudent().insertDB(new InsertStudent().insertStudent(request)); if (isSuccess == 1) { //若成功添加再请求转发 request.getRequestDispatcher("showclazz").forward(request, response); } else { PrintWriter out = response.getWriter(); out.write("<script>window.location.href=studentadd.jsp;window.confirm(‘添加失败‘);</script>"); } } } public class InsertStudent { public Object setField(Object obj,Field field) { String name = field.getName(); String methodName = "get" + name.substring(0,1).toUpperCase() + name.substring(1); Object setValue = null; try { Method method = obj.getClass().getMethod(methodName); setValue = method.invoke(obj); } catch (Exception e) { e.printStackTrace(); } return setValue; } public Object insertStudent(HttpServletRequest request){ //获取添加的学生的数据的Map Map<String, String[]> paraMap = request.getParameterMap(); //获得Key Set<String> paraKey = paraMap.keySet(); Class<Student> stuClazz = Student.class; Student stuInstance = null;; try { stuInstance = stuClazz.newInstance(); } catch (InstantiationException e1) { e1.printStackTrace(); } catch (IllegalAccessException e1) { e1.printStackTrace(); } for (String key : paraKey) { //通过Key获得对应的值 String[] values = request.getParameterValues(key); try { Field field = stuClazz.getDeclaredField(key); Method stuMethod = stuClazz.getDeclaredMethod(creatSetter(key), field.getType()); //由于MySQL中的int类型对应Java的Integer,所以需要一步转换 if (field.getType().getName().equals("int") || field.getType().getName().equals("java.lang.Integer")) { //每个Key均只有一个值,所以只需要取String[]第一个值便可 stuMethod.invoke(stuInstance, Integer.parseInt(values[0])); } else { stuMethod.invoke(stuInstance, values[0]); } } catch (Exception e) { e.printStackTrace(); } } return stuInstance; } public String creatSetter(String colName) { String setMethod = "set" + colName.substring(0, 1).toUpperCase() + colName.substring(1); return setMethod; } public int insertDB(Object stuInstance){ int isSuccess = 0; //数据库中的id为主键且自增,所以不需要绑定 String sql = "insert into t_student(studentname,studentage,studentgender,studentphone,clazz_id) values(?,?,?,?,?);"; Connection conn = DB_Conn.openDB(); PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); Field[] stuFields = stuInstance.getClass().getDeclaredFields(); for (int i = 0; i < stuFields.length-1; i++) { ps.setObject(i+1, setField(stuInstance, stuFields[i+1])); } isSuccess = ps.executeUpdate(); conn.commit(); } catch (Exception e) { e.printStackTrace(); } finally{ DB_Conn.closeDB(conn, ps); } return isSuccess; } }
新学员信息表单:
<form action="studentadd" method="GET"> 学生姓名:<input type="text" name="studentname"><br> 学生年龄:<input type="text" name="studentage"><br> 学生性别:<input type="text" name="studentgender"><br> 学生手机:<input type="text" name="studentphone"><br> 学生班级:<input type="text" name="clazz_id"><br> <input type="submit" value="确认添加"> </form>
效果:
原文地址:https://www.cnblogs.com/Gikin/p/11396609.html
时间: 2024-10-16 03:07:33