Use idea23 to make a simple javaweb project (servlet)

I want to make a diary here, and record a project I learned by the way. It is suitable for novices, so don’t comment if you are a big guy, hahaha!

Experiment Goal

1. Master the use of javabean to implement business logic in Web programs

2. Proficient in using IDE to develop Servlet applications

3. Master the annotation function of Servlet3.0

Experimental Analysis

  1. For the front-end part, add it by writing a static page
  2. The background part, that is, the Servlet code, implements data addition

Experimental content

(1) Experimental purpose and principle

Master the basics of data connections

(2) Experimental content and procedures

Implement functions such as entering and modifying user and student information through web pages;

First submit the code

First create a StudentServlet.java file


import javax.servlet.RequestDispatcher;
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;

@WebServlet("/StudentServlet")
/*Here is a very simple annotation, which is introduced in the Java Servlet 3.0 specification*/


public class StudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");//Here are the rules for defining encoding


        //Here are a series of defined variables, get the values from the page below
        String name = request.getParameter("name");
        String studentId = request.getParameter("studentId");
        int age = Integer.parseInt(request.getParameter("age"));

        Student student = new Student();
        student.setName(name);
        student.setStudentId(studentId);
        student.setAge(age);

        //Here is the code I used to test when I kept getting errors
       /* System.out.println("Name: " + name);
        System.out.println("Student ID: " + studentId);
        System.out.println("Age: " + age);*/

        request.setAttribute("student", student);


        response.setContentType("text/html; charset=UTF-8"); // Also sets the content type and character encoding
        response.setCharacterEncoding("UTF-8");



        //The last interface displayed after successful data acquisition
        RequestDispatcher dispatcher = request.getRequestDispatcher("viewStudent.jsp");
        dispatcher.forward(request, response);
    }
}

Then there is a student class Student.java


public class Student {//Just some simple variable methods
    private String name;
    private String studentId;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getStudentId() {
        return studentId;
    }

    public void setStudentId(String studentId) {
        this.studentId = studentId;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Then for the static page, I use jsp, or you can use html.

addStudent.jsp

//Define encoding format
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<!DOCTYPE html>
<html>
<head>
    <title>Add student information</title>
</head>
<body>
<h1>Add student information</h1>
<form action="StudentServlet" method="post" accept-charset="UTF-8">
//The form is created using the post request method, and the encoding format of the received data is UTF-8
    Name: <input type="text" name="name"><br>
    Student ID: <input type="text" name="studentId"><br>
    Age: <input type="text" name="age" ><br>
    <input type="submit" value="Add">
</form>
</body>
</html>

The last display interface viewStudent.jsp

<body><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>Student Information</title>
</head>
<body>
<h1>Student Information</h1>
<table>
    <tr>
        <th>Name</th>
        <th>Student ID number</th>
        <th>Age</th>
    </tr>
    <tr>
        <td>${student.name}</td>
        <td>${student.studentId}</td>
        <td>${student.age}</td>
    </tr>
</table>
</body>
</html>

OK, the code is all here, you need to have a certain foundation to understand it. Then I used the idea dependency and everything was already used.

Now let’s talk about the problem I encountered. Every time I input Chinese characters for my name, the output will be garbled.

I found a lot of codes on the Internet, and also asked chatgpt but couldn’t solve it. Let’s take a look at the methods I found first.

This is the jsp encoding setting, I found that I had it at the beginning, excluded.

Someone I found online asked me to add the receiving encoding format. I added it, but there was still no change.

Then I added this code to the servlet project, which also receives strings in uft-8. But I found that it was still not solved.

I considered whether it was a browser problem. There was a problem with the encoding when inputting in the browser. After troubleshooting, I found that there was no problem.

In other words, it is not a browser problem, nor a code problem (actually it is a code problem, which has not been checked at this time).

Later, I thought about whether there was no problem when receiving, but there was a problem when transcoding and printing, so I wrote the code to print on the console, which is the following paragraph.

I found that what was printed on the console was garbled code, so I can determine that the problem was that the code was garbled when getting the data.

So I searched frantically for a solution, but couldn’t solve it. I thought about changing the request method. I changed the form in addStudnt.jsp

<form action="StudentServlet" method="post" accept-charset="UTF-8">Replaced
<form action="StudentServlet" method="get" accept-charset="UTF-8">

Of course, here is the change. In StudentServlet.java, you need to change doPost to doGet. I found that it is enough and it will not be garbled. I looked for information and found out

need to

request.setCharacterEncoding("UTF-8");

placed before the name.

Actually I don’t quite understand it, chatgpt explained

In Java Servlet, the request.setCharacterEncoding("UTF-8") method is used to set the requested character encoding. It tells the server to parse the requested data according to the specified character encoding. Therefore, this setting should be done before reading the request parameters to ensure that the server correctly parses the parameters in the request.

When you use methods such as request.getParameter("name") to get request parameters, the server needs to know how to decode the byte stream of these parameters. If the encoding is set before reading the parameter, the server will decode it according to the specified encoding to obtain the parameter value correctly.

If you put request.setCharacterEncoding("UTF-8") after reading the parameters, it may cause the parameters to be parsed incorrectly because the server has already followed the default encoding (usually ISO- 8859-1) The request has been parsed, and it is too late to set the encoding at this time.

Therefore, in order to ensure correct parsing of request parameters, it is usually recommended to set the requested character encoding before reading the parameters. It is a good practice to ensure that you use the correct encoding when getting parameters to avoid problems such as garbled characters.

The HTTP protocol defines multiple request methods, the most common of which are GET and POST. There are some differences in use between these two request methods, mainly related to the parameter transfer method, security and other aspects.

  1. Parameter passing method:

    • GET: Parameters are appended to the URL as a query string, such as http://example.com/page?name=value. In the URL, parameters are separated using & symbols.
    • POST: Parameters are passed in the request body, not in the URL, and therefore are not visible on the request URL.
  2. Security:

    • GET: Because the parameters are visible on the URL, they are not suitable for passing sensitive information such as passwords. The parameters of the GET request will be saved in the browser’s history, the server’s log file, etc.
    • POST: The parameters are in the request body and will not be saved in the browser history, which is relatively safer. Suitable for transmitting sensitive information.
  3. Data volume:

    • GET: Since the parameters are in the URL, the amount of data transmitted is limited, and it is generally used to obtain resources. URLs have length limits and are not suitable for transferring large amounts of data.
    • POST: can transfer large amounts of data and is suitable for operations such as submitting forms.

Regarding my question, why the GET request does not appear garbled, it is mainly because in general, the parameters of the GET request are directly appended to the URL, and the encoding used by the URL is usually UTF-8. Therefore, for a simple GET request, the browser will use UTF-8 encoding to transfer parameters by default, which is not prone to garbled characters.

However, if other encodings are manually specified in the URL, or the server uses different encodings when parsing the request, garbled characters may occur. Therefore, keeping URLs in the default UTF-8 encoding can usually avoid such problems.

================================================== =======================

end

That’s it for now, just briefly record the bugs that I haven’t been able to solve.