Server version of the confession wall

Posted by candy2126 on Thu, 24 Feb 2022 14:12:56 +0100

1, Connect the html page to the server

First, in the previous blog, I wrote the html version of the confession wall
Now, you need to connect the html version of the confession wall to the back-end server
The code is as follows:

import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileWriter;
import java.io.IOException;
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();
   //The data is saved in the List. After connecting to the server, you can only ensure that the information will not be lost after the browser is refreshed. However,
   // At this time, it is only saved in memory. When the server is restarted, the data cannot be permanently saved,
    // Therefore, to save permanently, you need to save the data in the file / database
   //Next, show how to save the information in a file in messageservlet 2
    private List<Message> list=new ArrayList<Message>();
    @Override
    public void init(){
        //Here, we construct several test data for the list to facilitate our observation. This construction data can be placed in the init method or in the constructor
        Message message=new Message();
        message.from="A";
        message.to="B";
        message.message="hello";
        list.add(message);

        message=new Message();
        message.from="C";
        message.to="D";
        message.message="Hello";
        list.add(message);
    }

    //This method is used to process: get data from the server
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset=utf-8");
        //Write the contents of the list in json format, and then give it to resp Getwrite() to print
        objectMapper.writeValue(resp.getWriter(),list);
    }
    //This method is used to process: submit data from the client to the server
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //First read the content and then parse it
        //Read the content, read the content in the request (req), and then put the read content in the Message class
        Message message=objectMapper.readValue(req.getInputStream(), Message.class);
        //Save the submitted data in the list
        resp.setContentType("application/json;charset=utf-8");
        list.add(message);
        resp.getWriter().write("{\"ok\":1}");
    }
}

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>ConfessionWall</title>
</head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<body>
<div class="container">
    <h1>Confession wall</h1>
    <p>Click Submit after input, and the information will be displayed in the form</p>
    <div class="row">
        <span>Who:</span>
        <input type="text" class="edit">
    </div>
    <div class="row" >
        <span>To whom:</span>
        <input type="text" class="edit">
    </div>
    <div class="row">
        <span>what did you say?</span>
        <input type="text" class="edit">
    </div>
    <div class="row">
        <input type="button" value="Submit" id="submit">
    </div>
    <!--use ajax On the premise of jquery cdn Copy on ajax´╝îThen paste it below-->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
        //1. When the page is loaded, access the server, obtain the message example table from the server and display it
        function load(){
            //Through the load function, the message is obtained from the server and displayed
            $.ajax({
                type:'get',
                url:'message',
                //Callback function
                success:function(data,status){
                    //data is the body of the response. At this time, the response may be in a string format. You can manually parse the object in json format
                    //Because at this time, the format of content type in MessageServlet class is application/json
                    //Therefore, at this time, the data format of data is Array,
                    //Therefore, you do not need to use this Jason parse(data);
                    // let messages=JSON.parse(data);
                    let messages=data;
                    let container=document.querySelector('.container');
                    //Traverse the obtained object
                    for(let message of messages){
                        let row =document.createElement('div');
                        row.className='row';
                        row.innerHTML=message.from+'yes'+message.to+'say:'+message.message;
                        container.appendChild(row);
                    }
                }
            });
        }
        //Call function
        load();
        //2. When clicking the submit button, construct the current data into an HTTP request and send it to the server
        let submitButton=document.querySelector('#submit');
        submitButton.onclick=function(){
            //1. Get the content of the edit box first
            let edits=document.querySelectorAll('.edit');
            //Rely on Its value input box to obtain its value
            let from=edits[0].value;
            let to=edits[1].value;
            let message=edits[2].value;
            console.log(from,to,message);
            //Here is to verify the legitimacy of user input to see whether the user input is legitimate
            if(from==''||to==' '||message==''){
                return;
            }
            //2. According to the content, construct HTML elements (. row contains user input)
            //createElement: create an element
            let row=document.createElement('div');
            row.className='row';
            row.innerHTML=from+'yes'+to+'Said:'+message;
            //3. Add this new element to the DOM tree
            let container=document.querySelector('.container');
            container.appendChild(row);
            //4. Clear the original input box
            for(let i=0;i<edits.length;i++){
                edits[i].value='';
            }
            //5. Construct an http request and send the message to the server for saving
            $.ajax({
                type:"POST",
                url:"message",
                data:JSON.stringify({from:from,to:to,message:message}),
                contentType:"application/json;charset:utf-8",
                success:function(data,status){
                    if(data.ok==1){
                        console.log('success');
                    }else{
                        console.log('fail');
                    }
                }
            })

        }
    </script>
    <style>
        /*Remove the browser default style: inner margin, outer margin, inner border and outer border will not support the box*/
        *{
            margin:0;
            padding: 0;
            box-sizing: border-box;
        }
        /*margin:0 auto :It means center*/
        .container{
            width: 400px;
            margin:0 auto;
        }
        /*padding:20px auto :h1 Label: upper and lower spacing 20*/
        h1{
            text-align:center;
            padding:20px auto;
        }
        p{
            text-align:center;
            color:#666;
            padding: 10px 0;
            font-size:14px;
        }
        /*display:flex:Based on elastic layout
          justify-content:center:horizontally
          align-items:center:Vertical center
        */
        .row{
            height:50px ;
            display: flex;
            justify-content: center;
            align-items:center;
        }
        /*Now adjust the length of span and input*/
        span{
            width:90px;
            font-size: 20px;
        }
        input{
            width:310px;
            height: 40px;
            font-size: 18px;
        }
        /*Now deal with the submit button
         First, the submit button is as wide as the parent element
         Secondly, set the font color and background color
         Then, border:none: function: to remove the black border
              border-radius:Set the four corners to circular rectangle
              font-size:Sets the size of the submission font
        */

        #submit{
            width: 400px;
            color: white;
            background-color:orange;
            border:none;
            border-radius:5px;
            font-size: 18px;
        }
        /*Clicking the submit button will change its background color*/
        #submit:active{
            background-color: black;
        }
    </style>
</div>
</body>
</html>

Complete screenshot

At this time, compared with the previous html version, this is connected to the server. When the page is refreshed, the submitted data still exists
However, at this time, the data is saved in memory, not permanently. When the server restarts, it will be completely updated and the entered data will not be saved
Therefore, at this time, there are two ways to save permanently: one is to save in the file, and the other is to save in the database

Parse strings into objects in JSON format:
In JS, let message = JSON parse(data );
In Java, message = objectmapper readValue(req.InputStreaam(),Message. class());
Convert object to string
In JS, JSON stringfy();
In Java, objectmapper writeValue(resp.getWriter(),list);
Content type is a text / HTML, and the data format of text / plain body is string
Content type is an application/json body, and the data format will be automatically converted into object/Array by jQuery
When the data of the body is a string, you need to use let message = JSON Parse (data), convert to object / Array

2, Save the data submitted by the html page in a file

As shown below, save the data of the service in a file
The html code remains unchanged

import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
class Message2{
    public String from;
    public String to;
    public String message;
}
//Here is how to save the data in the file
@WebServlet("/message")
public class MessageServlet2 extends HttpServlet {
    private ObjectMapper objectMapper=new ObjectMapper();
    //The data is saved in the List. After connecting to the server, you can only ensure that the information will not be lost after the browser is refreshed. However,
    // At this time, it is only saved in memory. When the server is restarted, the data cannot be permanently saved,
    // Therefore, to save permanently, you need to save the data in the file / database


    //Next, demonstrate the usage of saving in a file
    //The path where this file is saved
    private String filePath="d:/message.txt";

    //This method is used to process: get data from the server
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset=utf-8");
        //In the doPost method, the information has been obtained from the client and stored in the file
        //At this time, in the doGet method, you need to finish loading the information response in the file into the browser page
        //Load through load method
        //Put the information loaded by load into the list
        List<Message> messageList=load();
        //Convert the contents of messageList into json format, and then give it to resp Getwriter() to print
        objectMapper.writeValue(resp.getWriter(),messageList);
    }
    private List<Message> load() {
        //This method is responsible for reading the file, obtaining the read data and putting it in the list < message >
        List<Message> messageList=new ArrayList<>();
        System.out.println("Load from file!");
        //Currently, it is necessary to read by line. FileReader itself cannot read by line
        //Therefore, you need to add a layer of shell to FileReader. BufferReader bufferedReader =new BufferedReader()
        //Here, you need to read data from the file by line
        try(BufferedReader bufferedReader =new BufferedReader(new FileReader(filePath))){
            //Here, you need to read by line
            while(true){
                String line=bufferedReader.readLine();
                if(line==null){
                    //Here, it is considered that the read data is empty,
                    break;
                }
                //If the content of the line is read, the line is parsed into a Message object
                //Divide according to tab, and store the divided contents into the array
                String[] tokens=line.split("\t");
                Message message=new Message();
                message.from=tokens[0];
                message.to=tokens[1];
                message.message=tokens[2];
                messageList.add(message);
            }
        }catch(IOException e){
            e.printStackTrace();
        }
        return messageList;
    }
    //This method is used to process: submit data from the client to the server
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //First read the content and then parse it
        //Read the content, read the content in the request (req), and then put the read content in the Message class
        Message2 message=objectMapper.readValue(req.getInputStream(), Message2.class);
        //Data to be submitted
        resp.setContentType("application/json;charset=utf-8");

        //Here, you need to complete an operation to write a file
        //In the first method, the information of the client is stored in the file message under disk D Txt
        save(message);
        resp.getWriter().write("{\"ok\":1}");
    }
    //Functions for writing files
    private void save(Message2 message) {
        System.out.println("Write data to file");
        //The usage of FileWriter is similar to that of PrintWrite described earlier. There is a key method: write()
        try(FileWriter fileWriter=new FileWriter(filePath,true)){
            //There are many formats for writing files. You can write json directly or in line text format. Each record occupies one line, and the fields are distinguished by separators
            fileWriter.write(message.from+"\t"+message.to+"\t"+message.message+"\n");
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}

Access path:
http://localhost:8080/Light_demo1/ConfessionWall.html (this is selected according to the path of your computer)
Save the information input from the html front end in D: / message Txt

When the server is restarted, not only the information in the file still exists, but also the existing information in the file will be displayed on the page
>

In many languages,
There are three main ways to open a file:
1. Open read mode and use the mode of input stream object
2. Open the write mode and use the output stream object mode (open the write mode directly and the original contents of the file will be emptied)
3. The append write mode is turned on. When using the output stream object, the original contents of the file will not be cleared, but will be added directly to the last

3, Save the data submitted by html page in the database

Next, write about how to put the data submitted by html page in the database
1. Create database

2. Connect the server to the database

import com.fasterxml.jackson.databind.ObjectMapper;

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 Message3{
    public String from;
    public String to;
    public String message;
}
//Load the contents of the browser page into the back-end database
@WebServlet("/message")
public class MessageServlet3 extends HttpServlet {
    private ObjectMapper objectMapper=new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset=utf-8");
        List<Message> messageList=load();
        objectMapper.writeValue(resp.getWriter(),messageList);
    }
    private List<Message> load() {
        List<Message> messageList=new ArrayList<>();
        //Read data from database
        System.out.println("Read data from database");
        Connection connection=null;
        PreparedStatement statement=null;
        ResultSet resultSet=null;
        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");
                messageList.add(message);
            }
        }catch(SQLException e){
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,statement,resultSet);
        }
        return messageList;
    }
    @Override
    protected void doPost(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        //Read the client's request to, convert it into json format and put it in the class of Message3
        Message3 message3=objectMapper.readValue(req.getInputStream(),Message3.class);
        //Save the incoming information in the database
        save(message3);
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write("{\"ok\":1");
    }
    private void save(Message3 message3)  {
        System.out.println("Write data to the database");
        Connection connection=null;
        PreparedStatement statement=null;
        try{
            //1. First establish a connection with the database
            connection=DBUtil.getConnection();
            //2. Assemble sql statements
            String sql="insert into message values(?,?,?)";
            statement=connection.prepareStatement(sql);
            statement.setString(1,message3.from);
            statement.setString(2,message3.to);
            statement.setString(3,message3.message);
            //3. Execute SQL
            int ret=statement.executeUpdate();
            if(ret==1){
                System.out.println("Insert successful");
            }else{
                System.out.println("Insert failed");
            }
        }catch(SQLException e){
            e.printStackTrace();
        }finally{
            DBUtil.close(connection,statement,null);
        }
    }
}


//DBUtil class
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/java100?useUnicode=true&characterEncoding=UTF-8&useSSL=false";
    private static final String USERNAME="root";
    private static final String PASSWORD="root";
    private static DataSource dataSource =null;
    public 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 preparedStatement, ResultSet resultSet){
        if(resultSet!=null){
            try {
                resultSet.close();
            }catch(SQLException e){
                e.printStackTrace();
             }
            }
        if(preparedStatement!=null){
            try{
                preparedStatement.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
        if(connection !=null){
            try{
                connection.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
    }
}

Result screenshot:

Topics: Java server