一.创建项目,引入依赖和前端页面.
1.注意,静态页面放在webapp目录下,不是WEB-INF,
2.存档约定:前端使用post(/messageWall/message)发送http请求,使用json格式把数据传输到后端.服务器返回HTTP/1.1 200 ok.
3.读档约定:使用get(/messageWall/message),服务器返回HTTP/1.1 200 ok,和json数组.
4.使用maven管理数据库资源包.
5.在mysql客户端创建数据库和表.
二.代码
1.pom.xml:
- "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.0modelVersion>
-
- <groupId>org.examplegroupId>
- <artifactId>hello_servlet2023-9-18artifactId>
- <version>1.0-SNAPSHOTversion>
-
- <properties>
- <maven.compiler.source>8maven.compiler.source>
- <maven.compiler.target>8maven.compiler.target>
- properties>
- <dependencies>
-
- <dependency>
- <groupId>javax.servletgroupId>
- <artifactId>javax.servlet-apiartifactId>
- <version>3.1.0version>
- <scope>providedscope>
- dependency>
-
- <dependency>
- <groupId>com.fasterxml.jackson.coregroupId>
- <artifactId>jackson-databindartifactId>
- <version>2.14.2version>
- dependency>
-
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- <version>5.1.49version>
- dependency>
-
- dependencies>
- <packaging>warpackaging>
- <build>
- <finalName>messageWallfinalName>
- build>
- project>
2.web.xml:
- web-app PUBLIC
- "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
- "http://java.sun.com/dtd/web-app_2_3.dtd" >
-
- <web-app>
- <display-name>Archetype Created Web Applicationdisplay-name>
- web-app>
3.messageWall.html:
- html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>表白墙title>
- <style>
- /* * 通配符选择器, 是选中页面所有元素 */
- * {
- /* 消除浏览器的默认样式. */
- margin: 0;
- padding: 0;
- box-sizing: border-box;
- }
-
- .container {
- width: 600px;
- margin: 20px auto;
- }
-
- h1 {
- text-align: center;
- }
-
- p {
- text-align: center;
- color: #666;
- margin: 20px 0;
- }
-
- .row {
- /* 开启弹性布局 */
- display: flex;
- height: 40px;
- /* 水平方向居中 */
- justify-content: center;
- /* 垂直方向居中 */
- align-items: center;
- }
-
- .row span {
- width: 80px;
- }
-
- .row input {
- width: 200px;
- height: 30px;
- }
-
- .row button {
- width: 280px;
- height: 30px;
- color: white;
- background-color: orange;
- /* 去掉边框 */
- border: none;
- border-radius: 5px;
- }
-
- /* 点击的时候有个反馈 */
- .row button:active {
- background-color: grey;
- }
- style>
- head>
- <body>
- <div class="container">
- <h1>表白墙h1>
- <p>输入内容后点击提交, 信息会显示到下方表格中p>
- <div class="row">
- <span>谁: span>
- <input type="text">
- div>
- <div class="row">
- <span>对谁: span>
- <input type="text">
- div>
- <div class="row">
- <span>说: span>
- <input type="text">
- div>
- <div class="row">
- <button id="submit">提交button>
- div>
-
- div>
-
- <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">script>
-
- <script>
- // 实现提交操作. 点击提交按钮, 就能够把用户输入的内容提交到页面上显示.
- // 点击的时候, 获取到三个输入框中的文本内容
- // 创建一个新的 div.row 把内容构造到这个 div 中即可.
- let containerDiv = document.querySelector('.container');
- let inputs = document.querySelectorAll('input');
- let button = document.querySelector('#submit');
- button.onclick = function() {
- // 1. 获取到三个输入框的内容
- let from = inputs[0].value;
- let to = inputs[1].value;
- let msg = inputs[2].value;
- if (from == '' || to == '' || msg == '') {
- return;
- }
- // 2. 构造新 div
- let rowDiv = document.createElement('div');
- rowDiv.className = 'row message';
- rowDiv.innerHTML = from + ' 对 ' + to + ' 说: ' + msg;
- containerDiv.appendChild(rowDiv);
- // 3. 清空之前的输入框内容
- for (let input of inputs) {
- input.value = '';
- }
-
- // 4. 把用户输入的数据, 构造出 HTTP 请求, 发送给服务器.
- let body = {
- from: from,
- to: to,
- message: msg
- };
- $.ajax({
- type: 'post',
- // url: '/messageWall/message',
- url: 'message',
- contentType: 'application/json; charset=utf8',
- data: JSON.stringify(body),
- success: function(body) {
- // 预期 body 中返回 ok
- console.log(body);
- }
- });
- }
-
- // 在页面加载的时候, 发起一个 GET 请求给服务器, 从服务器拿到提交过的数据.
- $.ajax({
- type: 'get',
- url: 'message',
- success: function(body) {
- // 但是由于 jquery 见到响应中的 application/json , 就会自动的把响应
- // 转换成 js 对象数组. body 其实是 js 对象数组, 而不是 json 字符串了.
- // 就可以直接按照数组的方式来操作 body, 每个元素都是 js 对象
-
- // 1. 遍历数组, 取出每个 js 对象.
- // 2. 根据这里的 js 对象构造出 页面元素, 显示到页面上
- let container = document.querySelector('.container');
- for (let i = 0; i < body.length; i++) {
- let message = body[i];
- // 此处 message 对象, 就形如
- // {
- // from: '黑猫',
- // to: '白猫',
- // message: '喵'
- // }
- // 构造出 html 元素!!
- // 使用浏览器提供的 api (dom api) 创建 div 标签.
- let div = document.createElement('div');
- // 设置一个 CSS 的类. 应用到 CSS 样式了.
- div.className = 'row';
- // 给 div 标签里设置内容, 此处显示一行文本.
- div.innerHTML = message.from + " 对 " + message.to + " 说: " + message.message;
- container.appendChild(div);
- }
- }
- });
-
- script>
- body>
- html>
4.MessageServlet.java:
- import com.fasterxml.jackson.databind.ObjectMapper;
- import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
-
- 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.sql.DataSource;
- import java.io.IOException;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.List;
-
- class Message {
- // 这里的变量名要和前端js的变量名完全匹配
- public String from;
- public String to;
- public String message;
-
- @Override
- public String toString() {
- return "Message{" +
- "from='" + from + '\'' +
- ", to='" + to + '\'' +
- ", message='" + message + '\'' +
- '}';
- }
- }
-
- @WebServlet("/message")
- public class MessageServlet extends HttpServlet {
- private ObjectMapper objectMapper = new ObjectMapper();
- // private List
list = new ArrayList<>(); -
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- // 存档
- // 读取body中的json格式,转化成Java格式,存入链表
- Message message = objectMapper.readValue(req.getInputStream(), Message.class);
- try {
- save(message);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- System.out.println("收到请求" + message);
- resp.setStatus(200);
- resp.getWriter().write("ok");
- }
-
- // 使用jdbc,往数据库中插入数据
- private void save(Message message) throws SQLException {
- DataSource dataSource = new MysqlDataSource();
- ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/messageWall?characterEncoding=utf8&useSSL=false");
- ((MysqlDataSource)dataSource).setUser("root");
- ((MysqlDataSource)dataSource).setPassword("123456");
-
- Connection connection = dataSource.getConnection();
- String sql = "insert into message values(?, ?, ?)";
- PreparedStatement statement = connection.prepareStatement(sql);
- statement.setString(1, message.from);
- statement.setString(2, message.to);
- statement.setString(3, message.message);
- statement.executeUpdate();
-
- statement.close();
- connection.close();
- }
-
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- // 读档
- resp.setContentType("application/json; charset=utf8");
- String respJson = null;
- try {
- respJson = objectMapper.writeValueAsString(load());
- } catch (SQLException e) {
- e.printStackTrace();
- }
- resp.getWriter().write(respJson);
- }
-
- private List
load() throws SQLException { - DataSource dataSource = new MysqlDataSource();
- ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/messageWall?characterEncoding=utf8&useSSL=false");
- ((MysqlDataSource) dataSource).setUser("root");
- ((MysqlDataSource) dataSource).setPassword("123456");
-
- Connection connection = dataSource.getConnection();
- String sql = "select * from message";
- PreparedStatement statement = connection.prepareStatement(sql);
- ResultSet resultSet = statement.executeQuery();
- List
list = new ArrayList<>(); - while (resultSet.next()) {
- Message message = new Message();
- message.from = resultSet.getString("from");
- message.to = resultSet.getString("to");
- message.message = resultSet.getString("message");
- list.add(message);
- }
- resultSet.close();
- statement.close();
- connection.close();
- return list;
- }
- }
三.出错处理
1.首先使用Fiddler抓包,判断是前端问题还是后端问题.
2.如果是前端问题,去浏览器的开发者工具(F12)找错.