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" %>
Title
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
编号
姓名
年龄
住址
操作
${s.id}
${s.name}
${s.age}
${s.address}
修改
在student.jsp中有添加学生的按钮
通过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" %>
Title
点击添加按钮就把表单数据提交
发送给了"/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);
}
}
}
在student.jsp页面中点击删除按钮
为按钮绑定了一个点击事件,通过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);
}
}
}
点击student.jsp中的修改按钮,跳转到 /day01/toUpdate 页面
修改
新建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" %>
Title
通过表单提交到"/day01/updateStu"
新建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);
}
}
}
<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>