Servlet连接数据库查询班级及相应班级学生

简介:访问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

Servlet连接数据库查询班级及相应班级学生的相关文章

20161213 输入一个班级中n个学生某一科的成绩(假设都是正整数)并计算这个班这科平均分是多少?

题目: 输入一个班级中n个学生某一科的成绩(假设都是正整数)并计算这个班这科平均分是多少? 今天的题,要求只能用我规定的四个变量来做,n表示n个学生,a表示每个学生的成绩,i用来控制循环,s表示总分,这样平均分就是s/n (保留一位小数).这道题每一部分大家都知道是什么意思,组合起来看能不能做出来. 代码: 老师的答案:

数据库 查询方法详解 以学生老师信息表为例

create table Student--3rd再次执行 ( Sno int primary key not null,--学号主键 Sname varchar(50) not null,--学生姓名 Ssex varchar(50) not null,--学生性别 Sbirthday datetime,--出生年月 Class int--班级 ) truncate table Student--清空表格 insert into Student values(108,'曾华','男','197

VC++ 通过ADO连接数据库查询时返回空值报错的解决方案

当数据库的字段值允许为空时, 而且此时内容也为空时,则执行查询会出错,例如 CString str = pRecordset->GetFields()->GetItem((long)0)->GetValue(); 或者 str= pRecordset->GetCollect("posInfo"); 会弹出如下窗口提示出错! 更加奇怪的是  catch(...)也抓不到异常 今天碰着个问题算是头弄大了  最后终于弄好了 报错的原因:   在GetCollct返回了

SQL查询有两门以上不及格的学生及查询出全部及格的学生

1.表结构: /*学生*/ create table student( sno int not null primary key, sname varchar(10) ); /*课程*/ create table center( cno int not null primary key, cname varchar(10) ); /*分数*/ create table sgrade( sno int , cno int , sgrade int ); 2.插入数据: insert into st

【sql: 联系题 23 24】查询同名学生名单,并统计同名人数 找到同名的名字并统计个数,查询 1990 年出生的学生名单

题目23:查询同名学生名单,并统计同名人数 找到同名的名字并统计个数 一开始这个sql 写不出来,看了答案后好简单,也更加加深了我多count 的用法 SELECT stdentname,COUNT(*) FROM student GROUP BY stdentname HAVING COUNT(*)>=2 ; 题目24:查询 1990 年出生的学生名单 这个题目我写的是用like 直接查询出来,但是还有第二种写法,用关键字YEAR 表示年 第二种写法: SELECT * FROM studen

向班级集合中添加学生信息

实现效果: 知识运用: System.Collections命名空间下的ArrayList集合类的Add()方法 使用了 DataGridView 控件 实现代码: private void Form1_Load(object sender, EventArgs e) { ArrayList list_StudentInfo = new ArrayList(); string students=""; string[] arr_student, arr_studentinfo; lis

安卓+servlet+MySql 查询+插入(汉字乱码解决)

问题: 安卓程序,通过servlet连接MySQL数据库,并实现查询和插入(修改,删除类似). 其中遇到的最大的问题是:汉字乱码问题(查询条件有汉字乱码.servlet的汉字到数据乱码.安卓通过servlet方法数据库汉字乱码) 当所有的编码(客户端,服务端,数据库)都为UTF-8时,但是插入汉字依然为乱码. 1.安卓客户端中的汉字到servlet中为乱码. 当插入到数据库的汉字为乱码(而不是问号)时. 解决方法: 在安卓客户端将String中的汉字由UTF-8转码为ISO8859-1. use

OC字典存入数组,输出数组中数据,并且删除小明一项,然后进行排序、现根据班级排序,班级相同的用年龄进行排序

#import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { NSDictionary *[email protected]{@"name":@"小阳", @"class":@"IOS8", @"age":@"20" }; NSDictionary

Servlet分页查询

分页查询: 1.逻辑分页查询:用户第一次访问时就把全部数据访问出来,添加到一个大集合中,然后放到session中,进行转发.通过页码等的计算,把要显示的内容添加到一个小集合中,转发.遍历小集合以显示当前页码的数据 代码实现: Dao: package general.page.query; import java.lang.reflect.InvocationTargetException;import java.sql.Connection;import java.sql.PreparedSt