10.3使用Servlet写一个表白墙网站

一.创建项目,引入依赖和前端页面.

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客户端创建数据库和表.

二.代码

10.3使用Servlet写一个表白墙网站_第1张图片

10.3使用Servlet写一个表白墙网站_第2张图片 

1.pom.xml:



    4.0.0

    org.example
    hello_servlet2023-9-18
    1.0-SNAPSHOT

    
        8
        8
    
    
        
        
            javax.servlet
            javax.servlet-api
            3.1.0
            provided
        
        
        
            com.fasterxml.jackson.core
            jackson-databind
            2.14.2
        
        
        
            mysql
            mysql-connector-java
            5.1.49
        

    
    war
    
        messageWall
    

2.web.xml:




    Archetype Created Web Application

 3.messageWall.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)找错.

你可能感兴趣的:(tomcat,servlet,java,java-ee,maven)