1.创建maven项目(取名为firstServlet);
2.按上图创建各个文件:
3.在 pom.xml 中引⼊ mysql 的依赖
注意:引入与自己相对应的版本号
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.45version>
dependency>
4.创建数据库, 创建 messages 表
set character_set_database=utf8;
set character_set_server=utf8;
create database if not exists LovingWall;
use LovingWall;
drop table if exists messages;
create table messages (`from` varchar(255), `to` varchar(255), `message`
varchar(2048));
5.创建 DBUtil 类
DBUtil 类主要实现以下功能:
创建 MysqlDataSource 实例, 设置 URL, username, password 等属性.
提供 getConnection ⽅法, 和 MySQL 服务器建⽴连接.
提供 close ⽅法, ⽤来释放必要的资源.
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBUtil{
private DBUtil() {
}
private static volatile MysqlDataSource mysqlDataSource;
private static volatile Connection connection;
/**
* 采用了单例模式
*/
//1.get DataSource
private static MysqlDataSource getMysqlDataSource() {
if (mysqlDataSource == null) {
synchronized (DBUtil.class) {
if (mysqlDataSource == null) {
mysqlDataSource = new MysqlDataSource();
mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/LovingWall?characterEncoding:utf8&useSSL=false");
mysqlDataSource.setUser("root");
mysqlDataSource.setPassword("12345678");
}
}
}
return mysqlDataSource;
}
// 2.get connect
public static Connection getConnection() {
if (connection == null) { // 首次访问
synchronized (DBUtil.class) {
if (connection == null) {
try {
//1.得到数据源
MysqlDataSource dataSource = getMysqlDataSource();
//2.数据库连接
connection = (Connection) dataSource.getConnection();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
return connection;
}
// 2.提供关闭资源的方法
public static void close(ResultSet resultSet, PreparedStatement statement, Connection connection) throws SQLException {
//得到结果,执行完成,关闭资源
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
}
}
2.创建的loving_wall.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>
div>
<script>
//添加表白信息
function mySubmit(){
//1.得到控件
var from=jQuery("#from");
var to=jQuery("#to");
var message=jQuery("#message");
//2.非空效验
if(""==jQuery.trim(from.val())){
alert("请先输入表白者!");
username.focus();
return;
}
if(""==jQuery.trim(to.val())){
alert("请先输入被表白者!");
password.focus();
return;
}
if(""==jQuery.trim(message.val())){
alert("请先输入告白词!");
password.focus();
return;
}
//3.Ajax提交数据给后端
jQuery.ajax({
url:"addmessage2",
method:"POST",
data:{
from:from.val(),
to:to.val(),
message:message.val()
},
success:function(result){ //后端返回给前端的数据
if(result!=null&&result>0){
alert("表白添加成功!");
//更新表白墙信息
GetMessage();
}else{
alert("表白添加失败,请重试!")
}
}
});
}
//得到表白信息
function GetMessage(){
jQuery.ajax({
url:"getmessage2",
method:"GET",
data:{},
success:function(result){
if(result!=null&&result.length>0){
//有数据
var mh="";
for(var i=0;i<result.length;i++){
mh+= ''+
result[i].from+'对'+
result[i].to+'说: '+
result[i].message+'';
}
jQuery("#allMsg").html(mh);
}else if(result!=null&&result.length>0){
//没有数据
console.log("没有表白信息")
}else{
alert("访问出错啦!")
}
}
});
}
GetMessage();//页面加载时,就执行
script>
body>
html>
3.valuable 文件
public class Valuable {
public static boolean haslength(String s){
return (s!=null&&s.length()!=0);
}
}
4.AddLovingMessage2类
import com.mysql.jdbc.Connection;
import lombok.SneakyThrows;
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.PreparedStatement;
@WebServlet("/addmessage2")
public class AddLovingMessage2 extends HttpServlet {
@SneakyThrows
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int result=0;
//1.得到前端值
String from=req.getParameter("from");
String to=req.getParameter("to");
String message=req.getParameter("message");
if(Valuable.haslength(from)&&Valuable.haslength(to)&&Valuable.haslength(message)){
//2.讲表白信息加到数据库
/**
* 2.1得到connection:包括去获取数据源了
* 2.2得到执行器
* 2.3执行SQL
* 2.4关闭资源
*/
//2.1
Connection connection = DBUtil.getConnection();
//2.2
String insertSQL="insert into messages(`from`,`to`,`message`) values(?,?,?)";
PreparedStatement statement= connection.prepareStatement(insertSQL);
statement.setString(1,from);
statement.setString(2,to);
statement.setString(3,message);
// 2.3 执行执行器,并返回结果
result=statement.executeUpdate();
// 2.4 关闭资源
DBUtil.close(null, statement, connection);
}
resp.setContentType("text/html;charset=utf-8");
//给前端一个消息提示是否添加成功
resp.getWriter().println(result);
}
}
5.GetLovingMessage2类
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.Connection;
import lombok.SneakyThrows;
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.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/getmessage2")
public class GetLovingMessage2 extends HttpServlet {
@SneakyThrows
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 查询数据库中的表白列表
List<Message> list = new ArrayList<>();
// 1.得到 connection
Connection connection = DBUtil.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.关闭资源
DBUtil.close(resultSet, statement, connection);
resp.setContentType("application/json; charset=utf-8");
ObjectMapper objectMapper = new ObjectMapper();
resp.getWriter().println(objectMapper.writeValueAsString(list));
}
}