1.内存版表白墙
1.创建servlet项目 2.创建必要的目录src 3.调整pom.xml 引入servlet和jackson依赖: 4.message-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 class="row">
猫猫对狗狗说: 喵喵喵
</div>
<div class="row">
小赵对小张说: 你好
</div>
</div>
</div>
<script>
function mySubmit(){
var from = jQuery("#from");
var to = jQuery("#to");
var msg = jQuery("#message");
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("恭喜:添加成功!");
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="row">'+
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.AddMeaageServlet.java:
import lombok.Getter;
import lombok.Setter;
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;
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)) {
AddMessageServlet.msgList.add(new Message(from, to, msg));
result = 1;
}
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().println(result);
}
}
@Setter
@Getter
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;
}
}
6.MessageListServlet.java:
import com.fasterxml.jackson.databind.ObjectMapper;
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.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;
resp.setContentType("application/json;charset=utf-8");
ObjectMapper objectMapper=new ObjectMapper();
resp.getWriter().println(objectMapper.writeValueAsString(messageList));
}
}
7.通过浏览器访问:http://localhost:8080/first-servlet/message-wall.html 可以看到: 添加表白信息: (1)成功添加表白信息:
(2)用户输入不完整时提示输入错误:
表白信息列表: 上面的程序有一个问题数据是存储在内存中的,当服务器重启之后数据就会丢失。
2.数据库版表白墙
1.创建数据库和数据表: 此时数据库中还没有数据: 2.连接数据库: pom.xml中添加MYSQL JDBC依赖: 3.message-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");
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].message+'</div>';
}
jQuery("#allMsg").html(msgHtml);
}else if(result!=null && result.length==0){
console.log("没有表白信息");
}else{
alert("访问出错!");
}
}
});
}
getAllMsg();
</script>
</body>
</html>
4.DBUtils.java:
package utils;
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 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("123456");
}
}
}
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();
}
if (connection != null) {
connection.close();
}
}
}
5.AddMessageServletV2.java:
import com.mysql.jdbc.Connection;
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.PreparedStatement;
@WebServlet("/message/add2")
public class AddMessageServletV2 extends HttpServlet {
@SneakyThrows
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int result = -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)) {
Connection connection = DBUtils.getConnection();
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);
result = statement.executeUpdate();
DBUtils.close(null, statement, connection);
}
resp.setContentType("text/html; charset=utf-8");
resp.getWriter().println(result);
}
}
6.MessageListServletV2.java:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.Connection;
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.PreparedStatement;
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<>();
Connection connection= DBUtils.getConnection();
String sql="select * from messages";
PreparedStatement statement=connection.prepareStatement(sql);
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));
}
DBUtils.close(resultSet,statement,connection);
resp.setContentType("application/json;charset=utf-8");
ObjectMapper objectMapper=new ObjectMapper();
resp.getWriter().println(objectMapper.writeValueAsString(list));
}
}
7.运行结果: 添加表白信息: 添加信息失败: 表白信息列表: 8.数据库里查询信息:
|