520到了,教你做个JavaWeb表白墙小项目
Posted 澄白易
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了520到了,教你做个JavaWeb表白墙小项目相关的知识,希望对你有一定的参考价值。
目录
1.配置 Maven 项目
1.1 创建 Maven 项目
之后就是选择存放路径和命名,比较简单,就不做过多赘述啦!
1.2 引入相关依赖
在 pom.xml 中引入引⼊ servlet , jackson ,mysql-connector 和 lombok 依赖:
<?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>message_wall</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>message_wall Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</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.2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<!-- 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>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>message_wall</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
1.3 项目总结构
2. 约定前后端交互接口
所谓 “前后端交互接口” 是进行 Web 开发中的关键环节,具体来说:就是允许页面给服务器发送哪些 HTTP 请求,并且每种请求预期获取什么样的 HTTP 响应。
- 从服务器上获取全部信息
请求:GET
响应:JSON 格式 - 向服务器提交信息
请求:JSON 格式
响应:JSON 格式
3.服务端代码
3.1 创建Message类
@Setter
@Getter
public class Message
private String from;
private String to;
private String message;
public Message(String from, String to, String message)
this.from = from;
this.to = to;
this.message = message;
注意: @Setter 和 @Getter 会自动生成所有的get和set方法。
3.2 创建工具类
创建 DBUtils 类,用于连接数据库。
DBUtil 类主要实现以下功能:
- 创建 MysqlDataSource 实例,设置 URL , username , password 等属性.
- 提供 getConnection 方法,和MySQL服务器建立连接.
- 提供 close 方法,用来释放必要的资源.
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;
// 1.get connect
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;
// 2.提供关闭资源的方法
public static void close(ResultSet resultSet, PreparedStatement statement) throws SQLException
if (resultSet != null)
resultSet.close();
if (statement != null)
statement.close();
创建 StringUtils 类,用于判空:
public class StringUtils
public static boolean hasLength(String str)
return !(str == null || str.length() == 0);
3.3 添加信息类(AddMessage)
用于向服务器提交信息。
@WebServlet("/message/add")
public class AddMessage extends HttpServlet
@SneakyThrows
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
int result = -1;
// 1.得到前端参数并效验
String from = req.getParameter("from");
String to = req.getParameter("to");
String msg = req.getParameter("msg");
if (StringUtils.hasLength(from) && StringUtils.hasLength(to)
&& StringUtils.hasLength(msg))
// 2.将表白对象加入到集合
// 2.1 得到 Connection
Connection connection = DBUtils.getConnection();
// 2.2 拼接 sql,创建执行器
String sql = "insert into messages(`from`,`to`,`message`) values(?,?,?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, from);
statement.setString(2, to);
statement.setString(3, msg);
// 2.3 执行执行器,并返回结果
result = statement.executeUpdate();
// 2.4 关闭资源
DBUtils.close(null, statement);
resp.setContentType("text/html; charset=utf-8");
resp.getWriter().println(result);
3.4 查询信息类(MessageList)
用于获取服务器上所有信息。
@WebServlet("/message/list")
public class MessageList 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();
// 2.拼接SQL,创建执行器
String sql = "select * from messages";
PreparedStatement statement = connection.prepareStatement(sql);
// 3.执行SQL,返回 resultSet 并循环将数据添加到 list 中
ResultSet resultSet = statement.executeQuery();
while (resultSet.next())
String from = resultSet.getString("from");
String to = resultSet.getString("to");
String message = resultSet.getString("message");
list.add(new Message(from, to, message));
// 4.关闭资源
DBUtils.close(resultSet, statement);
resp.setContentType("application/json; charset=utf-8");
ObjectMapper objectMapper = new ObjectMapper();
resp.getWriter().println(objectMapper.writeValueAsString(list));
4. 前端代码
<!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>
body
background-image: url(image/wall.jpeg);
background-repeat: no-repeat;
background-size: cover;
*
margin: 0;
padding: 0;
.container
width: 400px;
margin: 0 auto;
h1
text-align: center;
padding: 20px 0;
color: rgb(11, 213, 248);
p
color: rgb(226, 87, 129);
text-align: center;
font-size: 14px;
padding: 10px 0;
.row
height: 40px;
width: 350px;
display: flex;
justify-content: center;
align-items: center;
.row1
height: 40px;
display: flex;
justify-content: center;
align-items: center;
padding-left: 20px;
span
width: 70px;
line-height: 40px;
.edit
color: rgb(41, 227, 134);
text-align: center;
width: 261px;
height: 30px;
padding-right: 15px;
.submit
width: 280px;
height: 40px;
color: white;
background-color: orange;
border: none;
.submit:active
background-color: #666;
.msg
width: 100%;
height: 25px;
color: rgb(48, 66, 227);
justify-content: center;
align-items: center;
text-align: center;
padding-top: 10px;
</style>
<script src="js/jquery-1.9.1.min.js"></script>
</head>
<body>
<div class="container">
<h1>表白墙</h1>
<p> 给他/她留下一句话吧!</p>
<div class="row">
<span style="color: rgb(236, 10, 244)">谁: </span>
<input id="from" class="edit" type="text">
</div>
<div class="row">
<span style="color: rgb(236, 10, 244)">对谁: </span>
<input id="to" class="edit" type="text">
</div>
<div class="row">
<span style="color: rgb(236, 10, 244)">说: </span>
<input id="message" class="edit" type="text">
</div>
<div class="row1">
<input type="button" value="表白" class="submit" onclick="mySubmit()">
</div>
</div>
<div id="allMsg"></div>
<script>
// 添加表白信息
function mySubmit()
var from = jQuery("#from");
var to = jQuery("#to");
var msg = jQuery("#message");
// 1.非空效验
if (from.val() == "" || to.val() == "" || msg.val() == "")
alert("请输入表白信息!")
if (from.val() == "")
from.focus();
if (to.val() == "")
to.focus();
if (msg.val() == "")
msg.focus();
return;
// 2.ajax 提交数据给后端
jQuery.ajax(
url: "message/add", // 提交到后端的地址
type: "POST", // 提交类型
data:
from: from.val(),
to: to.val(),
msg: msg.val()
, // 参数
success: function (result) // 后端返回给前端的数据
if (result != null && result > 0)
alert("表白成功!");
from.val('');
to.val('');
msg.val('');
// 刷新表白列表
getAllMsg();
else
alert("表白失败!");
);
// 查询所有的表白信息
function getAllMsg()
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="msg">' +
result[i].from + '对' +
result[i].to + '说: ' +
result[i].message + '</div>';
jQuery("#allMsg").html(msgHtml);
else if (result != null && result.length == 0)
// 没有表白数据
console.log("没有表白信息");
else
alert("访问出错!");
);
getAllMsg(); // 执行方法
</script>
</body>
</html>
5.创建数据库
创建数据库,并添加 messages 表.
-- 设置编码格式
set character_set_database=utf8;
set character_set_server=utf8;
-- 创建数据库
create database if not exists messagewall;
-- 使用数据库
use messagewall;
-- 创建messages表
drop table if exists messages;
create table messages (`from` varchar(255), `to` varchar(255), `message`
varchar(2048));
6.部署项目
(1)在IDEA中配置Tomcat,需要先下载一个插件:
(2)然后点击 Add Configuration
(3)选择Tomcat
(4)可以改个名字,然后点击ok
(5)启动Tomcat
这样就说明启动成功啦!
(6)在浏览器输入项目对应URL
成功访问!
7.效果展示
初始界面:
查询数据库:
数据库为空!
输入信息并点击表白:
提示表白成功!并从服务器获取信息展示在下方:
查询数据库中信息:
可以看到成功将数据写入数据库中!
结束啦!祝大家度过一个快乐的520 !
以上是关于520到了,教你做个JavaWeb表白墙小项目的主要内容,如果未能解决你的问题,请参考以下文章