首先构建添加javaweb和mvmen框架
系统整体架构
工具类src/main/java/dao/JdbcTools.java
package dao;
import org.apache.commons.beanutils.BeanUtils;
//工具类可以直接选择调用
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.*;
public class JdbcTools {
private static String driver;
private static String url;
private static String user;
private static String password;
//静态代码块,提前加载,只有一次
static {
//I/O
InputStream resourceAsStream = JdbcTools.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
try {
properties.load(resourceAsStream);
} catch (IOException e) {
e.printStackTrace();
}
driver = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
//加载驱动
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//释放资源
if (resourceAsStream != null) {
try {
resourceAsStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 1.完成数据库链接操作
*
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
Connection connection = DriverManager.getConnection(url, user, password);
return connection;
}
// @Test
public void study()
{
System.out.println("111 = " + 111);
}
/**
* 2.获取完整的预编译好的sql对象
*
* @param sql 预编译的sql语句
* @param connection db链接对象
* @param parameters sql替换的参数
* @return 预编译好的sql对象
* @throws SQLException
*/
public static PreparedStatement getPreparedStatement(String sql, Connection connection, Object... parameters) throws SQLException {
PreparedStatement statement = connection.prepareStatement(sql);
//1.获取元数据
ParameterMetaData parameterMetaData = statement.getParameterMetaData();
//2.获取字符串需要的参数个数
int count = parameterMetaData.getParameterCount();
//3.判断是否传参,并且设置参数值
if (count != 0 && parameters != null && parameters.length == count)
for (int i = 0; i < count; i++) {
statement.setObject(i + 1, parameters[i]);
}
return statement;
}
/**
* 3.实现更新
* @param sql
* @param parameters
* @return
* @throws SQLException
*/
public static int update1(String sql, Object... parameters) throws SQLException {
Connection connection = JdbcTools.getConnection();
PreparedStatement preparedStatement = getPreparedStatement(sql, connection, parameters);
int i = preparedStatement.executeUpdate();
return i;
}
/**
* 4. 关闭对象,释放资源
* @param resources
*/
public static void closeAll(AutoCloseable... resources) {
if (resources != null && resources.length > 0) {
Arrays.stream(resources).forEach(source -> {
if (source != null) {
System.out.println("source = " + source);
try {
source.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
/**
* 5.根据条件查询一条数据,以传入的javaBean类型返回 null
*
* @param sql
* @param cls
* @param parameters
* @param <T>
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static <T> T queryBean(String sql, Class<T> cls, Object... parameters) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException {
//1.定义需要的变量
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
T t = null;//初始值
//2.获取链接
connection = JdbcTools.getConnection();
//3.获取sql的预编译对象
preparedStatement = JdbcTools.getPreparedStatement(sql, connection, parameters);
//4.执行查询,得到结果集
resultSet = preparedStatement.executeQuery();
//5.反编译对象,从结果集中获取表的元数据
ResultSetMetaData metaData = resultSet.getMetaData();
System.out.println("metaData = " + metaData);
if(resultSet.next())//false
{
t = cls.newInstance();//实例化一个bean的空对象,用来封装数据
int count = metaData.getColumnCount();
for (int i = 1; i <= count; i++) {
BeanUtils.setProperty(t, metaData.getColumnName(i), resultSet.getObject(i));
}
JdbcTools.closeAll(connection, preparedStatement, resultSet);
return t;
}
return t;
}
/**
* 6.根据条件查询多条数据
*
* @param sql String
* @param cls Class<T>
* @param parameters 替换函数
* @param <T>
* @return
* @throws SQLException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static <T> List<T> queryBeanList(String sql, Class<T> cls, Object... parameters) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException {
//1.定义需要的变量
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
ArrayList<T> arrayList = new ArrayList<>();
T t = null;
//2.获取链接
connection = JdbcTools.getConnection();
//3.获取sql的预编译对象
preparedStatement = JdbcTools.getPreparedStatement(sql, connection, parameters);
//4.执行查询,得到结果集
resultSet = preparedStatement.executeQuery();
System.out.println("resultSet = " + resultSet);
//5.反编译对象,从结果集中获取表的元数据
ResultSetMetaData metaData = resultSet.getMetaData();
System.out.println("metaData = " + metaData);
int count = metaData.getColumnCount();
while (resultSet.next()) {
t = cls.newInstance();//实例化一个bean的空对象,用来封装数据
for (int i = 1; i <= count; i++) {
BeanUtils.setProperty(t, metaData.getColumnName(i), resultSet.getObject(i));
}
arrayList.add(t);
}
JdbcTools.closeAll(connection, preparedStatement, resultSet);
return arrayList;
}
/**
* 7.查询多条记录,以Map集合的形式返回。
* @param sql
* @param parameters
* @return
* @throws SQLException
*/
public static ArrayList<Map> queryMapList(String sql, Object... parameters) throws SQLException {
//1.定义需要的变量
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
ArrayList<Map> maps = new ArrayList<>();
//2.获取链接
connection = JdbcTools.getConnection();
//3.获取sql的预编译对象
preparedStatement = JdbcTools.getPreparedStatement(sql, connection, parameters);
//4.执行查询,得到结果集
resultSet = preparedStatement.executeQuery();
//5.反编译对象,从结果集中获取表的元数据
ResultSetMetaData metaData = resultSet.getMetaData();
int count = metaData.getColumnCount();
while (resultSet.next()) {
HashMap<String, Object> map = new HashMap<>();
for (int i = 1; i <= count; i++) {
map.put(metaData.getColumnName(i), resultSet.getObject(i));
}
maps.add(map);
}
JdbcTools.closeAll(connection, preparedStatement, resultSet);
return maps;
}
/**
* 8.查询一条记录,以数组形式返回
*
* @param sql
* @param parameters
* @return Array
* @throws SQLException
*/
public static Object[] queryArray(String sql, Object... parameters) throws SQLException {
//1.定义需要的变量
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
//2.获取链接
connection = JdbcTools.getConnection();
//3.获取sql的预编译对象
preparedStatement = JdbcTools.getPreparedStatement(sql, connection, parameters);
//4.执行查询,得到结果集
resultSet = preparedStatement.executeQuery();
//5.反编译对象,从结果集中获取表的元数据
ResultSetMetaData metaData = resultSet.getMetaData();
int count = metaData.getColumnCount();
Object[] o = new Object[count];//定义长度为count的空数组
resultSet.next();
for (int i = 0; i < count; i++) {
o[i] = resultSet.getObject(i + 1);
}
JdbcTools.closeAll(connection, preparedStatement, resultSet);
return o;
}
/**
* 9.查询多条记录,以数组集合(集合中的数据是数组)的数据状态返回
*
* @param sql sql查询语句
* @param parameters 替换参数
* @return List
* @throws SQLException
*/
public static List<Object[]> queryArrayList(String sql, Object... parameters) throws SQLException {
//1.定义需要的变量
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<Object[]> objects = new ArrayList<>();
//2.获取链接
connection = JdbcTools.getConnection();
//3.获取sql的预编译对象
preparedStatement = JdbcTools.getPreparedStatement(sql, connection, parameters);
//4.执行查询,得到结果集
resultSet = preparedStatement.executeQuery();
//5.反编译对象,从结果集中获取表的元数据
ResultSetMetaData metaData = resultSet.getMetaData();
int count = metaData.getColumnCount();
while (resultSet.next()) {
Object[] o = new Object[count];//定义长度为count的空数组
for (int i = 0; i < count; i++) {
o[i] = resultSet.getObject(i + 1);
}
objects.add(o);
}
JdbcTools.closeAll(connection, preparedStatement, resultSet);
return objects;
}
/**
* 10.查询一条记录,以键值对形式返回
* @param sql
* @param parameters
* @return
* @throws SQLException
*/
public static Map<String,Object> queryMap(String sql, Object... parameters) throws SQLException {
//1.定义需要的变量
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
//2.获取链接
connection = JdbcTools.getConnection();
//3.获取sql的预编译对象
preparedStatement = JdbcTools.getPreparedStatement(sql, connection, parameters);
//4.执行查询,得到结果集
resultSet = preparedStatement.executeQuery();
//5.反编译对象,从结果集中获取表的元数据
ResultSetMetaData metaData = resultSet.getMetaData();
int count = metaData.getColumnCount();
HashMap<String, Object> map = new HashMap<>();
while (resultSet.next()) {
for (int i = 1; i <= count; i++) {
map.put(metaData.getColumnName(i), resultSet.getObject(i));
}
}
JdbcTools.closeAll(connection, preparedStatement, resultSet);
return map;
}
/**
* 11.更新
* @param sql
* @param parameters
* @return
* @throws SQLException
*/
public static int del(String sql, Object... parameters) throws SQLException {
Connection connection = JdbcTools.getConnection();
PreparedStatement preparedStatement = getPreparedStatement(sql, connection, parameters);
int i = preparedStatement.executeUpdate();
return i;
}
}
javabeab stu 位置: src/main/java/model/stu.java
package model;
//jiavabean文件user表
public class User {
private String username;
private String password;
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
/**
* 获取
* @return username
*/
public String getUsername() {
return username;
}
/**
* 设置
* @param username
*/
public void setUsername(String username) {
this.username = username;
}
/**
* 获取
* @return password
*/
public String getPassword() {
return password;
}
/**
* 设置
* @param password
*/
public void setPassword(String password) {
this.password = password;
}
public String toString() {
return "User{username = " + username + ", password = " + password + "}";
}
}
javabeab user 位置:src/main/java/model/User.java
package model;
//jiavabean文件user表
public class User {
private String username;
private String password;
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
/**
* 获取
* @return username
*/
public String getUsername() {
return username;
}
/**
* 设置
* @param username
*/
public void setUsername(String username) {
this.username = username;
}
/**
* 获取
* @return password
*/
public String getPassword() {
return password;
}
/**
* 设置
* @param password
*/
public void setPassword(String password) {
this.password = password;
}
public String toString() {
return "User{username = " + username + ", password = " + password + "}";
}
}
验证码生产工具src/main/java/Tool/Code.java
package Tool;
import cn.dsna.util.images.ValidateCode;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/code")
public class Code extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 创建一个ValidateCode对象,设置宽度为500,高度为200,字符个数为4,干扰线数为100。
ValidateCode validateCode = new ValidateCode(500, 200, 4, 100);
// 调用getCode()方法生成验证码字符串。
String code = validateCode.getCode();
//创建会话
HttpSession session = req.getSession();
// 将生成的验证码字符串存储在会话中,键名为"yz"。
session.setAttribute("yz", code);
// 将验证码图片写入响应输出流。
validateCode.write(resp.getOutputStream());
}
}
数据库连接配置文件德鲁伊版src/main/resources/dridok.properties
driverClassName = com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/shangluo666?useSSL=false&serverTimezone=UTC
username=root
password=123456
#初始化时建立物理连接的个数
initialSize=10
#最大连接池数量
maxActive=20
#获取连接时最大等待时间
maxWait=10000
数据库连接配置文件src/main/resources/jdbc.properties
user=root
password=123456
implementation 'mysql:mysql-connector-java:8.0.26'
url=jdbc:mysql://localhost:3306/shangluo666?useSSL=false&serverTimezone=UTC
driver=com.mysql.cj.jdbc.Driver
1.pom.xml文件添加依赖(验证码依赖无法进行添加,需要在前端新建lib文件夹导入jar包)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>groupId</groupId>
<artifactId>hotwed</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<!-- 添加servlet依赖-->
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- mysql数据库的依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<!-- 德鲁伊的依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.23</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>
1.2.12
</version>
</dependency>
</dependencies>
</project>
2前端登录页面,login.jsp
<%--
Created by IntelliJ IDEA.
User: 86173
Date: 2024/7/29
Time: 11:13
To change this template use File | Settings | File Templates.
--%>
<%--<%@ page contentType="text/html;charset=UTF-8" language="java" %>--%>
<%--<html>--%>
<%--<head>--%>
<%-- <title>Title</title>--%>
<%--</head>--%>
<%--<body>--%>
<%--<h1>欢迎登录!</h1>--%>
<%--<form action="loginok2" method="post">--%>
<%-- 姓名<input type="text" name="user"><br>--%>
<%-- 密码<input type="text" name="pwd"><br>--%>
<%--<%– 点击时重新生成新的验证码 //–%>--%>
<%-- <img src="code" alt="" width="100" onclick="this.src=this.src+'?'+Math.random()">--%>
<%-- <input type="text" name="yz" >--%>
<%-- <button>登陆</button>--%>
<%--</form>--%>
<%--</body>--%>
<%--</html>--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>学生信息管理系统登录页</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f7f7f7;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.box {
width: 360px;
background-color: #fff;
border-radius: 10px;
padding: 30px;
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
display: flex;
flex-direction: column;
align-items: center;
}
h1 {
font-size: 26px;
margin-bottom: 20px;
color: #333;
text-align: center;
}
form {
width: 100%;
}
.form-group {
margin-bottom: 20px;
display: flex;
flex-direction: column;
}
.form-group label {
margin-bottom: 5px;
font-size: 14px;
color: #555;
}
.form-group input[type="text"] {
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
box-sizing: border-box;
width: 100%;
}
.form-group input[type="text"]:focus {
border-color: #4CAF50;
outline: none;
}
.captcha-container {
display: flex;
align-items: center;
margin-bottom: 20px;
}
.captcha-container img {
margin-left: 10px;
cursor: pointer;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
button {
background-color: #4CAF50;
color: white;
padding: 12px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s ease;
width: 100%;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div class="box">
<h1>学生信息管理系统登录页</h1>
<form action="loginok2" method="post">
<div class="form-group">
<label for="user">账号</label>
<input type="text" id="user" name="user" placeholder="请输入账号">
</div>
<div class="form-group">
<label for="pw">密码</label>
<input type="text" id="pw" name="pwd" placeholder="请输入密码">
</div>
<div class="captcha-container">
<div class="form-group">
<label for="yzm">验证码</label>
<input type="text" id="yzm" name="yz" placeholder="请输入验证码">
</div>
<img src="code" alt="验证码" width="120" onclick="this.src=this.src+'?'+Math.random()">
</div>
<button type="submit">登录</button>
</form>
</div>
</body>
</html>
3登录页面进入后会进行后端处理判断账号密码,进行信息展示和错误提醒src/main/java/servlet/UserRequest2.java
package servlet;
//继承HttpServlet的方式进行连接前段
import dao.JdbcTool;
import dao.JdbcTools;
import model.User;
import model.stu;
import model.student;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;
//系统展示成功进入后展示页面
@WebServlet("/loginok2")
public class UserRequest2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
//前面那个是请求,后面那个是响应
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String user = req.getParameter("user");
String pwd = req.getParameter("pwd");
String yz = req.getParameter("yz");
System.out.println("user = " + user);
System.out.println("pwd = " + pwd);
System.out.println("yz = " + yz);
//判断用户输入的验证码和机器生成的验证码是否相同
//创建会话Java Servlet中获取HttpSession对象并从中获取名为"yz"的属性值的示例。
// 首先,通过调用req.getSession()方法获取HttpSession对象。
// 然后,使用session.getAttribute("yz")方法从会话中获取名为"yz"的属性值存到yz1里面。
HttpSession session = req.getSession();
String yz1 = (String) session.getAttribute("yz");
if (!yz1.equals(yz))
{
System.out.println("验证码错误");
return;
}
访问dao层
// if (denglvdaotest.dlcx(user, pwd)) {
// //数据展示 servlet
// req.getRequestDispatcher("showlist").forward(req, resp);
//
// } else {
// //错误提示servlet
// req.getRequestDispatcher("usererror").forward(req, resp);
// }
//访问Dao,查询记录
String sql="select * from user where username=? and password=?";
try {
List<User> is = JdbcTool.select(sql, User.class, user, pwd);
//如果查到结果为空进行错误提醒
if(is.isEmpty())
{
//错误提示servlet
req.getRequestDispatcher("usererror").forward(req,resp);
}else{
//查询到结果,进入到数据展示
System.out.println("进入");
// 获取数据库中的展示数据
List<stu> stulist= JdbcTool.select("select * from stu ", stu.class);
// System.out.println("stulist = " + stulist);
// 进行数据请求
req.setAttribute("stulist",stulist);
//数据展示 servlet
req.getRequestDispatcher("showlist").forward(req,resp);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
3-1,若账号密码失败则进入错误提醒页面src/main/java/UI/UserError.java
package UI;
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 java.io.IOException;
import java.io.PrintWriter;
//用户登录失败之后的错误页面
/**
* 服务器端渲染生成错误页面
*/
@WebServlet("/usererror")
public class UserError extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// System.out.println("用户登陆失败!");
//服务端生成前端页面 CGI
req.setCharacterEncoding("utf-8");//响应用户请求时,告知用户服务器的编码
resp.setContentType("text/html;charset=utf-8");
PrintWriter user = resp.getWriter();
user.write("<!Doctype html>");
user.write("<html>");
user.write("<head>");
user.write("<meta charset='utf-8>'");
user.write("</head>");
user.write("<body>");
user.write("<h2 style='color:red;font-weight:bold;'>" +
"用户名或密码有错误,请重新登陆" +
"</h2>" +
"<p>请重新登陆<p>");
user.write("</body>");
user.write("</html>");
}
}
3-2若账号密码正确进入信息展示页面src/main/java/UI/ShowList.java
package UI;
import model.stu;
import model.student;
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 java.io.Console;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
//登录成功的展示页面
/**
* 服务器端渲染生成信息展示页面
* 以表格的形式展示数据
*/
@WebServlet("/showlist")
public class ShowList extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//先请求
req.setCharacterEncoding("utf-8");
//再响应
resp.setContentType("text/html;charset=utf-8");
//1. servlet类
List<stu> stulist = (List<stu>) req.getAttribute("stulist");
// System.out.println("信息列表");
//动态生成前段页面
PrintWriter writer = resp.getWriter();
writer.write("<!Doctype html");
writer.write("<html>");
writer.write("<head>");
writer.write("</head>");
writer.write("<body style='background:lightyellow;'>");
writer.write("<h1>学生信息展示页面</h1>");
writer.write("<h3><a href='insert'>录入信息按钮</a><h3>");
writer.write("<table cellpadding='3' cellspacing='0' border='1' align='center'>");
writer.write("<tr><th>ID</th><th>姓名</th><th>年龄</th><th>操作1</th><th>操作2</th></tr>");
for (int i = 0; i < stulist.size(); i++) {
writer.write("<tr>");
writer.write("<td>" + stulist.get(i).getId() + "</td>");
writer.write("<td>" + stulist.get(i).getName()+ "</td>");
writer.write("<td>" + stulist.get(i).getAge()+ "</td>");
writer.write("<td><a onclick=\"if(confirm('确认删除么?'))return true;return false;\" href=delone?id=" + stulist.get(i).getId() +">删除</a></td>");
writer.write("<td><a href=updateshow?id=" + stulist.get(i).getId() +">更新</a></td>");
writer.write("</tr>");
}
writer.write("</table>");
writer.write("</body>");
writer.write("</html>");
}
}
4根据前端弹出的页面提示触发信息的录入,删除,更新和验证功能
4-1信息录入,先生成信息录入的空白表单src/main/java/UI/Stulnsertdata.java
package UI;
import model.stu;
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 java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
//插入数据的表单输入生成页面
@WebServlet("/insert")
public class Stulnsertdata extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 先请求
req.setCharacterEncoding("utf-8");
//再响应
resp.setContentType("text/html;charset=utf-8");
//动态生成前段页面
PrintWriter writer = resp.getWriter();
writer.write("<!Doctype html");
writer.write("<html>");
writer.write("<head>");
writer.write("</head>");
writer.write("<h1>学生信息添加页面</h1>");
writer.write("<body style='background:lightblue;'>");
writer.write("<h1>学生信息展示页面</h1>");
writer.write("<div style='margin:0 auto;width:600px;border:solid 3px red;'>"
+ "<h3><a href='insert'>录入信息</a></h3>");
writer.write("<form action='insertok'>" +
"姓名:<input type='text' name='name'><br>" +
"年龄:<input type='text' name='age'><br>" +
"<button>提交</button>" +
"<input type='resert' value='重置’/>" + "</form>" + "</div>");
writer.write("</body>");
writer.write("</html>");
}
}
4-1-1生成表单之后,跳转页面进行数据的添加和重新展示src/main/java/servlet/insertok.java
package servlet;
import dao.JdbcTool;
import dao.JdbcTools;
import model.stu;
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 java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;
//插入之后的重新显示页面
@WebServlet("/insertok")
public class insertok extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 真正的实现入库操作,并且跳转展示页面
// 接受前一个页面的表单值
// 动态生成表单
// 先请求
req.setCharacterEncoding("utf-8");
//再响应
resp.setContentType("text/html;charset=utf-8");
// 通过请求获取到输入得name和age
String name = req.getParameter("name");
String age = req.getParameter("age");
try {
int i = JdbcTools.update1("insert into stu values(null,?,?)", name, age);
// 数据展示servlet
if (i > 0) {
//获取成功后,重新获取数据,动态生成前段页面
List<stu> stulist = JdbcTool.select("select * from stu ", stu.class);
// System.out.println("stulist = " + stulist);
// 这段代码是在Java的Servlet中设置属性的一种方式。req.setAttribute("stulist", stulist); 这行代码的作用是将名为"stulist"的属性设置为变量stulist的值。这样,你可以在后续的请求处理过程中通过这个属性名来获取到这个值。
//
//在Java Servlet中,HttpServletRequest对象的setAttribute方法用于存储一个对象,
// 以便在同一个请求的生命周期内的其他部分(例如JSP页面或其他Servlet)可以访问它。
// 这个方法接受两个参数:一个是属性的名称(字符串),另一个是要存储的对象。
req.setAttribute("stulist", stulist);
//数据展示 servlet
// 在Java Servlet中,HttpServletRequest对象的getRequestDispatcher方法用于获取一个RequestDispatcher对象,该对象可以将请求转发到指定的资源。这个方法接受一个参数,即要转发到的资源的名称或路径。
//
//然后,通过调用RequestDispatcher对象的forward方法,将当前的请求和响应对象传递给目标资源。这样,目标资源可以处理这个请求并生成响应,然后将响应发送回客户端。
// req.getRequestDispatcher("showlist").forward(req,resp);
//HttpServletResponse对象的sendRedirect方法用于将客户端重定向到另一个URL。
// 这个方法接受一个参数,即要重定向到的目标URL。
resp.sendRedirect("showlist");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
4-2数据删除src/main/java/servlet/Studel.java 根据前端点击删除按钮跳转删除,并且重新生产页面
package servlet;
import dao.JdbcTool;
import dao.JdbcTools;
import model.stu;
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 java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;
//删除之后的重新显示页面
@WebServlet("/delone")
public class Studel extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取到id进行删除
String id = req.getParameter("id");
System.out.println("id = " + id);
//调用dao包的api进行删除
try {
int del = JdbcTools.del("delete from stu where id=?", id);
System.out.println("找到id啦"+del);
if (del>0){
//获取成功后,重新获取数据,动态生成前段页面
List<stu> stulist= JdbcTool.select("select * from stu ", stu.class);
System.out.println("stulist = " + stulist);
req.setAttribute("stulist",stulist);
//数据展示 servlet
req.getRequestDispatcher("showlist").forward(req,resp);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
4-3数据更新,先从showlist页面点击更新操作,进入页面进行数据表单回显,并且进行修改
src/main/java/UI/updatashow.java
package UI;
import dao.JdbcTools;
import model.stu;
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 java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
//更新的数据回显页面
@WebServlet("/updateshow")
public class updatashow extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//先请求,设置编码
req.setCharacterEncoding("utf-8");
//再响应
resp.setContentType("text/html;charset=utf-8");
//获取id进行查询
String id = req.getParameter("id");
// System.out.println("id = " + id);
stu stu = null;
try {
stu = JdbcTools.queryBean("select * from stu where id=?", stu.class, id);
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//动态生成前段页面
PrintWriter writer = resp.getWriter();
writer.write("<!Doctype html");
writer.write("<html>");
writer.write("<head>");
writer.write("</head>");
writer.write("<tittle>学生信息更新页面</tittle>");
writer.write("<body style='background:lightblue;'>");
writer.write("<h1>学生信息更新页面</h1>");
writer.write("<div style='margin:0 auto;width:600px;border:solid 3px red;'>"
+ "<h3><a href='insert'>请修改你要更新的字段</a></h3>");
writer.write("<form action='updateok'>" +
"<input type='hidden' value=" +
stu.getId() +
" name='id'><br>" +
"姓名:<input type='text' value=" +
stu.getName() +
" name='name'><br>" +
"年龄:<input type='text' value="+
stu.getAge()+
" name='age'><br>" +
"<button>更新</button>" +
"<input type='resert' value='重置’/>" + "</form>" + "</div>");
writer.write("</body>");
writer.write("</html>");
}
}
4-3-1数据回显之后进行更新操作,并且重新生成数据显示页面
src/main/java/servlet/updateok.java
package servlet;
import dao.JdbcTools;
import model.stu;
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 java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;
@WebServlet("/updateok")
public class updateok extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//动态生成表单
// 1设编
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
String id = req.getParameter("id");
String name = req.getParameter("name");
String age = req.getParameter("age");
// 调用数据操作类
try {
int i = JdbcTools.update1("update stu set name=?,age=? where id=?", name, age, id);
if (i > 0) {
List<stu> stulist = JdbcTools.queryBeanList("select *from stu", stu.class);
req.setAttribute("stulist", stulist);
//数据展示 servlet
req.getRequestDispatcher("showlist").forward(req, resp);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
验证码的添加步骤
错误小结
严格遵守前端文字格式,要有空格