【Web】基于Servlet、Tomcat、HTTP协议、html、js、css实现的表白墙(数据可持久化保存至硬盘中)
网页实现效果如下
Tomcat配置
项目文件目录
MessageServlet
import com.fasterxml.jackson.databind.ObjectMapper; import javax.servlet.ServletConfig; 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.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; class Message{ public String from; public String to; public String message; } @WebServlet("/message") public class MessageServlet extends HttpServlet { private ObjectMapper objectMapper = new ObjectMapper(); //private List<Message> messageList = new ArrayList<Message>(); // 这个是保存文件的路径 private String filePath = "D:/Git/java/messagewall/messages.txt"; //这个方法用来处理从服务器获取到消息数据 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("application/json;charset=utf-8"); List<Message> messageList = load(); objectMapper.writeValue(resp.getWriter(), messageList); } private List<Message> load() { // 这个方法负责读文件, 把读到的数据获取到之后, 放到 List<Message> 中 List<Message> messageList = new ArrayList<>(); System.out.println("从文件加载!"); // 此处我们需要按行读取. FileReader 本身不支持. 需要套上一层 BufferedReader // 当然这里使用 Scanner 也行 try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) { while (true) { String line = bufferedReader.readLine(); if (line == null) { break; } // 如果读取到 line 的内容, 就把 line 解析成一个 Message 对象 String[] tokens = line.split("\t"); Message message = new Message(); message.from = tokens[0]; message.to = tokens[1]; message.message = tokens[2]; messageList.add(message); } } catch (IOException e) { e.printStackTrace(); } System.out.println("从数据库读取数据!"); return messageList; } // 这个方法用来处理, 从客户端提交数据给服务器 @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Message message = objectMapper.readValue(req.getInputStream(), Message.class); // 在这里, 要进行一个 "写文件" 操作 save(message); resp.setContentType("application/json;charset=utf-8"); resp.getWriter().write("{\"ok\": 1}"); } private void save(Message message) { System.out.println("向文件中写入数据!"); // FileWriter 的使用方法, 就和咱们前面介绍过的 PrintWriter 差不多. 里面都是有一个关键的方法叫做 write try (FileWriter fileWriter = new FileWriter(filePath, true)) { // 写入文件的格式也有很多方式. 可以直接写 json, 也可以使用行文本(每个记录占一行, 字段之间使用分隔符区分) fileWriter.write(message.from + "\t" + message.to + "\t" + message.message + "\n"); } catch (IOException e) { e.printStackTrace(); } System.out.println("向数据库中写入数据!"); } }
web.xml
<!DOCTYPE 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 Application</display-name> </web-app>
表白墙.html
<!DOCTYPE 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>Document</title> </head> <body> <div class="container"> <h1>表白墙</h1> <p>输入后点击提交, 会将信息显示在表格中</p> <div class="row"> <span>谁: </span> <input class="edit" type="text"> </div> <div class="row"> <span>对谁: </span> <input class="edit" type="text"> </div> <div class="row"> <span>说什么: </span> <input class="edit" type="text"> </div> <div class="row"> <input type="button" value="提交" class="submit"> </div> </div> <style> * { margin: 0; padding: 0; } .container { width: 400px; margin: 0 auto; } h1 { text-align: center; padding: 20px 0; } p { color: #666; text-align: center; font-size: 14px; padding: 10px 0; } .row { height: 40px; display: flex; justify-content: center; align-items: center; } span { width: 100px; line-height: 40px; } .edit { width: 200px; height: 30px; } .submit { width: 304px; height: 40px; color: white; background-color: orange; border: none; } </style> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> //1.在页面加载的时候访问服务器,从服务器这边获取到消息列表并展示出来 function load(){ $.ajax({ type: 'GET', url: 'message', success: function(data,status){ //data是响应的body,此时的响应可能只是一个字符串格式,可以手动的进行一个解析,按照json格式解析成对象 let container = document.querySelector('.container'); //let message = JSON.parse(data);//data已经是数组类型,不用再解析(将string转成array或者object)了 let messages = data; for(let message of messages){ let row = document.createElement('div'); row.className = 'row'; row.innerHTML = message.from + '对' + message.to + '说:' + message.message; container.appendChild(row); } } }); } load(); //2.点击提交按钮的时候把当前的数据构造一个HTTP请求发送给服务器 // 给点击按钮注册点击事件 var submit = document.querySelector('.submit'); submit.onclick = function () { // 1. 获取到编辑框内容 var edits = document.querySelectorAll('.edit'); var from = edits[0].value; var to = edits[1].value; var message = edits[2].value; console.log(from + "," + to + "," + message); if (from == '' || to == '' || message == '') { return; } // 2. 构造 html 元素 var row = document.createElement('div'); row.className = 'row'; row.innerHTML = from + '对' + to + '说: ' + message; // 3. 把构造好的元素添加进去 var container = document.querySelector('.container'); container.appendChild(row); // 4. 同时清理之前输入框的内容 for (var i = 0; i < 3; i++) { edits[i].value = ''; } //5.构造一个http请求,把消息发给服务器端保存 $.ajax({ type: "POST", url: "message", data: JSON.stringify({from: from,to: to,message: message}), contentType: "application/json: charset=utf-8", success: function(data, status){ if(data.ok ==1){ console.log('提交信息成功!'); }else{ console.log('提交信息失败!'); } } }) } </script> </body> </html>
pom.xml
引入所需依赖
<?xml version="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.0</modelVersion> <groupId>org.example</groupId> <artifactId>messagewall</artifactId> <version>1.0-SNAPSHOT</version> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>7</source> <target>7</target> </configuration> </plugin> </plugins> </build> <dependencies> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.1</version> </dependency> </dependencies> </project>