提示:以下是本篇文章正文内容,Java系列学习将会持续更新
程序的流程
- 我们通过访问
127.0.0.1:8080/record.html
来发送GET请求,访问到记录
的页面 - 填写页面中的表单并提交,向
/save
发起 POST 请求 - Servlet 作出响应后重定向到
/list.html
页面,请求方法为 GET list.html 动态资源
通过HTML拼接,显示数据库中的数据
main
java
DBUtil
public class DBUtil {
private static DataSource dataSource;
static {
MysqlDataSource mysqlDataSource = new MysqlDataSource();
mysqlDataSource.setUrl("jdbc:mysql://127.0.0.1:3306/grades?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai");
mysqlDataSource.setUser("root");
mysqlDataSource.setPassword("123456");
dataSource = mysqlDataSource;
}
public static Connection connection() throws SQLException {
return dataSource.getConnection();
}
}
ListServlet
请求方法为 GET,通过拼接HTML来显示数据。
@WebServlet("/list.html")
public class ListServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
List<Student> list = new ArrayList<>();
try (Connection c = DBUtil.connection()) {
String sql = "select name, grade from grades order by id";
try (PreparedStatement ps = c.prepareStatement(sql)) {
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
Student student = new Student();
student.name = rs.getString("name");
student.grade = rs.getInt("grade");
list.add(student);
}
}
}
} catch (SQLException exc) {
throw new RuntimeException(exc);
}
// 拼接 HTML
writer.println("<!DOCTYPE html>");
writer.println("<html lang='zh-hans'>");
writer.println("<head>");
writer.println(" <meta charset='utf-8'>");
writer.println(" <title>成绩单</title>");
writer.println("</head>");
writer.println("<body>");
writer.println(" <table border='1'>");
writer.println(" <tbody>");
for (Student student : list) {
writer.println("<tr>");
writer.printf("<td>%s</td>\n<td>%d</td>\n", student.name, student.grade);
writer.println("</tr>");
}
writer.println(" </tbody>");
writer.println(" </table>");
writer.println("</body>");
writer.println("</html>");
}
}
SaveServlet
读取 form 表单发来的POST请求,响应:将数据存入数据库、重定向到 /list.html
@WebServlet("/save")
public class SaveServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1. 读取
req.setCharacterEncoding("utf-8");
String name = req.getParameter("name");
String grade = req.getParameter("grade");
if (name == null || name.trim().isEmpty()) {
System.out.println("必须填写姓名");
return;
}
if (grade == null || grade.trim().isEmpty()) {
System.out.println("必须填写成绩");
return;
}
int g;
try {
g = Integer.parseInt(grade);
} catch (NumberFormatException exc) {
System.out.println("成绩必须是数字");
return;
}
// 2. 保存 (必须保证数据是同一份数据)
String sql = "insert into grades (name, grade) values (?, ?)";
try (Connection c = DBUtil.connection()) {
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, name);
ps.setInt(2, g);
ps.executeUpdate();
}
} catch (SQLException exc) {
throw new RuntimeException(exc);
}
// 3. 重定向
resp.sendRedirect("/list.html");
}
}
Student
public class Student {
public String name;
public int grade;
}
webapp
WEB-INF
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1"
metadata-complete="false">
</web-app>
record.html
通过GET请求访问HTML页面。其中的form表单发送 POST 请求,请求地址为 /save
<!DOCTYPE html>
<html lang="zh-hans">
<head>
<meta charset="UTF-8">
<title>成绩录入</title>
</head>
<body>
<form method="post" action="/save">
<input type="text" name="name">
<input type="text" name="grade">
<button>提交</button>
</form>
</body>
</html>
运行效果
-
提交前
-
提交后
总结:
提示:这里对文章进行总结:
以上就是今天的学习内容,本文是JavaWeb的学习,写一个成绩录入的小程序,为了是对Servlet动态绑定学习的综合应用。之后的学习内容将持续更新!!!