当前位置:网站首页>Complete solution of servlet: inheritance relationship, life cycle, container, request forwarding and redirection, etc
Complete solution of servlet: inheritance relationship, life cycle, container, request forwarding and redirection, etc
2022-07-02 09:08:00 【Programmer Qiqi】
One 、Servlet summary
1、Servlet name
Servlet = Server + applet
Server: The server applet: Applet Servlet: Server side applet
2、Servlet stay Web Role in application
① Examples in life

② Corresponding Web application

③ Specific details

④Servlet Play a role Throughout Web Application ,Servlet Mainly responsible for processing requests 、 Coordination and dispatching function . We can Servlet be called Web In application 『 controller 』
Two 、Servlet HelloWorld
1、HelloWorld analysis
① The goal is Click the hyperlink on the page , from Servlet Process this request , And return a response string :Hello,I am Servlet! .
② Ideas

2、 Specific operation
① Create dynamic Web Module 《 Step on the pit + Demining new edition IDEA2021.1 Create a configuration Javaweb Project and deploy in Tomcat Containers 》
② Create front page hyperlinks begin.html The code for is as follows :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="hello"> Please click on me </a>
</body>
</html>
Copy code ③ establish HelloServlet Of Java class
package com.yeman.Servlets;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @Author: Yeman
* @Date: 2022-02-11-18:15
* @Description:
*/
public class Hello extends HttpServlet {
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
System.out.println(" Yes Hello This Servlet!");
// Returns the response string
// 1、 Gets a character stream object that can return response data
PrintWriter writer = res.getWriter();
// 2、 Write data to the character stream object
writer.write("Hello,I am Servlet!");
}
}
Copy code ④ To configure Hello Servlet Profile location :WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- To configure Servlet In itself -->
<servlet>
<!-- to Servlet Set a short name -->
<servlet-name>Hello</servlet-name>
<!-- To configure Servlet Full class name of -->
<servlet-class>com.yeman.Servlets.Hello</servlet-class>
</servlet>
<!-- take Servlet Associated with the access address -->
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
Copy code ⑤ test

⑥ Summary demand : Click the hyperlink on the browser to access Java Program .

3、 Combing concepts
① Native Tomcat

②IDEA Medium Tomcat example

③IDEA Medium Web engineering

④ according to Web Project generated war package

⑤Web Resources in the project [1] Static resources
- HTML file
- CSS file
- JavaScript file
- Picture file
[2] Dynamic resources
- Servlet
⑥ The address of the access resource [1] Static resources
/Web apply name / The path of the static resource itself
[2] Dynamic resources
/Web apply name / Virtual path
⑦Web apply name

⑧ The overall logical structure

3、 ... and 、Servlet Inheritance relationships
1、 Inheritance relationships
javax.servlet.Servlet Interface ----->
javax.servlet.GenericServlet abstract class ----->javax.servlet.http.HttpServlet Abstract subclass

2、 Related methods

①javax.servlet.Servlet Interface :
- void init(config) - Initialization method
- void service(request,response) - The service method
- void destory() - Destruction method
②
javax.servlet.GenericServlet abstract class :
- void service(request,response) - Still abstract
③
javax.servlet.http.HttpServlet Abstract subclass :
- void service(request,response) - It's not abstract
String method = req.getMethod(); How to get the request Various if Judge , Depending on the way of request , Decide to call different do Method :
if (method.equals("GET")) {
this.doGet(req,resp);
} else if (method.equals("HEAD")) {
this.doHead(req, resp);
} else if (method.equals("POST")) {
this.doPost(req, resp);
} else if (method.equals("PUT")) {
......
Copy code stay HttpServlet In this abstract class ,do The methods are almost the same :
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_get_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(405, msg);
} else {
resp.sendError(400, msg);
}
}
Copy code 3、 Summary
① Inheritance relationships : HttpServlet -> GenericServlet -> Servlet
②Servlet The core approach in :init(),service(),destroy()
③ The service method : When a request comes ,service Method will automatically respond ( It's actually tomcat Container called ).
④ stay HttpServlet The method of the request will be analyzed in : What is the get、post、head still delete etc. , Then decide which one to call do Opening method .
⑤ stay HttpServlet Medium do The default method is 405 The implementation style of , Subclasses are required to implement the corresponding methods , Otherwise, it will report by default 405 error . therefore , We're building Servlet when , The request method needs to be considered , To decide which one to rewrite do Method .
Four 、Servlet Life cycle
1、 Life cycle
The process from birth to death is the life cycle . Corresponding Servlet Three methods in init(),service(),destroy().
By default : The first time you receive a request , This Servlet Instantiate ( Call constructor )、 initialization ( call init())、 And then service ( call service()). Start with the second request , Every time it's a service . When the container is closed , All of them servlet The instance will be destroyed , Call destroy method .
Servlet example Tomcat Only one will be created , All requests are answered by this instance . By default , On the first request ,Tomcat To instantiate , initialization , Then serve . The advantage of this is that it can improve the startup speed of the system , The drawback is that the first request takes a long time . So come to the conclusion : If you need to improve the startup speed of the system , The current default is OK , If you need to improve response speed , It should be set up Servlet Initialization time of .
2、 Initialization time
We can go through <load-on-startup> To set up servlet Order of start up , The smaller the number is. , Start more forward , minimum value 0. It can be instantiated and initialized when the system starts , Improve post response speed .
modify web.xml in Servlet Configuration of :
<!-- To configure Servlet In itself -->
<servlet>
<!-- The full class name is too long , to Servlet Set a short name -->
<servlet-name>HelloServlet</servlet-name>
<!-- To configure Servlet Full class name of -->
<servlet-class>com.yeman.servlet.HelloServlet</servlet-class>
<!-- To configure Servlet Startup sequence -->
<load-on-startup>1</load-on-startup>
</servlet>
Copy code 3、Servlet Containers
① Containers Among various technologies developed and used , There are often many objects placed in containers .
② Functions provided by the container The container manages the entire lifecycle of the internal objects . Objects can only work properly in containers , Get full support from the container .
- Create objects
- initialization
- Work
- clear
③ The container itself is also an object characteristic 1: Often very large objects characteristic 2: Usual singleton
④ A typical Servlet Examples of container products Tomcat、jetty、jboss、Weblogic、WebSphere、glassfish
⑤Servlet In the container is : The singleton 、 Thread unsafe .
Single case : All requests are answered by the same instance Thread unsafe : A thread needs to make logical judgment according to the value of a member variable in this instance , But at some point in the middle , Another thread changed the value of the member variable , This causes the execution path of the first thread to change .
Be careful : Try not to be in servlet Define member variables in , If you have to define member variables , Then don't go :① Change the value of the member variable ② Make some logical judgments according to the value of member variables .
4、 Summary

5、 ... and 、ServletConfig and ServletContext
1、ServletConfig Interface
① An overview of the interface

② Interface method

③ Examples of initialization parameters
<!-- To configure Servlet In itself -->
<servlet>
<!-- The full class name is too long , to Servlet Set a short name -->
<servlet-name>HelloServlet</servlet-name>
<!-- To configure Servlet Full class name of -->
<servlet-class>com.yeman.servlet.HelloServlet</servlet-class>
<!-- Configure initialization parameters -->
<init-param>
<param-name>goodMan</param-name>
<param-value>me</param-value>
</init-param>
<!-- To configure Servlet Startup sequence -->
<load-on-startup>1</load-on-startup>
</servlet>
Copy code ④ Experience
public class HelloServlet implements Servlet {
// Declare a member variable , For reception init() Method passed in servletConfig object
private ServletConfig servletConfig;
public HelloServlet(){
System.out.println("HelloServlet objects creating !");
}
@Override
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("HelloServlet Object initialization ");
// take Tomcat call init() Method servletConfig Object is assigned to a member variable
this.servletConfig = servletConfig;
}
@Override
public ServletConfig getServletConfig() {
// Returns the member variable servletConfig, Easy to use
return this.servletConfig;
}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
// Console printing , Prove that this method was called
System.out.println(" I am a HelloServlet, I did !");
// Returns the response string
// 1、 Gets a character stream object that can return response data
PrintWriter writer = servletResponse.getWriter();
// 2、 Write data to the character stream object
writer.write("Hello,I am Servlet!");
// ============= Split line ===============
// test ServletConfig Use of objects
// 1. obtain ServletConfig object : stay init() Method
System.out.println("servletConfig = " + servletConfig.getClass().getName());
// 2. adopt servletConfig Object acquisition ServletContext object
ServletContext servletContext = this.servletConfig.getServletContext();
System.out.println("servletContext = " + servletContext.getClass().getName());
// 3. adopt servletConfig Object to get initialization parameters
Enumeration<String> enumeration = this.servletConfig.getInitParameterNames();
while (enumeration.hasMoreElements()) {
String name = enumeration.nextElement();
System.out.println("name = " + name);
String value = this.servletConfig.getInitParameter(name);
System.out.println("value = " + value);
}
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
System.out.println("HelloServlet The object is about to be destroyed , Now perform the cleanup operation ");
}
}
Copy code ⑤Servlet Standards and JDBC Standard comparison : In a broad sense Servlet:javax.servlet A set of interface definitions under a package Web Development standards . Follow this set of standards , Different Servlet Containers provide different implementations . narrow sense Servlet:javax.servlet.Servlet Interface and its implementation class , That is, the specific Servlet.

It also embodies the idea of interface oriented programming , It also embodies the idea of decoupling : As long as the interface doesn't change , Any changes to the underlying method , Will not affect the upper level methods .

2、ServletContext Interface
① brief introduction
On behalf of the entire Web application , It's a singleton .
Typical functions :
- Get the real path of a resource :getRealPath()
- Get the entire Web Application level initialization parameters :getInitParameter()
- As Web Domain object of application scope
In the data :setAttribute() Take out the data :getAttribute(
② Experience [1] To configure Web Application level initialization parameters
<!-- To configure Web Application initialization parameters -->
<context-param>
<param-name>handsomeMan</param-name>
<param-value>alsoMe</param-value>
</context-param>
Copy code [2] To obtain parameters
String handsomeMan = servletContext.getInitParameter("handsomeMan");
System.out.println("handsomeMan = " + handsomeMan);
Copy code 6、 ... and 、 Request forwarding and redirection
1、 The relay
Send a request to Servlet, The baton passed to Servlet In the hands of . And in most cases ,Servlet Can't do everything alone , The baton needs to be passed on , At this point we need to request 『 forward 』 or 『 Redirect 』.
2、 forward
① The essence : Hand over
② Complete definition : During the processing of the request ,Servlet Completed their own tasks , The request needs to be forwarded to the next Servlet To continue processing .

③ Code
request.getRequestDispatcher("/fruit/apple/red/big.html").forward(request, response);
Copy code ④ analogy

The key : Because the core part of the forwarding operation is completed on the server side , So the browser is not aware of , The browser only sends the request once in the whole process .

3、 Redirect
① The essence : A special response
② Complete definition : During the processing of the request ,Servlet Completed their own tasks , Then tell the browser in a response way : To complete this task, you need to access the next resource ”.

③ Code
response.sendRedirect("/app/fruit/apple/red/big.html");
Copy code 
The key : Because the core part of the redirection operation is completed on the browser side , So the browser sends two requests during the whole process .
4、 contrast

5、 Application scenarios
It's easy to judge : If you can use forwarding, use forwarding first , If forwarding fails , Then use redirection .
Need to pass through the same request Object to carry data to the target resource : Only forward .
If you want to go to the next resource , Browser refresh accesses the second resource : You can only use redirection .
7、 ... and 、 Get request parameters
1、 The concept of request parameters
The browser sends a request to the server at the same time , Carried parameter data .
2、 The browser sends the basic form of request parameters
- URL Request parameters attached after address
/orange/CharacterServlet?username=Tom
- Forms
- Ajax request
3、 Server encapsulation of request parameters
In general , The server encapsulates the request parameters as Map<String, String[]>.
key : The name of the request parameter value : An array of request parameter values
4、 Method to get request parameters

5、 test
①HTML Code
<!-- Form for testing request parameters -->
<form action="/orange/ParamServlet" method="post">
<!-- Single line text box -->
<!-- input Label fit type="text" Property to generate a single line text box -->
<!-- name Property defines the name of the request parameter -->
<!-- If set value attribute , Then this value is the default value of the single line text box -->
Individuality signature :<input type="text" name="signal" value=" The default value for a single line text box " /><br/>
<!-- Password box -->
<!-- input Label fit type="password" Property to generate a password box -->
<!-- The content filled in by the user in the password box will not be displayed in clear text -->
password :<input type="password" name="secret" /><br/>
<!-- Radio buttons -->
<!-- input Label fit type="radio" Property to generate a radio box -->
<!-- name Property consistent radio Will be recognized by the browser as the same set of radio boxes , Only one... Can be selected in the same group -->
<!-- After submitting the form , What is really sent to the server is name Properties and value The value of the property -->
<!-- Use checked="checked" Property settings are selected by default -->
Please choose your favorite season :
<input type="radio" name="season" value="spring" /> spring
<input type="radio" name="season" value="summer" checked="checked" /> summer
<input type="radio" name="season" value="autumn" /> autumn
<input type="radio" name="season" value="winter" /> winter
<br/><br/>
Your favorite animal is :
<input type="radio" name="animal" value="tiger" /> Land rover
<input type="radio" name="animal" value="horse" checked="checked" /> BMW
<input type="radio" name="animal" value="cheetah" /> jaguar
<br/>
<!-- Checkbox -->
<!-- input Labels and type="checkbox" Cooperate to generate multiple selection boxes -->
<!-- After multiple selection boxes are selected by the user and the form is submitted, a 『 A name carries multiple values 』 The situation of -->
Your favorite team is :
<input type="checkbox" name="team" value="Brazil"/> Brazil
<input type="checkbox" name="team" value="German" checked="checked"/> Germany
<input type="checkbox" name="team" value="France"/> The French
<input type="checkbox" name="team" value="China" checked="checked"/> China
<input type="checkbox" name="team" value="Italian"/> Italy
<br/>
<!-- The drop-down list -->
<!-- Use select Label definition drop-down list , stay select In label settings name attribute -->
Your favorite sport is :
<select name="sport">
<!-- Use option Property defines the list item of the drop-down list -->
<!-- Use option Labeled value Property to set the value submitted to the server , stay option The value set to the user in the label body of the label -->
<option value="swimming"> swimming </option>
<option value="running"> running </option>
<!-- Use option Labeled selected="selected" Property setting this list item is selected by default -->
<option value="shooting" selected="selected"> Shooting </option>
<option value="skating"> skating </option>
</select>
<br/>
<br/><br/>
<!-- Form hidden fields -->
<!-- input Labels and type="hidden" Cooperate to generate form hidden fields -->
<!-- Form hidden fields will not be displayed on the page , Used to save data to be submitted to the server but do not want users to see -->
<input type="hidden" name="userId" value="234654745" />
<!-- Multi-line text box -->
Self introduction. :<textarea name="desc"> The default value for multiline text boxes </textarea>
<br/>
<!-- General button -->
<button type="button"> General button </button>
<!-- Reset button -->
<button type="reset"> Reset button </button>
<!-- Form submit button -->
<button type="submit"> Submit button </button>
</form>
Copy code ②Java Code
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Get the... That contains all the request parameters Map
Map<String, String[]> parameterMap = request.getParameterMap();
// Iterate through the... That contains all the request parameters Map
Set<String> keySet = parameterMap.keySet();
for (String key : keySet) {
String[] values = parameterMap.get(key);
System.out.println(key + "=" + Arrays.asList(values));
}
System.out.println("---------------------------");
// Obtain the specified request parameter value according to the request parameter name
// getParameter() Method : Get the request parameters of the radio box
String season = request.getParameter("season");
System.out.println("season = " + season);
// getParameter() Method : Get the request parameters of multiple selection boxes
// Only the first of multiple values can be obtained
String team = request.getParameter("team");
System.out.println("team = " + team);
// getParameterValues() Method : Take the request parameters of the radio box
String[] seasons = request.getParameterValues("season");
System.out.println("Arrays.asList(seasons) = " + Arrays.asList(seasons));
// getParameterValues() Method : Take the request parameters of multiple selection boxes
String[] teams = request.getParameterValues("team");
System.out.println("Arrays.asList(teams) = " + Arrays.asList(teams));
}边栏推荐
- [staff] time sign and note duration (full note | half note | quarter note | eighth note | sixteenth note | thirty second note)
- Qt——如何在QWidget中设置阴影效果
- First week of JS study
- C # save web pages as pictures (using WebBrowser)
- Npoi export word font size correspondence
- 汉诺塔问题的求解与分析
- Qt QTimer类
- C language - Blue Bridge Cup - 7 segment code
- Redis安装部署(Windows/Linux)
- 一个经典约瑟夫问题的分析与解答
猜你喜欢

Dix ans d'expérience dans le développement de programmeurs vous disent quelles compétences de base vous manquez encore?

Redis安装部署(Windows/Linux)

Minecraft group service opening
![[blackmail virus data recovery] suffix Rook3 blackmail virus](/img/46/debc848d17767d021f3f41924cccfe.jpg)
[blackmail virus data recovery] suffix Rook3 blackmail virus

查看was发布的应用程序的端口

Win10 uses docker to pull the redis image and reports an error read only file system: unknown

【Go实战基础】gin 高效神器,如何将参数绑定到结构体

Service de groupe minecraft

京东面试官问:LEFT JOIN关联表中用ON还是WHERE跟条件有什么区别

【Go实战基础】如何安装和使用 gin
随机推荐
Cloud computing in my eyes - PAAS (platform as a service)
Data type case of machine learning -- using data to distinguish men and women based on Naive Bayesian method
Linux安装Oracle Database 19c RAC
Openshift container platform community okd 4.10.0 deployment
How to realize asynchronous programming in a synchronous way?
【Go实战基础】gin 高效神器,如何将参数绑定到结构体
Minecraft安装资源包
2022/2/14 summary
机器学习之数据类型案例——基于朴素贝叶斯法,用数据辩男女
【Go实战基础】gin 如何绑定与使用 url 参数
MYSQL安装出现问题(The service already exists)
oracle删除表空间及用户
Analysis and solution of a classical Joseph problem
Installing Oracle database 19C RAC on Linux
[staff] the lines and spaces of the staff (the nth line and the nth space in the staff | the plus N line and the plus N space on the staff | the plus N line and the plus N space below the staff | the
Mysql安装时mysqld.exe报`应用程序无法正常启动(0xc000007b)`
Npoi export word font size correspondence
聊聊消息队列高性能的秘密——零拷贝技术
Oracle修改表空间名称以及数据文件
统计字符串中各类字符的个数