How to create a Servlet project (Maven) to provide data interface for the front end?

foreword

Servlet is a technology for implementing dynamic pages, and it is a set of API provided by Tomcat to programmers to help programmers develop a web app simply and efficiently.

The main work of Servlet

Programmers are allowed to register a class, and execute some codes in this class when Tomcat receives a specific HTTP request.
Help programmers parse HTTP requests, and parse HTTP requests from a string into an HttpRequest object.
To help programmers construct HTTP responses, programmers only need to fill in some attribute fields for the specified HttpResponse object, and the Servlet will automatically construct an HTTP response string according to the HTTP protocol, and write it back to the client through the Socket. 

In short, Servlet is a set of API provided by Tomcat, so that the code written by programmers can cooperate well with Tomcat, so as to realize a web app more simply. Instead of paying attention to technical details such as Socket, HTTP protocol format, multi-thread concurrency, etc., the development threshold of web app is lowered and the development efficiency is improved. We only need to focus on this process of generating the response.

The following is a servlet project I wrote, which can be downloaded if necessary:

https://download.csdn.net/download/anything14/87348329

1. Steps to create a Servlet project (Maven)

1. Create a Maven project

Create a Maven project with IDEA: Menu -> File -> New Project -> Maven

2. Introduce dependencies

After the Maven project is created, a pom.xml file will be automatically generated:

We need to introduce the jar packages that the Servlet API depends on in pom.xml.

1) Search for "servlet" in the central repository https://mvnrepository.com/:

2) Select the version, generally we use version 3.1.0 

Note: The version of Servlet must match Tomcat.
If we use Tomcat 8, then we need to use Servlet 3.1.0.
You can check the version correspondence at http://tomcat.apache.org/whichversion.html
 
3) Provide the central warehouse The xml is copied to the pom.xml of the project 

The jar package that the project depends on is placed inside the <dependencies> tag, and maven will automatically download the dependencies to the local:

3. Create a directory

When the project is created, IDEA will automatically create some directories for us:

src indicates the directory where the source code is located; main/java indicates the root directory of the source code, and the subsequent created .java files are placed in this directory; main/resources indicates the directory where some resource files of the project are located; test/java indicates the directory of the test code Root directory;

We also need to create some new directories/files:

1) Create a webapp directory

In the main directory, parallel to the java directory, create a webapp directory (note, not webapps)

2) Create web.xml

Then create a WEB-INF directory inside the webapp directory and create a web.xml file

3) Write web.xml

Copy the following code into 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>

Tomcat finds this file to correctly handle dynamic resources in webapp.

Then under webapp, add index.html at the same level as WEB-INF, which will be loaded directly at runtime.

Just write whatever you want

4. Write code

The following code is just an example:

Create a class HelloServlet in the java directory, the code is as follows:

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("hello");
    }
}

Note:
Create a class HelloServlet that inherits from HttpServlet.
Add the @WebServlet("/hello") annotation above this class, indicating that among the requests received by Tomcat, only the request whose path is /hello
will call the code of the HelloServlet class (this path does not include Context Path).
Override the doGet method. There are two parameters of doGet, which respectively represent the received HTTP request and the HTTP response to be constructed. This
method will be triggered when Tomcat receives a GET request.
HttpServletRequest represents an HTTP request.
Tomcat converts the request in string format into an HttpServletRequest object according to the HTTP request format . Subsequent requests to obtain information (method, url, header, body, etc.) are
obtained through this object.
HttpServletResponse represents an HTTP response. Construct the response object in the code (construct the response status code, header,
body, etc.).
resp.getWriter() will get a stream object, through which some data can be written, the written data will be constructed into the
body part of an HTTP response, Tomcat will convert the entire response into a string, and pass the socket Write back to the browser
.  

The current code does not use the main method as the entry point. The main method has been included in Tomcat, and the code we wrote will be called by Tomcat at the right time.
What conditions must the written class meet to be called by Tomcat?
a) The created class needs to inherit from HttpServlet
b) This class needs to use the @WebServlet annotation to associate an HTTP path
c) This class needs to implement the doXXX method.
When these three conditions are met, Tomcat can find this class, and call at the right time

5. Packager

Use maven for packaging: Menu -> View -> Tool Window -> Maven Open

Then expand Lifecycle, and double-click the package to package it.

There is an important point to note here: if we package directly like this, a jar package will be automatically generated, which is not what we need. What Tomcat needs to recognize is another war package format. The jar package is the result of ordinary java program packaging, which will contain some .class files. The war package is a java web program, which contains not only .class files, but also HTML, CSS, JavaScript, pictures, and other jar packages. It must be formatted as a war package to be recognized by Tomcat.

Add a packing tag in pom.xml, indicating that the packaging method is to make a war package. Add a build tag in pom.xml, and a built-in finalName tag, indicating that the name of the war package to be output is HelloServlet.

 6. Deployment program

Copy the war package to Tomcat's webapps directory; start Tomcat, and Tomcat will automatically decompress the war package.

 7. Verification procedure

At this time, visit http://127.0.0.1:8080/ServletHelloWorld/hello through the browser, and you can see the result.

Summarize

In this deployment link, there is an easier way, you can use the smart tomcat plug-in in IDEA to simplify packaging (packaging and deployment are integrated). Because the IDEA community edition does not have the deployment function of Tomcat, this needs to be done by using the smart tomcat plug-in.

The installation steps are as follows:

1) Menu -> File -> Settings

2) Select Plugins, select Marketplace, search for "tomcat", and click "Install"

3) After the installation is complete, it will prompt "restart IDEA"

 Configure the Smart Tomcat plugin:

0) Edit configuration


1) Click "+" in the upper left corner
2) Select "Smart Tomcat" on the left


3) Fill in a name in the Name column (you can write whatever you want),

Select the directory where Tomcat is located in the Tomcat Server column,

Other options do not need to be modified,

Among them, the default value of Context Path is the project name.


4) Click OK. Then the upper right corner becomes what it is now: 

 

Click the green triangle, and IDEA will automatically compile and deploy.

Notice:

Tomcat is not part of IDEA or in other words, it is not a function of IDEA. In IDEA, it can be run with one click, and the Tomcat log is displayed. This process is actually that the IDEA process calls the Tomcat process (process creation + program replacement), and IDEA redirects the output of Tomcat to its own terminal window. .

 The following is a servlet project I wrote, which can be downloaded if necessary:

https://download.csdn.net/download/anything14/87348329

おすすめ

転載: blog.csdn.net/anything14/article/details/128260136