前期的准备工作和系统资源配置已经在上一篇博客讲到
https://blog.csdn.net/saha__/article/details/124739358?spm=1001.2014.3001.5501
1、本机内存项目实例(关闭程序数据丢失)
1.1创建文件,并从中央仓库导入相应的依赖包
依赖包:
1、servlet 3.1依赖包
2、jackson 2.13
项目文件
在main创建java包
在Java包里创建两个java文件
命名为MessageListServlet(拿到前端的参数写入内存)后端代码
AddMessageServlet(把内存中的数据反馈给前端)后端
在webapp文件目录底下创建meessage.html文件(前端代码)
还有两个普通的公共类
DBUtils(使用于jdbc编程)
StringUtils(判空)
运行时会使用到Tomcat运行
使用fiddlre进行抓包
也可以使用Postman模拟发送请求
接下来就是写代码 了,涉及到很多知识,就不一一介绍了,有数据库,jdbs编程、js、java、html
代码
MessageListServlet(拿到前端的参数写入内存)后端代码
import utils.StringUtils;
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.IOException;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/message/add")
public class AddMessageServlet extends HttpServlet {
public static List<Message> msgList = new ArrayList<>();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int result = -1;
//得到前端参数并效验
//1.getParameter获取通过http协议提交过来的数据.
String from = req.getParameter("from");
String to = req.getParameter("to");
String msg = req.getParameter("msg");
/**
* 非空效验使用StringUtils类里写 方法hasLength非空返回true
*/
if(StringUtils.hasLength(from) && StringUtils.hasLength(to) &&
StringUtils.hasLength(msg)){
//将表白对象加入到集合里面
AddMessageServlet.msgList.add(new Message(from,to,msg ));
result = 1 ;
}
//将结果返回给前端setContentType方法用于设置发送到客户端的响应的内容类型
resp.setContentType("text/html; charset = utf-8");
resp.getWriter().println(result);
}
}
/**
* 内存集合类
*/
class Message{
private String from;
private String to;
private String msg;
public Message(String from , String to , String msg){
this.from = from ;
this.to = to;
this.msg = msg ;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
}
AddMessageServlet(把内存中的数据反馈给前端)后端
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import lombok.SneakyThrows;
import utils.DBUtils;
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.IOException;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/message/list")
public class MessageListServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<Message> messagelist = AddMessageServlet.msgList;
//将结果返回给前端setContentType方法用于设置发送到客户端的响应的内容类型
resp.setContentType("application/json; charset = utf-8");
ObjectMapper objectMapper = new ObjectMapper();
resp.getWriter().println(objectMapper.writeValueAsString(messagelist));
}
}
在webapp文件目录底下创建meessage.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>表白墙</title>
<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;
}
.submit:active {
background-color: #666;
}
</style>
<script src="js/jquery-1.9.1.min.js"></script>
</head>
<body>
<div id="container" class="container">
<h1>表白墙</h1>
<p>输入后点击提交, 会将信息显示在表格中</p>
<div class="row">
<span>谁: </span>
<input id="from" class="edit" type="text">
</div>
<div class="row">
<span>对谁: </span>
<input id="to" class="edit" type="text">
</div>
<div class="row">
<span>说什么: </span>
<input id="message" class="edit" type="text">
</div>
<div class="row">
<input type="button" value="提交" class="submit" onclick="mySubmit()">
</div>
<div id="allMsg">
<!-- <div class="row">
小猫对小狗说: 喵
</div>
<div class="row">
小黑对小白说: 拜拜。
</div> -->
</div>
</div>
<script>
//添加表白信息
function mySubmit(){
var from = jQuery("#from");
var to = jQuery("#to");
var msg = jQuery("#message");
//todo非空效验
//ajax提交数据给后端
jQuery.ajax({
url:"message/add",//提交到后端的地址
type:"POST",//提交类型
data:{from:from.val(),
to:to.val(),
msg:msg.val()},//参数在前端会使用req.getParameter("from");读取数据
success:function(result){//后端返回给前端的数据
if(result != null && result > 0){
alert("恭喜添加成功!");
//刷新表白列表
gerAllMsg();
}else{
alert("抱歉,添加失败,请重试");
}
}
});
}
//查询所有表白信息
function gerAllMsg(){
jQuery.ajax({
url:"message/list",
type:"GET",
data:{},
success:function(result){
if(result != null && result.length>0){
//没有表白数据
var msgHtml = "";
for(var i=0;i<result.length;i++){
msgHtml +='<div class="row>'+
result[i].from +
'对'+result[i].to +
'说' + result[i].msg+'</div>';
}
jQuery("#allMsg").html(msgHtml);
}else if(result != null && result.length==0){
//没有表白数据
console.log("没有表白信息");
}else{
alert("访问出错! ");
}
}
});
}
gerAllMsg();//执行方法
</script>
</body>
</html>
公共类DBUtils
package utils;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.SQLError;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBUtils {
private DBUtils(){
}
private static volatile MysqlDataSource mysqlDataSource;
private static volatile Connection connection;
private static MysqlDataSource getMysqlDataSource(){
if(mysqlDataSource == null){
synchronized (DBUtils.class){
if(mysqlDataSource == null){
mysqlDataSource = new MysqlDataSource();
mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/MessageWall?character=utf8&useSSL=true");
mysqlDataSource.setUser("root");
mysqlDataSource.setPassword("12345678");
}
}
}
return mysqlDataSource;
}
public static Connection getConnection() {
if (connection == null) { // 首次访问
synchronized (DBUtils.class) {
if (connection == null) {
try {
MysqlDataSource dataSource = getMysqlDataSource();
connection = (Connection) dataSource.getConnection();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
return connection;
}
//关闭资源的方法
public static void close(ResultSet resultSet, PreparedStatement statement, Connection connection) throws SQLException{
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
}
}
公共类StringUtils
package utils;
public class StringUtils {
/**
* 用来判空
* 如果为null返回true
* @param str
* @return
*/
public static boolean hasLength(String str){
return !(str == null || str.length() == 0);
}
}
2、存储到数据库项目(关闭计算机数据不会丢失)
和前面的项目类似,只是需要连接数据库
创建数据库,在java包下创建
AddMessageServletV2(拿到前端的参数添加到数据库)后端代码
MessageListServletV2把数据库中的数据反馈给前端)后端
在webapp底下创建meessage-wallV2.html文件(前端代码)
创建数据库
set character_set_database=utf8;
set character_set_server=utf8;
create database if not exists MessageWall;
use MessageWall;
drop table if exists messages;
create table messages (`from` varchar(255), `to` varchar(255), `message`
varchar(2048));
AddMessageServletV2(拿到前端的参数添加到数据库)后端代码
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import lombok.SneakyThrows;
import utils.DBUtils;
import utils.StringUtils;
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.IOException;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/message/add2")
public class AddMessageServletV2 extends HttpServlet {
@SneakyThrows
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int result = -1;
//得到前端参数并效验
//1.getParameter获取通过http协议提交过来的数据.
String from = req.getParameter("from");
String to = req.getParameter("to");
String msg = req.getParameter("msg");
/**
* 非空效验使用StringUtils类里写 方法hasLength非空返回true
*/
if(StringUtils.hasLength(from) && StringUtils.hasLength(to) &&
StringUtils.hasLength(msg)){
//将表白对象加入到集合里面
//2.1得到Connection
Connection connection = DBUtils.getConnection();
String sql = "insert into messages(`from`,`to`,`message`) values(?,?,?)";
PreparedStatement statement = (PreparedStatement) connection.prepareStatement(sql);
statement.setString(1,from);
statement.setString(2,to);
statement.setString(3,msg);
//执行执行器,并返回结果
result = statement.executeUpdate();
//关闭资源
DBUtils.close(null, statement, connection);
}
//将结果返回给前端setContentType方法用于设置发送到客户端的响应的内容类型
resp.setContentType("text/html; charset = utf-8");
resp.getWriter().println(result);
}
}
MessageListServletV2把数据库中的数据反馈给前端)后端
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.sun.corba.se.impl.oa.poa.ActiveObjectMap;
import lombok.SneakyThrows;
import utils.DBUtils;
import utils.StringUtils;
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.IOException;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/message/list2")
public class MessageListServletV2 extends HttpServlet {
@SneakyThrows
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//查询数据据库中的表白列表
List<Message> list = new ArrayList<>();
//1.得到Connection
Connection connection = DBUtils.getConnection();
//拼接sql,得到执行器
String sql = "select * from messages";
PreparedStatement statement = (PreparedStatement) connection.prepareStatement(sql);
//执行sql,返回resultset 并循环将数据添加到list中
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()){
String from = resultSet.getString("from");
String to = resultSet.getString("to");
String msg = resultSet.getString("message");
list.add(new Message(from,to,msg));
}
//关闭资源
DBUtils.close(resultSet,statement,connection);
//将结果返回给前端setContentType方法用于设置发送到客户端的响应的内容类型
resp.setContentType("application/json; charset = utf-8");
ObjectMapper objectMapper = new ObjectMapper();
resp.getWriter().println(objectMapper.writeValueAsString(list));
}
}
在webapp底下创建meessage-wallV2.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>表白墙——连接数据库版本</title>
<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;
}
.submit:active {
background-color: #666;
}
</style>
<script src="js/jquery-1.9.1.min.js"></script>
</head>
<body>
<div id="container" class="container">
<h1>表白墙</h1>
<p>输入后点击提交, 会将信息显示在表格中</p>
<div class="row">
<span>谁: </span>
<input id="from" class="edit" type="text">
</div>
<div class="row">
<span>对谁: </span>
<input id="to" class="edit" type="text">
</div>
<div class="row">
<span>说什么: </span>
<input id="message" class="edit" type="text">
</div>
<div class="row">
<input type="button" value="提交" class="submit" onclick="mySubmit()">
</div>
<div id="allMsg">
<!-- <div class="row">
小猫对小狗说: 喵
</div>
<div class="row">
小黑对小白说: 拜拜。
</div> -->
</div>
</div>
<script>
// 添加表白信息
function mySubmit(){
var from = jQuery("#from");
var to = jQuery("#to");
var msg = jQuery("#message");
// todo:1.非空效验
// 2.ajax 提交数据给后端
jQuery.ajax({
url:"message/add2", // 提交到后端的地址
type:"POST", // 提交类型
data:{
from:from.val(),
to:to.val(),
msg:msg.val()
}, // 参数
success:function(result){ // 后端返回给前端的数据
if(result!=null && result>0){
alert("恭喜:添加成功!");
// 刷新表白列表
getAllMsg();
}else{
alert("抱歉:添加失败,请重试!");
}
}
});
}
// 查询所有的表白信息
function getAllMsg(){
jQuery.ajax({
url:"message/list2",
type:"GET",
data:{},
success:function(result){
if(result!=null && result.length>0){
// 表示有表白数据
var msgHtml = "";
for(var i=0;i<result.length;i++){
msgHtml +='<div class="row">'+
result[i].from +'对'+
result[i].to+'说: '+
result[i].msg+'</div>';
}
jQuery("#allMsg").html(msgHtml);
}else if(result!=null && result.length==0){
// 没有表白数据
console.log("没有表白信息");
}else{
alert("访问出错!");
}
}
});
}
getAllMsg(); // 执行方法
</script>
</body>
</html>
点击配置好的Tomcat运行在浏览器中输入相应的地址即可访问
IDEA生成localhost:8080/maven-servlet/
加上HTML文件的名字meessage-wallV2.html即可访问
http://localhost:8080/maven-servlet/meessage-wallV2.html