当前位置:网站首页>Web service connector: Servlet
Web service connector: Servlet
2022-07-06 05:51:00 【Ah, teacher Q】
summary
Servlet(Server Applet) yes Java Servlet For short , Called server applet or service connector . It runs on the server Java Applet , Platform - and protocol-independent , The main function is to interactively browse and generate data ( That is to realize the interaction between the front and back ends ), Generate dynamic Web Content .
Working principle diagram
among ,Tomcat Can pass HTTP Provide HTML Request access to static content such as pages ; It has also been realized. Servlet standard , Can run Servlet Program ; At the same time through Servlet Container call Servlet Processing dynamic requests , therefore Tomcat It can be Web Server or Servlet Container or Web Lightweight application servers .
Workflow
1) client ( It's usually a browser ) visit Web The server , send out HTTP request .
2)Web After the server receives the request , Pass request to Servlet Containers .
3)Servlet Container resolution request , load Servlet, meanwhile Servlet Containers create one HttpRequest Object and a HttpResponse object .HttpRequest Object encapsulates the passed request information .
4)Servlet Container call HttpServlet Object's service() Method , hold HttpRequest Object and the HttpResponse Object as a parameter to HttpServlet object .HttpServlet call HttpRequest Object about methods , obtain Http Request information ; call HttpResponse Object about methods , Generating response data .
5)Servlet Container handle HttpServlet The response result of is returned to Web The server .
Servlet Life cycle of
Servlet The life cycle of Servlet The process from Startup to shutdown , as follows :
- Load and instantiate : If Servlet The container has not instantiated one Servlet object , At this point, the container loads and instantiates a Servlet. If there is already one Servlet object , No new instances will be created at this time .
- initialization : Is producing Servlet After the instance , The container is responsible for calling the Servlet Example of init() Method , Yes Servlet To initialize .
- Response request : When Servlet The container received a Servlet When asked , Then run the corresponding Servlet Example of service() Method ,service() Method calls the corresponding doGet or doPost Method to handle user requests . Then enter the corresponding method to call the logical layer method , Response to customers .
- The destruction : When Servlet stay Web Execute before the application is uninstalled , Release Servlet Occupied computer resources .
Be careful :(1)(2)(4) stay Servlet It will only be executed once in the whole life cycle of .
The code is as follows ,ServletLifeCycle.java:
package com.edu.ServletStudy;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ServletLifeCycle implements Servlet {
public ServletLifeCycle() {
// The constructor is called , Create an instance object
System.out.println(" First step : Instance object ");
}
@Override
public void init(ServletConfig servletConfig) throws ServletException {
// Yes servlet To initialize , Only once
System.out.println(" The second step : initialization ");
}
@Override
public ServletConfig getServletConfig() {
// Return to one ServletConfig Object is used to return initialization parameters and ServletContext
return null;
}
@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
System.out.println(" The third step : Provide services ");
// Chinese code scrambling
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
// Information in response to the request
HttpServletResponse res = (HttpServletResponse)response ;
res.getWriter().write("Hello Servlet, I am Q teacher ");
}
@Override
public String getServletInfo() {
// Provide relevant servlet Information about
return null;
}
@Override
public void destroy() {
System.out.println(" The destruction ");
}
}
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-->
<servlet>
<!--servlet Internal name -->
<servlet-name>ServletLifeCycle</servlet-name>
<!--servlet The full name of the class -->
<servlet-class>com.edu.ServletStudy.ServletLifeCycle</servlet-class>
</servlet>
<!--servlet Mapping configuration -->
<servlet-mapping>
<!--servlet The internal name of , Keep consistent with the above -->
<servlet-name>ServletLifeCycle</servlet-name>
<!--servlet Mapping path for ( The address is usually action What's in it , Get data request )-->
<url-pattern>/ServletLifeCycle</url-pattern>
</servlet-mapping>
</web-app>
The operation is as shown in the figure : Console
page
When you click stop ,Servlet Will perform destroy() Method
ServletConfig object
ServletConfig Object is mainly used to configure servlet Is the initialization parameter of . The specific implementation is realized by Servlet Decided by the container developer . We use Tomcat For example .
The code is as follows ,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">
<servlet>
<servlet-name>ServletLifeCycle</servlet-name>
<servlet-class>com.edu.ServletStudy.ServletLifeCycle</servlet-class>
<!-- You can use one or more <init-param> Label configuration book Servlet Is the initialization parameter of -->
<init-param>
<!-- key -->
<param-name>username</param-name>
<!-- value -->
<param-value> ah Q teacher </param-value>
</init-param>
<init-param>
<param-name>pwd</param-name>
<param-value>123</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ServletLifeCycle</servlet-name>
<url-pattern>/ServletLifeCycle</url-pattern>
</servlet-mapping>
</web-app>
ServletLifeCycle.java:
package com.edu.ServletStudy;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
public class ServletLifeCycle implements Servlet {
@Override
// When Servlet Container initialization Servlet when ,Servlet The container will give Servlet Of init( ) Way to introduce a ServletConfig object
public void init(ServletConfig servletConfig) throws ServletException {
// Get configuration servlet Keys for all initialization parameters
Enumeration<String> enumeration = servletConfig.getInitParameterNames();
// Traverse the output keys and values
while (enumeration.hasMoreElements()){
String names = (String)enumeration.nextElement();
String values = servletConfig.getInitParameter(names); // obtain servlet Configuration initialization parameters
System.out.println("ParamName = " + names + "ParamValue = " + values);
}
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
}
The console is shown in the picture :
ServletContext object
ServletContext Is in Web When container starts , Every Web The application will create a corresponding ServletContext object ( Also known as Context object ). One Web All in the application Servlet Share the same ServletContext object , therefore Servlet Objects can pass through ServletContext Object to communicate .
ServletContext In the object , To configure Servlet Parameter is used context-param Tags can be shared ; And the above ServletConfig In the object , To configure Servlet Parameters can only be used in servlet Internal init-param label , Only Ben Servlet To obtain parameters .
The code is as follows ,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">
<!-- share Servlet Is the initialization parameter of -->
<context-param>
<param-name>username</param-name>
<param-value> ah Q teacher </param-value>
</context-param>
<context-param>
<param-name>pwd</param-name>
<param-value>123</param-value>
</context-param>
<servlet>
<servlet-name>ServletConextTest</servlet-name>
<servlet-class>com.edu.ServletStudy.ServletConextTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletConextTest</servlet-name>
<url-pattern>/ServletConextTest</url-pattern>
</servlet-mapping>
</web-app>
ServletConextTest.java:
package com.edu.ServletStudy;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
public class ServletConextTest implements Servlet {
public void init(ServletConfig servletConfig) throws ServletException {
// visit ServletContext
ServletContext context = servletConfig.getServletContext();
// Get configuration servlet Keys for all initialization parameters
Enumeration<String> paramNames = context.getInitParameterNames();
// Traverse the output keys and values
while (paramNames.hasMoreElements()) {
String name = paramNames.nextElement();
String value = context.getInitParameter(name);
System.out.println(name + " = " + value);
}
}
public ServletConfig getServletConfig() {
return null;
}
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
}
public String getServletInfo() {
return null;
}
public void destroy() {
}
}
HttpServlet
HttpServlet The purpose of this is to acquire HTTP request , Respond to HTTP result . stay IDEA Choose HttpServlet,“ctrl + Click the left mouse button ” Will jump to HttpServlet Class , At this time, you will find HttpServlet Abstract class GenericServlet Subclasses of . meanwhile ,HttpServlet Class is written doGet()、doPost()、doOptions()、doDelete() Other methods , They are corresponding to HTTP Medium Get、Post、Options、Delete Wait for those who request services .
Here is a brief introduction to commonly used doGet()、doPost() Method : There are two ways for forms to submit data to the server , namely < form action = “***” method= " get / post " > attribute method Medium get or post. They correspond to each other HttpServlet Of doGet()、doPost() Method .
doGet(): The data transmitted in this way will follow < key , value > The way in URL It shows , Low security .
doPost(): The data transmitted in this way is stored in HTTP In the message body of the protocol , It is transmitted to the server by entity . Package and send the data , High safety .
Servlet The implementation of the
Next , We went further to Servlet The implementation of the , obtain Register.html Parameters of page form submission .
stay web File directory to create Register.html, The code is as follows :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Servlet Study </title>
<link rel="stylesheet" type="text/css" href="CSS/Register.css">
</head>
<body>
<form action="http://localhost:8080/MSW/Register" method="post">
<h1>Welcome</h1>
<label> account number :</label>
<input type="text" name="username"/><br>
<label> password :</label>
<input type="password" name="pwd"/><br>
<label> Gender :</label>
<input type="radio" name="sex" value=" male "/> male
<input type="radio" name="sex" value=" Woman "/> Woman <br>
<label> Birthday :</label>
<select name="birthday">
<optgroup label=" Please select the year "> Please select the year </optgroup>
<option value="2000">2000</option>
<option value="2001">2001</option>
<option value="2002">2002</option>
</select><br>
<input type="submit" value=" notes book ">
<input type="reset" value=" heavy Set up ">
</form>
</body>
</html>
stay web/CSS Create under directory Register.css, The code is as follows :
body{
text-align:center;
background-color: antiquewhite;
}
stay src establish com.edu.ServletStudy package , To create a RegisterServlet.java, The code is as follows :
package com.edu.ServletStudy;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class RegisterServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Solve the garbled Chinese display of response results
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
// Data acquisition
String username = request.getParameter("username");
String pwd = request.getParameter("pwd");
String sex = request.getParameter("sex");
String birthdayStr = request.getParameter("birthday"); // Get data of string type
Integer birthday = Integer.parseInt(birthdayStr); // String to integer
// Print on the console
System.out.println("username = " + username);
System.out.println("pwd = " + pwd);
System.out.println("sex = " + sex);
System.out.println("birthday = " + birthday);
// Jump to print on the new page
response.getWriter().println(request.getParameter("username"));
response.getWriter().println(request.getParameter("pwd"));
response.getWriter().println(request.getParameter("sex"));
response.getWriter().println(Integer.parseInt(birthdayStr));
}
}
stay web/WEB-INF In the catalog web.xml, Add the following code :
<?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">
<!-- First , The user initiates a request ,action=Register; then Tomcat Medium web.xml Look first url-pattern = /Register, To servlet-mapping Medium servlet-name = RegisterServlet; Until then servlet Look for a match servlet-mapping Of servlet-name Of servlet; And find servlet-class Of com.edu.ServletStudy.RegisterServlet; Finally, because the user sent post request (method = post), therefore Tomcat perform doPost Method . -->
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>com.edu.ServletStudy.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/Register</url-pattern>
</servlet-mapping>
</web-app>
stay RegisterServlet.java Click on the run , The effect is as shown in the picture :
Console results :
Web results :
Solve the problems encountered in the implementation process
solve Address localhost:1099 is already in use The problem of
stay Intellij idea The running port appears Address localhost:1099 is already in use The problem of ( That is, the port is occupied ). The solution is :
1.win+R, Input cmd command , open dos Command line , Input netstat -ano | find “1099”, obtain PID ( That is, the last column of numbers )
2. adopt PID Find the process , Input :tasklist | find “ That column of figures ”
3. Finally, enter the command to close the process :taskkill /f /t /im java.exe
Pictured :
solve Servlet obtain radio The value of is on The problem of
Pictured :
The main reason for this problem may be There's something wrong with the code , Unrecognized get value .
The right code :
<input type="radio" name="sex" value=" male "/> male
<input type="radio" name="sex" value=" Woman "/> Woman <br>
IDEA Medium clean engineering
clean The function clears the cache in the project and reloads the verification .
The steps are shown in the figure :
1. Click on File—>Invalidate Caches / Restart…
2. Click on Invalidate and Restart, The cache will expire and be rebuilt the next time it starts , Local history will also be erased .
3.IDEA restart
边栏推荐
- [email protected]树莓派
- OSPF configuration command of Huawei equipment
- Sequoiadb Lake warehouse integrated distributed database, June 2022 issue
- Jushan database appears again in the gold fair to jointly build a new era of digital economy
- Deep learning -yolov5 introduction to actual combat click data set training
- PDK process library installation -csmc
- Migrate Infones to stm32
- First knowledge database
- Pay attention to the details of pytoch code, and it is easy to make mistakes
- Winter 2021 pat class B problem solution (C language)
猜你喜欢
华为路由器如何配置静态路由
29io stream, byte output stream continue write line feed
Practice sharing: how to safely and quickly migrate from CentOS to openeuler
数字经济破浪而来 ,LTD是权益独立的Web3.0网站?
Analysis report on development trends and investment planning of China's methanol industry from 2022 to 2028
Winter 2021 pat class B problem solution (C language)
Leetcode 701 insertion operation in binary search tree -- recursive method and iterative method
【课程笔记】编译原理
Redis消息队列
Processes and threads
随机推荐
B站刘二大人-多元逻辑回归 Lecture 7
Easy to understand IIC protocol explanation
Quantitative description of ANC noise reduction
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
[email protected] raspberry pie
Li Chuang EDA learning notes 12: common PCB board layout constraint principles
查詢生產訂單中某個(些)工作中心對應的標准文本碼
What is independent IP and how about independent IP host?
应用安全系列之三十七:日志注入
网络协议模型
H3C防火墙RBM+VRRP 组网配置
CoDeSys note 2: set coil and reset coil
P2802 回家
B站刘二大人-Softmx分类器及MNIST实现-Lecture 9
[Jiudu OJ 07] folding basket
Cannot build artifact 'test Web: War expanded' because it is included into a circular depend solution
Redis message queue
03. Login of development blog project
[email protected]树莓派
Jushan database appears again in the gold fair to jointly build a new era of digital economy