Javaweb02
学生信息CURD
1、查询
1.首先创建了一个StudentServlet类,第一步使用JDBC去获取学生信息数据库,取出数据并存放在一个List当中。
2.setAttribute
是ServletRequest接口的一个方法,用于在请求中设置一个属性。它的语法是:
void setAttribute(String name, Object value)
name
参数是属性的名字,可以是任意字符串。一般推荐使用合理的命名规范来避免冲突。value
参数是属性的值,可以是任意的Java对象。
使用setAttribute
方法可以将数据存储在请求对象中,在整个请求的生命周期内都可以访问到。
例如,req.setAttribute("aaa", data)
将名为"aaa"
的属性设置为data
变量的值。
可以通过ServletRequest
接口的其他方法,如getAttribute
来获取设置的属性值。
Object value = req.getAttribute("aaa");
这样的代码可以在同一个请求中获取到之前通过setAttribute
方法存储的属性值。
3.getRequestDispatcher
是ServletRequest接口的一个方法,用于获取请求调度器。它的语法是:
RequestDispatcher getRequestDispatcher(String path)
path
参数是一个字符串,表示要转发或包含的目标资源的路径。这可以是一个相对路径或绝对路径。
通过getRequestDispatcher
方法可以获取到一个RequestDispatcher
对象,用于将请求转发到其他资源或包含其他资源。
例如,req.getRequestDispatcher("student.jsp")
将获取到与"student.jsp"
对应的请求调度器。
可以使用RequestDispatcher
的forward
方法将当前请求转发给另一个资源。
dispatcher.forward(request, response);
这将停止当前资源的处理,将请求和响应传递给目标资源进行处理。目标资源可以是一个JSP页面、Servlet或其他可处理请求的组件。
另外,getRequestDispatcher
也可以用于获取同一应用程序中其他servlet的调度器,以便实现包含关系和共享请求数据的功能。
StudentServlet类
package com.grg;
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.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* @Author Grg
* @Date 2023/8/22 9:27
* @PackageName:com.grg
* @ClassName: servlet
* @Description: 又是码代码的一天
* @Version plus max 宇宙无敌终极版本
*/
@WebServlet("/stu")
public class StudentServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.查询数据
List<HashMap<String, Object>> data = new ArrayList<>();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql:///jdbctest", "root", "123456");
PreparedStatement ps = conn.prepareStatement("select * from student");
ResultSet set = ps.executeQuery();
while (set.next()) {
HashMap<String, Object> map = new HashMap<>();
for (int i = 1; i <= set.getMetaData().getColumnCount(); i++) {
map.put(set.getMetaData().getColumnLabel(i),
set.getObject(i));
}
data.add(map);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
req.setAttribute("aaa", data);
req.getRequestDispatcher("student.jsp").forward(req, resp);
}
}
4.将请求转到student.jsp页面
<%--
Created by IntelliJ IDEA.
User: asus
Date: 2023/8/22
Time: 9:48
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<style>
.jumbotron {
text-align: center;
background: linear-gradient(45deg, #020031, #6d3353);
color: white;
}
</style>
</head>
<body>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<div class="jumbotron">
<h1>欢迎来到学生管理系统</h1>
<p>欢迎您</p>
<p><a class="btn btn-primary btn-lg" href="/day01/addStu.jsp" role="button">添加学生</a></p>
</div>
<table class="table table-striped table-bordered table-hover table-condensed">
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
<th>住址</th>
<th style="width: 200px;">操作</th>
</tr>
<c:forEach var="s" items="${aaa}">
<tr>
<td>${s.id}</td>
<td>${s.name}</td>
<td>${s.age}</td>
<td>${s.address}</td>
<td>
<button class="btn btn-danger" οnclick="delStu(${s.id})">删除</button>
<a href="/day01/toUpdate?id=${s.id}" class="btn btn-primary">修改</a>
</td>
</tr>
</c:forEach>
</table>
<script>
function delStu(a){
if(confirm("确定删除吗")){
window.location.href = "/day01/delStu?id="+ a;
}
}
</script>
</body>
</html>
2、增加
在student.jsp中有添加学生的按钮
<p><a class="btn btn-primary btn-lg" href="/day01/addStu.jsp" role="button">添加学生
通过href绑定将请求发送给/day01/addStu.jsp
<%--
Created by IntelliJ IDEA.
User: asus
Date: 2023/8/22
Time: 9:54
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<style>
fieldset {
width: 500px;
margin: 100px auto;
}
</style>
</head>
<body>
<fieldset>
<legend>添加学生
<span class="label label-primary">${msg}</span>
</legend>
<form class="form-horizontal" action="/day01/addStu" method="post">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">学生姓名</label>
<div class="col-sm-10">
<input name="name" type="text" class="form-control" id="inputEmail3" placeholder="请输入学生姓名">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">学生年龄</label>
<div class="col-sm-10">
<input name="age" type="text" class="form-control" id="inputPassword3" placeholder="请输入学生年龄">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">学生住址</label>
<div class="col-sm-10">
<select name="address" id="">
<option>北京</option>
<option>上海</option>
<option>郑州</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default btn-success">添加</button>
<a href="/day01/stu" class="btn btn-default btn-danger">返回</a>
</div>
</div>
</form>
</fieldset>
</body>
</html>
点击添加按钮就把表单数据提交
<form class="form-horizontal" action="/day01/addStu" method="post">
发送给了"/day01/addStu"
新建addStuServlet类,通过JDBC将接收到的数据存入数据库并返回成功与否的信息
package com.grg;
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.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* @Author Grg
* @Date 2023/8/22 9:58
* @PackageName:com.grg
* @ClassName: addStuServlet
* @Description: 又是码代码的一天
* @Version plus max 宇宙无敌终极版本
*/
@WebServlet("/addStu")
public class addStuServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.接受请求参数
req.setCharacterEncoding("UTF-8");
String name = req.getParameter("name");
String age = req.getParameter("age");
String address = req.getParameter("address");
//2.添加数据到数据库
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql:///jdbctest", "root", "123456");
PreparedStatement ps = conn.prepareStatement("insert into student values (null,?,?,?)");
ps.setObject(1, name);
ps.setObject(2, age);
ps.setObject(3, address);
int i = ps.executeUpdate();
//3.返回 成功/失败
req.setAttribute("msg", i > 0 ? "添加成功" : "添加失败");
req.getRequestDispatcher("addStu.jsp").forward(req,resp);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
3、删除
在student.jsp页面中点击删除按钮
<button class="btn btn-danger" οnclick="delStu(${s.id})">删除</button>
为按钮绑定了一个点击事件,通过JS去修改浏览器的URL地址
<script>
function delStu(a){
if(confirm("确定删除吗")){
window.location.href = "/day01/delStu?id="+ a;
}
}
</script>
这段代码的目的是在浏览器中跳转到/day01/delStu
页面,并传递一个名为id
的查询参数,参数值为变量a
的值。
新建一个DelStuServlet类,通过接收到的id参数,在数据库中删除对应的数据
package com.grg;
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.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
/**
* @Author Grg
* @Date 2023/8/22 10:12
* @PackageName:com.grg
* @ClassName: DelStuServlet
* @Description: 又是码代码的一天
* @Version plus max 宇宙无敌终极版本
*/
@WebServlet("/delStu")
public class DelStuServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.接受参数
String id = req.getParameter("id");
//2.在数据库中删除该数据
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql:///jdbctest?characterEncoding=UTF-8&useSSL=false", "root", "123456");
PreparedStatement ps = conn.prepareStatement("delete from student where id = ?");
ps.setObject(1,id);
int i = ps.executeUpdate();
//3.返回 成功/失败
req.getRequestDispatcher("stu").forward(req,resp);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
4、修改
点击student.jsp中的修改按钮,跳转到 /day01/toUpdate 页面
<a href="/day01/toUpdate?id=${s.id}" class="btn btn-primary">修改</a>
新建ToUpdateServlet类,通过接收到的id现在数据库中查询数据
package com.grg;
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.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Author Grg
* @Date 2023/8/22 10:17
* @PackageName:com.grg
* @ClassName: ToUpdateServlet
* @Description: 又是码代码的一天
* @Version plus max 宇宙无敌终极版本
*/
@WebServlet("/toUpdate")
public class ToUpdateServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.接受参数
String id = req.getParameter("id");
//2.根据id去查询学生
List<Map<String, Object>> data = new ArrayList<>();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql:///jdbctest?characterEncoding=UTF-8&useSSL=false", "root", "123456");
PreparedStatement ps = conn.prepareStatement("select * from student where id = ?");
ps.setObject(1, id);
ResultSet set = ps.executeQuery();
int count = set.getMetaData().getColumnCount();
while (set.next()) {
HashMap<String, Object> map = new HashMap<>();
for (int i = 1; i <= count; i++) {
map.put(set.getMetaData().getColumnLabel(i),
set.getObject(i));
}
data.add(map);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
//3.传数据跳转
if(data.size()>0){
req.setAttribute("student",data.get(0));
}
req.getRequestDispatcher("updateStu.jsp").forward(req,resp);
}
}
将查询到的数据传给updateStu.jsp
<%--
Created by IntelliJ IDEA.
User: asus
Date: 2023/8/22
Time: 10:21
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<style>
fieldset {
width: 500px;
margin: 100px auto;
}
</style>
</head>
<body>
<fieldset>
<legend>修改学生</legend>
<span class="label label-primary">${msg}</span>
<form class="form-horizontal" action="/day01/updateStu" method="post">
<input value="${student.id}" name="id" type="hidden">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">学生姓名</label>
<div class="col-sm-10">
<input value="${student.name}" name="name" type="text" class="form-control" id="inputEmail3"
placeholder="请输入学生姓名">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">学生年龄</label>
<div class="col-sm-10">
<input name="age" value="${student.age}" type="text" class="form-control" id="inputPassword3"
placeholder="请输入学生年龄">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">学生住址</label>
<div class="col-sm-10">
<select name="address">
<option value="北京" id="北京">北京</option>
<option value="上海" id="上海">上海</option>
<option value="郑州" id="郑州">郑州</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default btn-success">修改</button>
<a href="/day01/stu" class="btn btn-default btn-danger">返回</a>
</div>
</div>
</form>
</fieldset>
<script>
document.getElementById(${student.address}).selected = true;
</script>
</body>
</html>
通过表单提交到"/day01/updateStu"
<form class="form-horizontal" action="/day01/updateStu" method="post">
新建UpdateStuServlet类,将接收到的数据修改数据库内的数据
package com.grg;
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.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
/**
* @Author Grg
* @Date 2023/8/22 10:28
* @PackageName:com.grg
* @ClassName: UpdateStuServlet
* @Description: 又是码代码的一天
* @Version plus max 宇宙无敌终极版本
*/
@WebServlet("/updateStu")
public class UpdateStuServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.接受请求参数
req.setCharacterEncoding("UTF-8");
String id = req.getParameter("id");
String name = req.getParameter("name");
String age = req.getParameter("age");
String address = req.getParameter("address");
//2.在数据库中更改
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql:///jdbctest", "root", "123456");
PreparedStatement ps = conn.prepareStatement("update student set name=?,age=?,address=? where id = ?");
ps.setObject(1,name);
ps.setObject(2,age);
ps.setObject(3,address);
ps.setObject(4,id);
int i = ps.executeUpdate();
//3.返回 成功/失败
req.setAttribute("msg", i>0 ? "修改成功":"修改失败");
req.getRequestDispatcher("updateStu.jsp").forward(req,resp);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
5.pom文件
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.grg</groupId>
<artifactId>StudentCURD</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>StudentCURD Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
<build>
<finalName>StudentCURD</finalName>
</build>
</project>