Several ways to use tomcat to deploy front-end and back-end programs to interact with front-end and back-end programs

This article mainly involves how to use tomcat to deploy front-end and back-end programs and several ways to interact with front-end and back-end programs. First, how to deploy back-end programs in tomcat

Deployment backend program

1. Create a project

First create a maven project in idea

File in the upper right corner – New – Create a new project and select the maven project to get a pom.xml project

2. Introduce dependencies

Create the tag and introduce the corresponding jar package in it. The code is as follows

 <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

The code contains the parent class required by the next http class

After importing, the pom.xml project file is as follows



    4.0.0

    org.example
    untitled1
    1.0-SNAPSHOT

    
        8
        8
        UTF-8
    
    
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <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.14.1</version>
        </dependency>
        
    
<packaging>war</packaging>
    hello_servlet1

3. Create a project

Create a new WEB-INF file under the webapp folder Create a web.xml file under this folder

The main purpose of introducing this file is to tell tomcat that the project needs to be run by tomcat

Write the following code in 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>

So far it’s been a routine

4. Create code

Create java code under the java folder

@WebServlet("/hello1")
public class hellosevelet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

       // super. doGet(req, resp);
        //belongs to the resp object and writes to the body object of resp
        String student=req. getParameter("studentid");
        String classid=req. getParameter("classid");
        resp.getWriter().write("studentid=" + student + "classid=" + classid);


    }
}

Here are a few points to note

1. You need to inherit the httpservlet class in the jar package that the first step depends on

2. Shield the super that comes with the code, because the parent class returns the error interface by default

3. req is the request sent by the client, it will be automatically parsed, and resp is the feedback information set by the programmer himself

4. Finally, you need to add @WebServlet(“/the file path you want to set”) in front of the code

5. doget is called when the front end sends a get request, and dopost is called when a post is sent

5. Packager

First, tomcat needs a war package to run the back-end code, and the default jar package is packaged, so the code needs to be written in pom.xml

<packaging>war</packaging>

turn it into a war package

Then find the maven program on the right, find the packet, double-click to run, and a jar package with the default project name will appear

6. Deployment program

Put the obtained jar package under the webapp in tomcat, tomcat will automatically generate a directory, and then find the start.bat program in the bin folder to start tomcat

7. Verification

Enter verification into the site

http://127.0.0.1:8080/hello_servlet1/hello2

127.0.0.1 represents the local ip 8080 represents the local port bound to tomcat hello_servlet is the jar package name, which is the context path hello2 is the file path written by myself

In this way, we have successfully deployed the backend code to tomcat (note that using the dopost method will display a 405 method error because the default code for opening the backend page is get)

Of course, there are plug-ins such as smarttomcat that can combine packaging projects and deployment projects. You can download and install them for a try, which can improve efficiency.

Next, let’s see how to deploy the front-end code

Deploy front-end code

Deploying the front-end code is simpler than the back-end. Create an html project in the webapp (tomcat stipulates that the front-end code needs to be saved here)

Several ways of front-end and back-end interaction

1. Transmission of query string through key-value pair

 String student=req. getParameter("studentid");
        String classid=req. getParameter("classid");
        resp.getWriter().write("studentid=" + student + "classid=" + classid);

Next, our default backend code needs to accept two values student and classid and print them

The first and easiest way is to add query strings to the website to pass information

http://127.0.0.1:8080/hello_servlet1/hello1?studentid=100 &classid=200

Use = to connect the key-values, use ? to separate the file hierarchy and query string directly, use & amp; to separate different key-value pairs

In this way, the studentid and classid can be passed to the backend correctly

2. Delivery via ajax

First introduce jquery cdn containing ajax

<script src="//i2.wp.com/cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js">

</script>

And the required method and relative path (this is for the path where the html file is located)

$.ajax({
 type:'get',
  url:'hello1',
  

  

});

After the construction is completed, the front-end and back-end interaction can be completed to realize data transmission

3. Use the form tag

 <form action="hello1"method="Post">
  <input type="text" name="studentid">
  <input type="text"name="classid">
  <input type="submit"value="submit">
</form> 

The action and method are the same as the url and type in ajax. The user enters through input and submits it with submit. The backend can get the value corresponding to the name

4. Send json request with postman

body-raw-json send json request (send) json request format is similar to

{

“studentid”: 10,

“classid”:20

}Same

Note that when the backend receives the json request at this time, it does not automatically parse out the key-value pair, but req reads the json request completely by reading bytes

If you want to parse out key-value pairs, you need

1. Introduce dependencies

 <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.14.1</version>
        </dependency>

2. Create a class in the java code that contains the key-value pairs that need to be read

class student{
    public int studentid;
    public int classid;
}

3. Create ObjectMapper objectMapper = new ObjectMapper();

4. Through getvalueof in objectmapper, convert the json request byte stream read by req into the corresponding attribute in the class and return a new class object

student s=objectMapper.readValue(req.getInputStream(),student.class);

In this way, the required key-value pairs can be obtained. In actual production, if tomcat is used to realize front-end and back-end interaction, json requests are used more