文章目录

  • 前言
  • 一、数据库和实体类的建立
    • 1.数据库的创建
    • 2.实体类的创建
  • 二、dao、service、servlet和前端jsp的编写
    • 1.dao层
      • 1.编写链接数据库、以及查询、更新、释放等代码
      • 2.编写接口
    • 2.service层
    • 3.servlet层
    • 3.jsp前端
  • 二、运行截图
  • 总结

前言

这里主要讲述一些采用mvc三层架构的方式,编写dao、service、servlet、前端jsp代码来实现提取数据库数据显示到前端网页表单中。这里以获取数据库中准考证信息为例子。

所用的编译器idea、基于maven的javaweb、服务器是tomcat、mysql版本8.0.22。

一、数据库和实体类的建立

1.数据库的创建

提示:这里只是示例我本人自己的数据库:
数据库名称、表名称、以及内容(示例):

2.实体类的创建

StudentInfo.java代码如下(示例):

package edu.login.pojo;public class StudentInfo {String name;String candidate_number;String id_number;String gender;String subject;String address;String time;String seat;String email;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getCandidate_number() {return candidate_number;}public void setCandidate_number(String candidate_number) {this.candidate_number = candidate_number;}public String getId_number() {return id_number;}public void setId_number(String id_number) {this.id_number = id_number;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public String getSubject() {return subject;}public void setSubject(String subject) {this.subject = subject;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public String getTime() {return time;}public void setTime(String time) {this.time = time;}public String getSeat() {return seat;}public void setSeat(String seat) {this.seat = seat;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}@Overridepublic String toString() {return "StudentInfo{" +"name='" + name + '\'' +", candidate_number='" + candidate_number + '\'' +", id_number='" + id_number + '\'' +", gender='" + gender + '\'' +", subject='" + subject + '\'' +", address='" + address + '\'' +", time='" + time + '\'' +", seat='" + seat + '\'' +", email='" + email + '\'' +'}';}}

二、dao、service、servlet和前端jsp的编写

1.dao层

过程图示:

在编写dao层的时候,这里初始化连接参数,从配置文件里获得
创建db.properties文件如图

文件内容:

driver=com.mysql.cj.jdbc.Driverurl=jdbc:mysql://127.0.0.1:3306/test?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8user=rootpassword=filters=statinitialSize=2maxActive=300maxWait=60000timeBetweenEvictionRunsMillis=60000minEvictableIdleTimeMillis=300000validationQuery=SELECT 1testWhileIdle=truetestOnBorrow=falsetestOnReturn=falsepoolPreparedStatements=falsemaxPoolPreparedStatementPerConnectionSize=200

注意:

  • driver,根据mysql的版本不同是不一样的,例如:如果是5.0的版本需要用,driver=“com.mysql.jdbc.Driver”
  • url,选择本地数据库就行,这里的test是我的数据库名字,后面的“?&”这些链接的是来防止乱码问题的
  • 本数据库root没有设置密码,所以我这里的password等于空
  • 其余复制下来就行

1.编写链接数据库、以及查询、更新、释放等代码

创建BaseDao.java代码如下,用来链接数据库

package edu.login.dao;import java.io.IOException;import java.io.InputStream;import java.sql.*;import java.util.Properties;/** * 操作数据库的基类--静态类 * @author Administrator * */public class BaseDao {//静态代码块,在类加载的时候执行static{init();}private static String driver;private static String url;private static String user;private static String password;//初始化连接参数,从配置文件里获得public static void init(){Properties params=new Properties();String configFile = "db.properties";InputStream is= BaseDao.class.getClassLoader().getResourceAsStream(configFile);try {params.load(is);} catch (IOException e) {e.printStackTrace();}driver=params.getProperty("driver");url=params.getProperty("url");user=params.getProperty("user");password=params.getProperty("password");}/** * 获取数据库连接 * @return */public static Connection getConnection(){Connection connection = null;try {Class.forName(driver);connection = DriverManager.getConnection(url, user, password);System.out.println("suceess ");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return connection;}/** * 查询操作 * @param connection * @param pstm * @param rs * @param sql * @param params * @return */public static ResultSet execute(Connection connection,PreparedStatement pstm,ResultSet rs,String sql,Object[] params) throws Exception{pstm = connection.prepareStatement(sql);for(int i = 0; i < params.length; i++){pstm.setObject(i+1, params[i]);}rs = pstm.executeQuery();return rs;}/** * 更新操作 * @param connection * @param pstm * @param sql * @param params * @return * @throws Exception */public static int execute(Connection connection,PreparedStatement pstm,String sql,Object[] params) throws Exception{int updateRows = 0;pstm = connection.prepareStatement(sql);for(int i = 0; i < params.length; i++){pstm.setObject(i+1, params[i]);}updateRows = pstm.executeUpdate();return updateRows;}/** * 释放资源 * @param connection * @param pstm * @param rs * @return */public static boolean closeResource(Connection connection,PreparedStatement pstm,ResultSet rs){boolean flag = true;if(rs != null){try {rs.close();rs = null;//GC回收} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();flag = false;}}if(pstm != null){try {pstm.close();pstm = null;//GC回收} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();flag = false;}}if(connection != null){try {connection.close();connection = null;//GC回收} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();flag = false;}}return flag;}}

代码如下(示例):

import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport warningswarnings.filterwarnings('ignore')importsslssl._create_default_https_context = ssl._create_unverified_context

2.编写接口

创建接口:UserDao.java

package edu.login.dao.user;import edu.login.pojo.ScoreInfo;import edu.login.pojo.StudentInfo;import edu.login.pojo.User;import java.sql.Connection;public interface UserDao {//获取学生准考证信息public StudentInfo findAll(Connection connection ,String candidate_number) throws Exception;}

实现接口里面的方法:UserDaoIml.java

package edu.login.dao.user;import edu.login.dao.BaseDao;import edu.login.pojo.ScoreInfo;import edu.login.pojo.StudentInfo;import edu.login.pojo.User;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;public class UserDaoIml implements UserDao {@Overridepublic StudentInfo findAll(Connection connection, String candidate_number) throws Exception {PreparedStatement pstm = null;//搭桥者ResultSet rs = null;StudentInfo studentInfo = null;if (null != connection) {String sql = "select * from t_admission_ticket where candidate_number=?";Object[] params = {candidate_number};rs = BaseDao.execute(connection, pstm, rs, sql, params);//得到结果集if (rs.next()) {//把搜索到数据库中的内容读写到实体类中studentInfo = new StudentInfo();studentInfo.setName(rs.getString("name"));studentInfo.setEmail(rs.getString("email"));studentInfo.setSeat(rs.getString("seat"));studentInfo.setTime(rs.getString("time"));studentInfo.setAddress(rs.getString("address"));studentInfo.setSubject(rs.getString("subject"));studentInfo.setCandidate_number(rs.getString("candidate_number"));studentInfo.setGender(rs.getString("gender"));studentInfo.setId_number(rs.getString("id_number"));}BaseDao.closeResource(null, pstm, rs);} else {System.out.println("fail");System.out.println("fail");System.out.println("fail");}return studentInfo;}}

2.service层

过程图示:

创建接口:UserService.java

package edu.login.service.user;import edu.login.pojo.ScoreInfo;import edu.login.pojo.StudentInfo;import edu.login.pojo.User;public interface UserService {//获取学生准考证信息public StudentInfo FindAll(String candidate_number);}

实现接口方法:UserServiceImpl.java

package edu.login.service.user;import edu.login.dao.BaseDao;import edu.login.dao.user.UserDao;import edu.login.dao.user.UserDaoIml;import edu.login.pojo.ScoreInfo;import edu.login.pojo.StudentInfo;import edu.login.pojo.User;import java.sql.Connection;import java.sql.SQLException;public class UserServiceImpl implements UserService{//业务层都会调用Dao层,所以要引入Dao层private UserDao userDao;public UserServiceImpl(){userDao = new UserDaoIml();}@Overridepublic StudentInfo FindAll(String candidate_number) {Connection connection = null;StudentInfo studentInfos=null;try {connection = BaseDao.getConnection();studentInfos= userDao.findAll(connection, candidate_number);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{BaseDao.closeResource(connection, null, null);}return studentInfos;}

3.servlet层

过程图示:

ShowInfoServlet.java代码如下

这里把要查询的学号candidate_number静态设置为100101,也可以通过从req前端获取或者session获取。

package edu.login.servlet.user;import edu.login.pojo.StudentInfo;import edu.login.pojo.User;import edu.login.service.user.UserService;import edu.login.service.user.UserServiceImpl;import edu.login.util.Constants;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.util.Arrays;import java.util.Collections;import java.util.List;public class ShowInfoServlet extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//调用service方法,进行用户匹配UserService userService=new UserServiceImpl();String candidate_number="10010";//这里的值可以从前端获取,可以从session里面获取,这里简单设置一下。StudentInfo studentInfos=userService.FindAll(candidate_number);System.out.println();System.out.println(studentInfos);//后端验证//把实体类转换成listList<StudentInfo>StudentList= Collections.singletonList(studentInfos);System.out.println();System.out.println(StudentList);//后端验证//将数据保存到数据域中req.setAttribute("StudentList",StudentList);//转发调转到准考证查询req.getRequestDispatcher("showStudentInfo.jsp").forward(req,resp);}}

web,xml配置:

<servlet><servlet-name>ShowInfoServlet</servlet-name><servlet-class>edu.login.servlet.user.ShowInfoServlet</servlet-class></servlet><servlet-mapping><servlet-name>ShowInfoServlet</servlet-name><url-pattern>/ShowInfo.do</url-pattern></servlet-mapping>

3.jsp前端

这里我只显示直接前端jsp代码,因为实际上我加了许多css、js格式只为了美化表单。

<%@ page contentType="text/html;charset=UTF-8" language="java" %><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <div class="container"><table class="table table-bordered table-hover"><tr class="success"><th>姓名</th><th>学号</th><th>身份证号</th><th>性别</th><th>考场</th><th>邮箱</th><th>数学</th><th>英语</th><th>专业课</th></tr><jsp:useBean id="ScoreList" scope="request" type="java.util.List"/><c:forEach var="li" items="${ScoreList}" varStatus="s"><tr><!--切记不能用打写例如:li.Name--><td>${li.name}</td><td>${li.candidate_number}</td><td>${li.id_number}</td><td>${li.gender}</td><td>${li.address}</td><td>${li.email}</td><td>${li.math}</td><td>${li.english}</td><td>${li.scources}</td></tr></c:forEach></table></div>

二、运行截图


总结

愿自学的小伙伴们,今天依旧是收获满满的一天。