Location>code7788 >text

Java Web Programming ---- Beginning Servlet

Popularity:588 ℃/2024-11-15 11:16:28

Jave Web is java oriented web development related technologies, he is the related technologies collectively, does not refer to a single technology.
In my previous blog (Java Web Programming ---- talk about the BIO model by implementing a simple chat tool /jilodream/p/), it has been written that java can be used as a server (e.g., TCP/UDP) to receive external requests. Such as the use of TCP to listen to the port, and then directly with the web page request the port, then the server will receive the relevant response, and then do a good job of business processing, return the response to the request can be. But the whole business process is too cumbersome. We not only have to deal with the business process, but also to control the request session, but also control the processing of various business branches, obviously this is not what we want.
So smart developers quickly thought of ----- decoupling , business people only need to write the relevant business can be , do not need to care about the tedious details of the network processing , so the birth of the servlet. developers only need to implement the servlet , and the servlet and the different path bindings. web request , forwarded directly by the system to the respective Servlet , and by the Servlet to deal with the relevant business can be.
What is a servlet, then?Server Applet(server application) shorthand, from the name we can see that it is designed to write server-side applications. We usually use it to handle the processing and response of http requests in the server.
It's a very old technology that has been around since the dawn of java, and many people don't even know what Servlets do. So the question is, why do we still need to learn and master Servlet? This is mainly due to Servlet is an important component of javaEE, java web development is an important cornerstone. We are now commonly used in the project Jsp, Springmvc, Springboot and other frameworks to deal with network requests in the core technology, is still Servlet. we do not need to continue to face the Servlet or more underlying technology for development, but Servlet exactly what kind of how to implement, and then the new technology to assume what kind of role, this is what we want to be familiar with the bottom of the Servlet. role, this is what we want to familiarize with the underlying principles must be mastered.

Without further ado, to use a Servlet, we need to do two steps:

1, write Servlet related business code
2, the business code is packaged and placed in Tomcat, Tomcat to load these Servlet

The first step is to try to write a servlet.
We first through IDEA to build a new web project, here we choose to use maven deployment, build a good project after the overall structure of the file hierarchy tree as follows(modal particle intensifying preceding clause)

E:.
├─.idea
├─.smarttomcat
│  └─PureJaveServlet
│      └─conf
└─src
    └─main
        ├─java
        │  └─org
        │      └─example
        ├─resources
        └─webapp

Among them:

resources Generally, we fill in the resource information, such as images, business configuration files, etc..
webapp will place html, css and other rendering files, but also put some web components (Servlet, Filter) configuration information. We just need to know the role here.
src/main/java is our business code. It is worth noting that we have to introduce the Servlet web programming related dependency packages to do the related web development. The default java SE does not include these development packages.
Before Servlet 4.0, we only use javax-related packages, and the future docking is Tomcat and below. (Anti-theft link: this article was first published from /jilodream/ )
After Servlet 5.0, we only use javax-related packages, and the future interface is Tomcat and later versions.
Here we use a high version to learn, i.e., the jakarta version, which will be needed for tomcat in the future.

Next the POM file is prepared:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="/POM/4.0.0"
 3          xmlns:xsi="http:///2001/XMLSchema-instance"
 4          xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.">
 5 <modelVersion>4.0.0</modelVersion>
 6 
 7 <groupId></groupId>
 8 <artifactId>PureJaveServlet</artifactId>
 9 <version>1.0-SNAPSHOT</version>
10 <name>PureJaveServlet</name>
11 <packaging>war</packaging>
12 
13 <properties>
14     <>UTF-8</>
15     <>11</>
16     <>11</>
17     <>5.9.2</>
18 </properties>
19 
20 <dependencies>
21     <dependency>
22         <groupId></groupId>
23         <artifactId>-api</artifactId>
24         <version>5.0.0</version>
25         <scope>provided</scope>
26     </dependency>
27     <dependency>
28         <groupId></groupId>
29         <artifactId>junit-jupiter-api</artifactId>
30         <version>${}</version>
31         <scope>test</scope>
32     </dependency>
33     <dependency>
34         <groupId></groupId>
35         <artifactId>junit-jupiter-engine</artifactId>
36         <version>${}</version>
37         <scope>test</scope>
38     </dependency>
39     <dependency>
40         <groupId></groupId>
41         <artifactId>lombok</artifactId>
42         <version>1.18.30</version>
43     </dependency>
44     <dependency>
45         <groupId></groupId>
46         <artifactId>commons-lang3</artifactId>
47         <version>3.13.0</version>
48     </dependency>
49     <!-- http client-->
50     <!-- fastjson -->
51     <dependency>
52         <groupId></groupId>
53         <artifactId>fastjson</artifactId>
54         <version>1.2.83</version>
55     </dependency>
56 
57 
58     <dependency>
59         <groupId></groupId>
60         <artifactId>jackson-databind</artifactId>
61         <version>2.10.0</version>
62     </dependency>
63     <dependency>
64         <groupId></groupId>
65         <artifactId>pebble</artifactId>
66         <version>3.1.6</version>
67     </dependency>
68     <dependency>
69         <groupId></groupId>
70         <artifactId>maven-compiler-plugin</artifactId>
71         <version>3.10.1</version>
72     </dependency>
73 
74 </dependencies>
75 
76 <build>
77     <plugins>
78         <plugin>
79             <groupId></groupId>
80             <artifactId>maven-war-plugin</artifactId>
81             <version>3.3.2</version>
82         </plugin>
83         <plugin>
84             <groupId></groupId>
85             <artifactId>maven-compiler-plugin</artifactId>
86             <configuration>
87                 <compilerArgs>
88                     <arg>-parameters</arg>
89                 </compilerArgs>
90             </configuration>
91         </plugin>
92     </plugins>
93 </build>
94 </project>

Servlet class

 1 package ;
 2 
 3 
 4 import ;
 5 import ;
 6 import ;
 7 import ;
 8 import ;
 9 
10 import ;
11 import ;
12 
13 
14 @WebServlet(urlPatterns = "/nihao")
15 public class HiServlet extends HttpServlet {
16     @Override
17     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws  IOException {
18         String name = ("name");
19         ("text/html");
20         PrintWriter out = ();
21         ("<html><body>");
22         (("<h1>Hello, %s </h1>", name));
23         ("</body></html>");
24         ();
25     }
26 }

 

 1 package ;
 2 
 3 import ;
 4 import ;
 5 import ;
 6 import ;
 7 
 8 import ;
 9 import ;
10 
11 /**
12  * @discription
13  */
14 @WebServlet(urlPatterns = "/bye")
15 public class ByeServlet extends HttpServlet {
16     @Override
17     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
18         String name = ("name");
19         ("text/html");
20         PrintWriter out = ();
21         ("<html><body>");
22         (("<h1>bye bye, %s </h1>", name));
23         ("</body></html>");
24         ();
25     }
26 }

That concludes the code section, and we can see two things when we look at the code:
1, all Sevlet should be inherited from HttpServlet. HttpServlet is an abstract class, we need to rewrite the abstract methods in the abstract class to ensure that the future Tomcat and other web servers in the loading of Servlet, you can follow a unified specification to find the execution.
We override the doGet() method in the servlet to indicate that it handles get requests under that servlet path, and similarly doPost doDelete doPut and other methods can be overridden to handle the corresponding request type.
Here we're simple and just return a piece of responsive html.
2, we do not write the main method, but in the Pom to mark our project needs to be packaged into a war package.
Step 2: Configure tomcat
Without the main method, how do we start our java program? We usually configure it to the specified path of tomcat, after starting tomcat, tomcat will load the war package servlet related classes for processing.
So we would call a web server like tomcat a Servlet container.
We first download a version of tomcat from the official tomcat website (/) that matches our corresponding servlet version.

Just unzip it after downloading it locally.
Then we download a smart tomcat component in IDEA for convenience, and associate the component with the servlet code and tomcat server.
The key configurations are as follows:
Tomcat server: Select the tomcat server we downloaded, if there is no drop down option then select "Congure...". Add it manually.
Deployment dirctory: deployment folder, (anti-theft link: this article was first published from /jilodream/ ) This configuration points to the webapp of the previous project structure tree species.
Use classpath of module: select the current project
Context path: select the context path (in fact, is the url prefix path), in accordance with the rules of the url randomly fill in, I'm called here to fill in the /biubiubiu
server port: Servlet's server port, default is 8080.
admin port: tomcat management port default fill 8005, is generally used to stop tomcat (in fact, generally do not use).
After that we pass IDEA: pull up tomcat and load servlet related classes and resources.

The command line input is as follows:

....
15-Nov-2024 10:34:38.099 text [main] Start protocol processing handle["http-nio-8080"] 15-Nov-2024 10:34:39.831 text [main] [4858] milliseconds after the server starts http.//localhost:8080/biubiubiu

The execution effect is as follows:

Some people may find it a bit cumbersome to download and configure tomcat, and even more so if we want to debug the code, is there an easier way:
In fact, in addition to downloading tomcat, we can also directly pull up tomcat through the form of code. the idea is as follows:
First of all, load the corresponding tomcat dependencies through maven, and then create a tomcat instance in the main method, and specify the configuration information required by tomcat, such as resources and class path. Then start the tomcat instance through the start() method.
The code is as follows:

Build a new java web project, Servlet class and project structure we keep the same or the same as the original

POM file

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="/POM/4.0.0"
 3          xmlns:xsi="http:///2001/XMLSchema-instance"
 4          xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.">
 5     <modelVersion>4.0.0</modelVersion>
 6 
 7     <groupId></groupId>
 8     <artifactId>demotom</artifactId>
 9     <version>1.0-SNAPSHOT</version>
10     <name>demotom</name>
11     <packaging>war</packaging>
12 
13     <properties>
14         <>UTF-8</>
15         <>11</>
16         <>11</>
17         <>10.0.0</>
18     </properties>
19 
20     <dependencies>
21 
22 
23         <dependency>
24             <groupId></groupId>
25             <artifactId>tomcat-embed-core</artifactId>
26             <version>${}</version>
27             <scope>provided</scope>
28         </dependency>
29         <dependency>
30             <groupId></groupId>
31             <artifactId>tomcat-embed-jasper</artifactId>
32             <version>${}</version>
33             <scope>provided</scope>
34         </dependency>
35     </dependencies>
36 
37     <build>
38         <plugins>
39             <plugin>
40                 <groupId></groupId>
41                 <artifactId>maven-war-plugin</artifactId>
42                 <version>3.3.2</version>
43             </plugin>
44         </plugins>
45     </build>
46 </project>

Main Category:

 1 package ;
 2 
 3 import ;
 4 import ;
 5 import ;
 6 import ;
 7 import ;
 8 import ;
 9 
10 import ;
11 
12 /**
13  * @discription
14  */
15 public class TomMain {
16     public static void main(String[] args) throws LifecycleException {
17         Tomcat tomcat = new Tomcat();
18         (("port", 8080));
19         ();
20         String docBase = new File("src/main/webapp").getAbsolutePath();
21         Context ctx = ("", docBase);
22         WebResourceRoot resources = new StandardRoot(ctx);
23         String base = new File("target/classes").getAbsolutePath();
24         (new DirResourceSet(resources, "/WEB-INF/classes", base, "/"));
25         (resources);
26         ();
27         ().await();
28     }
29 }

The console output after startup is as follows, and we can see that port 8080 has been listened to:

"C:\Program Files\Java\jdk-11\bin\" -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:51854,suspend=y,server=n -=UTF-8 -classpath ....
Connected to the target VM, address: '127.0.0.1:51854', transport: 'socket'
11moon 15, 2024 10:47:54 morning init
text: Initializing ProtocolHandler ["http-nio-8080"]
11moon 15, 2024 10:47:54 morning startInternal
text: Starting service [Tomcat]
11moon 15, 2024 10:47:54 morning startInternal
text: Starting Servlet engine: [Apache Tomcat/10.0.0]
11moon 15, 2024 10:47:56 morning createSecureRandom
warnings: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [1,753] milliseconds.
11moon 15, 2024 10:47:56 morning start
text: Starting ProtocolHandler ["http-nio-8080"]