当前位置:网站首页>Code case - web version confession wall and file upload
Code case - web version confession wall and file upload
2022-06-10 00:42:00 【Classmate pan】
List of articles
Achieve one web Confession wall
Because the data of the confession wall written by the blogger before learning from the front end cannot be saved , So this time is to change the previously implemented confession wall program to the server version , So even if the page is closed , The content of the confession wall will not be lost , In order to realize the data, do " Persistence " Storage , So I use a database here to store information .
preparation
- establish maven project
- Create the necessary directories webapp,WEB-INF,web.xml

<!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 Application</display-name>
</web-app>
- adjustment pom.xml
Introduce dependencies , Configuration generation war package , as well as war The name of the bag
<?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>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- Join in servlet rely on -->
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<!-- servlet Version and tomcat There is a corresponding relationship between versions , Bear in mind -->
<version>3.1.0</version>
<!-- This means that we only need this dependency in the development phase , Deploy to tomcat You don't need it when you go on -->
<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.12.6.1</version>
</dependency>
<!-- introduce mysql Drive pack -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
</project>
- Copy the front page of the confession wall implemented before to webapp Directory
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Confession wall </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: 70px; } .row input {
width: 300px; height: 30px; font-size: 15px; text-indent: 0.5em; outline:none ; } .row #btn {
width:300px; height: 40px; font-size: 20px; line-height: 40px; margin: 0 auto; color: white; background-color: orange; border:none; border-radius: 10px; } .row #btn:active {
background-color: gray; } </style>
<div class="container">
<h3> Confession wall </h3>
<p> Click Submit after entering , The information will be displayed in the table </p>
<div class="row">
<span> who :</span>
<input type="text">
</div>
<div class="row">
<span> To whom :</span>
<input type="text">
</div>
<div class="row">
<span> what did you say? :</span>
<input type="text">
</div>
<div class="row">
<button id="btn"> Submit </button>
</div>
</div>
<script> // When the user clicks submit, You'll get it input The content in , So as to form a div, Insert at the end of the page let submitBtn=document.querySelector('#btn'); submitBtn.onclick=function(){
// 1. Get 3 individual input The content in let input=document.querySelectorAll('input'); let from=input[0].value; let to=input[1].value; let msg=input[2].value; if(from==''||to==''||msg==''){
// The user hasn't finished , Don't submit data for the time being return ; } //2. Make a new one div, The content is input What's in it , Put this new div Add to page let newDiv=document.createElement('div'); newDiv.innerHTML=from+' Yes '+to+' say :'+msg; newDiv.className='row'; let container=document.querySelector('.container'); container.appendChild(newDiv); //3. Clear the contents of the previous input box for (let i = 0; i < input.length; i++) {
input[i].value=''; } } </script>
</body>
</html>
Agree on the front and back-end interaction interface
So-called “ Front end and back end interface ”: Carry out Web Key links in development
say concretely : That is, what pages are allowed to send to the server HTTP request , And what kind of... Each request is expected to get HTTP ring Should be .
- Get all messages
request :
GET /message
Respond to : JSON Format
[
{
from: " Jackson Yi ",
to: " Crane ",
message: " Nice to meet you "
},
{
from: " Brother Xizi ",
to: " Fat crane ",
message: " Try to see me "
},
......
]
We expect the browser to send a message to the server GET /message Such a request , You can return the current total number of messages
record , The result is json Return to the format of
- Post new messages
request : body Also for the JSON Format
POST /message
{
from: " bosses ",
to: " Tsuruko ",
message: " Be happy "
}
Respond to : JSON Format
{
ok: true
}
We expect the browser to send a message to the server POST /message Such a request , You can submit the current message to the server
Implement server-side code
establish Message class
class Message{
public String from;
public String to;
public String message;
}
establish MessageServlet class
@WebServlet("/message")
public class MessageServlet extends HttpServlet {
// Used to convert JSON character string
private ObjectMapper objectMapper=new ObjectMapper();
// Used to save all messages
private List<Message>messages=new ArrayList<>();
// Get all messages
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Processing requests for submitted information
Message message=objectMapper.readValue(req.getInputStream(),Message.class);
// The simplest way to save is to save in memory
messages.add(message);
// adopt ContentType To inform the page , The data returned is json Format
// With such a statement , here jQuery Ajax Will automatically help us turn the string into js object
// without ,jQuery Ajax Just treat it as a string
resp.setContentType("application/json;charset=utf8");
resp.getWriter().write("{\"ok\":true}");
}
// Add a message
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Get message list , Just return the whole contents of the message list to the client
// You need to use ObjectMapper hold Java object , convert to json Format string
String jsonString=objectMapper.writeValueAsString(messages);
System.out.println("jsonString:"+jsonString);
resp.setContentType("application/json;charset=utf8");
resp.getWriter().write(jsonString);
}
ObjectMapper Of readValue Method Can also Directly from a InputStream Object reading data ;
ObjectMapper Of writeValueAsString Method Can also put a The object array is directly converted to JSON Format string
Adjust the front page code
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script> // Join in Ajax Code for , The logic to be added here has two parts // When you click the submit button ,Ajax To construct data to send to the server // When the page is loaded , Get the message list from the server , And display directly on the interface function getMessages(){
$.ajax({
type:'get', url:'message', success:function(body){
// At present body Is already a js Object array ,Ajax According to the response contentType To automatically parse // If the server returns contentType It's already application/json 了 ,Ajax It will body Automatically convert to js The object of // If the client does not automatically transfer , It can also be done through JSON.parse() This function is used to convert manually // Take each element in the array in turn let container=document.querySelector('.container'); for(let message of body){
let div=document.createElement('div'); div.innerHTML=message.from+' Yes '+message.to+' say :'+message.message; div.className='row'; container.appendChild(div); } } }); } // Plus function calls getMessages(); // When the user clicks submit, You'll get it input The content in , So as to form a div, Insert at the end of the page let submitBtn=document.querySelector('#btn'); submitBtn.onclick=function(){
//1. Get 3 individual input The content in let input=document.querySelectorAll('input'); let from=input[0].value; let to=input[1].value; let msg=input[2].value; if(from==''||to==''||msg==''){
// The user hasn't finished , Don't submit data for the time being return ; } //2. Make a new one div, The content is input What's in it , Put this new div Add to page let newDiv=document.createElement('div'); newDiv.innerHTML=from+' Yes '+to+' say :'+msg; newDiv.className='row'; let container=document.querySelector('.container'); container.appendChild(newDiv); //3. Clear the contents of the previous input box for (let i = 0; i < input.length; i++) {
input[i].value=''; } //4. Put the contents of the currently obtained input box , Construct into a HTTP POST request , adopt Ajax To the server let body={
from:from, to:to, message:msg }; $.ajax({
type:"post", url:"message", contentType:"application/json;charset=utf8", data:JSON.stringify(body), success:function(body){
alert(" Message submitted successfully !"); }, error:function(){
alert(" Message submission failed !"); } }); } </script>
At this point, every time we submit data, it will be sent to the server , Each time you open a page, the page loads data from the server , So even if you close the page , The data will not be lost .
But the data is stored in the memory of the server ( private List messages = new ArrayList(); ), Once the server restarts , Data will still be lost .
The data is stored in the database
Answer the above question , If you save data in a database , Then restart the server without losing data .
- stay pom.xml Introduction in mysql Dependence ( It has been introduced above )
- Create database , establish message surface
create table message(`from` varchar(1000), to varchar(1000), message varchar(3000));
ps: because from yes sql Keywords in statements , So use backquotes `` Surround
- establish DBUtil class
DBUtil Class mainly realizes the following functions :
- establish MysqlDataSource example , Set up URL, username,password Equal attribute
- Provide getConnection Method , and MySQL Server establishes connection
- Provide close Method , To release the necessary resources
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;
public class DBUtil {
private static final String URL="jdbc:mysql://127.0.0.1:3306/wall?characterEncoding=utf8&useSSL=false";
private static final String USERNAME="root";
private static final String PASSWORD="root";
private volatile 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 close(Connection connection, PreparedStatement statement, ResultSet resultSet){
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
- add to load and save Method , Operating the database
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.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
class Message{
public String from;
public String to;
public String message;
}
@WebServlet("/message")
public class MessageServlet extends HttpServlet {
private ObjectMapper objectMapper=new ObjectMapper();
// Change to database , You don't need this variable
//private List<Message>messages=new ArrayList<>();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Processing requests for submitted information
Message message=objectMapper.readValue(req.getInputStream(),Message.class);
// The simplest way to save is to save in memory
//messages.add(message);
// adopt ContentType To inform the page , The data returned is json Format
// With such a statement , here jQuery Ajax Will automatically help us turn the string into js object
// without ,jQuery Ajax Just treat it as a string
save(message);
resp.setContentType("application/json;charset=utf8");
resp.getWriter().write("{\"ok\":true}");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Get message list , Just return the whole contents of the message list to the client
// You need to use ObjectMapper hold Java object , convert to json Format string
List<Message>messages=load();
String jsonString=objectMapper.writeValueAsString(messages);
System.out.println("jsonString:"+jsonString);
resp.setContentType("application/json;charset=utf8");
resp.getWriter().write(jsonString);
}
private void save(Message message){
// Save a message to the database
Connection connection=null;
PreparedStatement statement=null;
try {
//1. Establish connection with database
connection=DBUtil.getConnection();
//2. structure sql sentence
String sql="insert into message values(?,?,?)";
statement= connection.prepareStatement(sql);
statement.setString(1,message.from);
statement.setString(2,message.to);
statement.setString(3,message.message);
//3. perform SQL
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.close(connection,statement,null);
}
}
private List<Message>load(){
// Get all the messages from the database
Connection connection=null;
PreparedStatement statement=null;
ResultSet resultSet=null;
List<Message>messages=new ArrayList<>();
try {
connection=DBUtil.getConnection();
String sql="select * from message";
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");
messages.add(message);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.close(connection,statement,resultSet);
}
return messages;
}
}
Realization effect


Redeploy the program , At this point, the use of the database can ensure that even if the server restarts , Data is not lost , It achieves the effect of permanent preservation .
Upload files
The core approach
HttpServletRequest Class method :
| Method | describe |
|---|---|
| Part getPart(String name) | Gets the value given in the request name The file of |
| Collection getParts()} Get all the files |
Part Class method :
| Method | describe |
|---|---|
| String getSubmittedFileName() | Get the submitted file name |
| String getContentType() | Get the file type submitted |
| long getSize() | Get file size |
| void write(String path) | Write the submitted file data to the disk file |
Code example —— Submit a picture to the server through the web page
- establish upload.html, Put it in webapp Directory
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="MyImage">
<input type="submit" value=" Submit ">
</form>
- Upload files usually through POST request Form implementation of
- stay form To add multipart/form-data Field
- establish UploadServlet class
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
@MultipartConfig
@WebServlet("/upload")
public class UpLoadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Part part=req.getPart("MyImage");
System.out.println(part.getSubmittedFileName());
System.out.println(part.getContentType());
System.out.println(part.getSize());
part.write("e:/yyqx.jpg");
resp.setContentType("text/html;charset=utf8");
resp.getWriter().write(" Upload successful !");
}
}
- Need to give UploadServlet add @MultipartConfig annotation , To enable support for uploading files , Otherwise, the server code calls getPart Method will throw an exception
- getPart Of Parameters Need and form in input Labeled name Properties corresponding to
- The client can submit multiple files at a time ( The use of multiple input label ), At this point, the server can use getParts Get all Part object .
- The deployment process

After selecting files , Click on the submit , Then the page jumps to /upload page
At this point, you can see the print log on the server side
At the same time e The disk generates yyqx.jpg
The packet capturing result of the upload image request is :

边栏推荐
- Py6s configuration tutorial (win10 × 64)
- wps合并单元格后怎么将文字的位置进行调整
- Several syntax for adding events to elements in a page
- 請問徽商期貨是正規的嗎?開戶交易安全嗎?
- ECA-Net: Efficient Channel Attention for Deep Convolutional Neural Networks
- 应用最新的AD和TXK补丁
- [docker]mysql scheduled backup
- Auto format when saving vscode configuration file
- Encryption, decryption and signature verification
- Disorder of flinksql
猜你喜欢

慢查询如何优化?(实战慢查询)

Sélection de la fonction pour déterminer si elle est vide
Score of sub series of previous test questions and [11th] [provincial competition] [group B]

if判斷是否為空時的函數選擇
Process test supports batch parameter import, and the test efficiency is directly full!

最低通行费
![二叉树展开为链表[树处理的精髓--如何处理每一颗子树]](/img/b3/5a7c20fad1fd17ef82ed730d686723.png)
二叉树展开为链表[树处理的精髓--如何处理每一颗子树]

Idea uninstall tutorial
DFS和BFS在二叉树中的应用

wps合并单元格后怎么将文字的位置进行调整
随机推荐
Cloudcompare & PCL principal curvature, mean curvature and Gaussian curvature calculation
Numpy basic operation
DFS和BFS在二叉树中的应用
蓝桥杯·寒假百校真题大联赛(第五期)研究生&大学A组 《货物摆放》真题练习
[typecho] how to query multiple tables
二分查找(折半查找)总结
With the advent of the digital era, 360 has joined hands with the dark horse of entrepreneurship to help small and medium-sized enterprises seize the key future
Disorder of flinksql
js 逻辑空分配双问号语法 、双竖杠语法 与 可选链语法
ArcMap resolving geometric errors
ADB shell WM command using
ps标尺调精确位置在哪
Introduction to bias and variance
Process test supports batch parameter import, and the test efficiency is directly full!
RHCSA第二天
Go Technology Daily (June 8, 2022) -- talk about 10 scenarios of index failure. It's too stupid
if判斷是否為空時的函數選擇
SIGIR 2022 | HKU and Wuhan University put forward kgcl: a recommendation system based on knowledge map comparative learning
慢查询如何优化?(实战慢查询)
View the installable version number of the wheel on this computer