在前端页面输入的数据,经过后台处理返回给前端显示
<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.12.6.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.45version>
dependency>
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 Applicationdisplay-name>
web-app>
1.告诉服务器,当前留言是一条什么样的数据
2.从服务器获取到,当前留言的数据
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created with IntelliJ IDEA.
* Description:
* User: 17673
* Date: 2022-07-14
* Time: 12:32
*/
public class DButil {
private static final String URL = "jdbc:mysql://127.0.0.1:3306/confession?characterEncoding=utf8&useSSL=false";
private static final String USERNAME = "root";
private static final String PASSWORD = "1234";
private static DataSource dataSource = null;
private static DataSource getDataSource(){
if(dataSource == null){
synchronized (DButil.class){
if(dataSource == null){
dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setURL(URL);
((MysqlDataSource)dataSource).setUser(USERNAME);
((MysqlDataSource)dataSource).setPassword(PASSWORD);
}
}
}
return dataSource;
}
public static Connection getConnection() throws SQLException {
return getDataSource().getConnection();
}
public static void clone(Connection connection, PreparedStatement statement, ResultSet resultSet){
try{
if(resultSet != null){
resultSet.close();
}
if(statement != null){
statement.close();
}
if(connection != null){
connection.close();
}
}catch (SQLException e){
e.printStackTrace();
}
}
}
创建数据库
create database confession;
use confession;
create table confession1(
`from` varchar(1024),
`to` varchar(1024),
`message` varchar(1024)
);
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>表白墙title>
head>
<body>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
width: 100%;
}
h3 {
text-align: center;
padding: 30px 0;
font-size: 24px;
}
p {
text-align: center;
color: #999;
padding: 10px 0;
}
.row {
width: 400px;
height: 50px;
margin: 0 auto;
display: flex;
justify-content: center;
align-items: center;
}
.row span {
width: 60px;
font-size: 20px;
}
.row input {
width: 300px;
height: 40px;
line-height: 40px;
font-size: 20px;
text-indent: 0.5em;
/* 去掉输入框的轮廓线 */
outline: none;
}
.row #submit {
width: 300px;
height: 40px;
font-size: 20px;
line-height: 40px;
margin: 0 auto;
color: white;
background-color: orange;
/* 去掉边框 */
border: none;
border-radius: 10px;
}
.row #submit:active {
background-color: gray;
}
style>
<div class="container">
<h3>表白墙h3>
<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.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js">script>
<script>
function getMessage(){
$.ajax({
type:"get",
url:"message",
success: function(body){
let div = document.createElement('div');
for(let message of body){
div.innerHTML = from + ' 对 ' + to + ' 说: ' + msg;
div.className = 'row';
let container = document.querySelector('.container');
container.appendChild(div);
}
},
error:function(){
console.log("失败");
}
});
}
getMessage();
// 当用户点击 submit, 就会获取到 input 中的内容, 从而把内容构造成一个 div, 插入到页面末尾.
let submitBtn = document.querySelector('#submit');
submitBtn.onclick = function() {
// 1. 获取到 3 个 input 中的内容.
let inputs = document.querySelectorAll('input');
let from = inputs[0].value;
let to = inputs[1].value;
let msg = inputs[2].value;
if (from == '' || to == '' || msg == '') {
// 用户还没填写完, 暂时先不提交数据.
return;
}
// 2. 生成一个新的 div, 内容就是 input 里的内容. 把这个新的 div 加到页面中.
let div = document.createElement('div');
div.innerHTML = from + ' 对 ' + to + ' 说: ' + msg;
div.className = 'row';
let container = document.querySelector('.container');
container.appendChild(div);
// 3. 清空之前输入框的内容.
for (let i = 0; i < inputs.length; i++) {
inputs[i].value = '';
}
//4. 把当前获取到的输入框的内容,构造成一个 HTTP POST请求,通过ajax 发给服务器
let body = {
from : from,
to : to,
message : msg
};
$.ajax({
type:"post",
url:"message",
contentType: "application/json",
data:JSON.stringify(body),
success: function(body) {
alert("消息提交成功");
},
error:function(){
alert("消息提交失败")
}
});
}
script>
body>
html>
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取到消息列表
List<Message> messages = load();
String jsonString = objectMapper.writeValueAsString(messages);
System.out.println("jsonString:" + jsonString);
resp.setContentType("application/json; charset=utf8");
resp.getWriter().write(jsonString);
}
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=utf8");
resp.getWriter().write("{\"ok\":true}");
}
private void save(Message message) {
Connection connection = null;
PreparedStatement statement = null;
try {
//1.和数据库建立连接
connection = DButil.getConnection();
//2.构造sql
String sql = "insert into confession1 value(?,?,?)";
statement = connection.prepareStatement(sql);
statement.setString(1,message.from);
statement.setString(2,message.to);
statement.setString(3,message.message);
//3.执行sql
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
DButil.clone(connection, statement, null);
}
}
private List<Message> load(){
//从数据中获取到所得信息
List<Message> list = new ArrayList<>();
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = DButil.getConnection();
String sql = "select * from confession1";
statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery();
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);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DButil.clone(connection,statement,resultSet);
}
return list;
}
项目由三个部分组成,前端页面,后台程序,数据库,可以通过fiddler来抓包判断是前台,还是后台的问题,判读前端请求是否正常,也可以看后台的响应是否和预定的一致,前端和后端数据和数据处理没问题,前端界面没有显示值,就要去查看数据库插入和查询是否正常,这里数据只涉及到插入和查询.学会善用工具.