当前位置:网站首页>Servlet usage
Servlet usage
2022-07-28 03:56:00 【Program three two lines】
summary
Is running on the web On the server java Program , Used to handle the front end ( client ) Responses and requests for
Life cycle
Servlet The object is tomcat Server created . By default, it is entered in the browser for the first time servlet Create this object when accessing , You can also create objects as soon as the server is started by configuring

Server down servlet It's destroyed
Use
Method
/**
* Run a project , When the server is turned on, it is not executed , Enter the address to access ,init()service() function ,
* Refresh once service Do it once , When shutting down the server tomcat When ,init()service() The destruction ,destroy perform
*/
public class DemoServlet implements Servlet {
//servlet When the object is created, execute ( Not at all tomcat When the server starts Is the access entered in the browser servlet Class time )
@Override
public void init(ServletConfig servletConfig) throws ServletException {
//ServletConfig Parameter function 1、 Get configuration information 2、 obtain xml Parameters in 3、 Get all parameter names 4、 obtain ServletContext object
servletConfig.getServletName();
servletConfig.getInitParameter("xxx");
servletConfig.getInitParameterNames();
servletConfig.getServletContext();
}
@Override
public ServletConfig getServletConfig() {
return null;
}
//ServletRequest : On behalf of request Think ServletRequest What's inside the package is http Requested information ,
// ServletResponse : For response It is believed that the information to be encapsulated is the response information
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
}
@Override
public String getServletInfo() {
return null;
}
//servlet Executed at the time of destruction
@Override
public void destroy() {
}
}
To configure

test
Browser input http://localhost:8080/web02---servlet practice /abc You can see it in the background servlet Content in method
Perform process analysis

Configuration instructions
url-pattern To configure

Default servlet
Can be url-pattern Configure as a /, On behalf of servlet It's the default servlet, When you access the resource address all servlet When none of them match , Default servlet Responsible for handling

overall situation web.xml

Static resource loading process

3.0 Time
Realization
from servlet3.0 From the beginning, you can directly use annotations to create servlet, direct new One servlet




// With this annotation There is no need to write configuration files , The content in brackets is in the address bar path What follows
@WebServlet("/myFirsetServlet")
public class MyFirsetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.service(req, resp);
}
}web.xml
metadata-complete Whether to scan annotations true Don't scan false scanning
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"
metadata-complete="false">
<absolute-ordering/>
<display-name>market</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>Calling procedure of internal method
Receive a servlet request ,tomcat Will find this servlet Corresponding service Method , without service Methods will go to the parent class
The following source code , The interior will ServletRequest Parameter conversion HttpServletRequest, After the conversion is completed, continue to call HttpServletRequest Of service Method , Call different methods according to different parameter types
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
HttpServletRequest request;
HttpServletResponse response;
try {
request = (HttpServletRequest)req;
response = (HttpServletResponse)res;
} catch (ClassCastException var6) {
throw new ServletException(lStrings.getString("http.non_http"));
}
this.service(request, response);
}
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getMethod();
long lastModified;
if (method.equals("GET")) {
lastModified = this.getLastModified(req);
if (lastModified == -1L) {
this.doGet(req, resp);
} else {
long ifModifiedSince;
try {
ifModifiedSince = req.getDateHeader("If-Modified-Since");
} catch (IllegalArgumentException var9) {
ifModifiedSince = -1L;
}
if (ifModifiedSince < lastModified / 1000L * 1000L) {
this.maybeSetLastModified(resp, lastModified);
this.doGet(req, resp);
} else {
resp.setStatus(304);
}
}
} else if (method.equals("HEAD")) {
lastModified = this.getLastModified(req);
this.maybeSetLastModified(resp, lastModified);
this.doHead(req, resp);
} else if (method.equals("POST")) {
this.doPost(req, resp);
} else if (method.equals("PUT")) {
this.doPut(req, resp);
} else if (method.equals("DELETE")) {
this.doDelete(req, resp);
} else if (method.equals("OPTIONS")) {
this.doOptions(req, resp);
} else if (method.equals("TRACE")) {
this.doTrace(req, resp);
} else {
String errMsg = lStrings.getString("http.method_not_implemented");
Object[] errArgs = new Object[]{method};
errMsg = MessageFormat.format(errMsg, errArgs);
resp.sendError(501, errMsg);
}
}边栏推荐
- [openvx] VX for basic use of objects_ convolution
- 高等数学(第七版)同济大学 习题3-6 个人解答
- Interface automation test, complete introduction
- 高等数学(第七版)同济大学 习题3-4 个人解答(后8题)
- conda虚拟环境总结与解读
- ES6 from entry to mastery 07: Deconstruction assignment
- Skillfully use stack backtracking to help you quickly locate problems
- 简单、好用的性能测试工具推荐
- 面试必备杀技:SQL查询专项训练!
- In depth introduction to sap ui5 fileuploader control - why do you need a hidden iframe trial
猜你喜欢
![[prototype and prototype chain] get to know prototype and prototype chain~](/img/8a/d6362fdd50dc883ff817a997ab9e1e.png)
[prototype and prototype chain] get to know prototype and prototype chain~

月薪28K学员 自动化测试经验分享

WordPress simple mkblog blog theme template v2.1

CH340 RTS DTR引脚编程驱动OLED

MySQL Basics (create, manage, add, delete, and modify tables)

Build an "industrial brain" and improve the park's operation, management and service capabilities with "digitalization"!
![[force deduction] 1337. Row K with the weakest combat effectiveness in the matrix](/img/6c/b5fd3350886fd74557439f5361e7f8.png)
[force deduction] 1337. Row K with the weakest combat effectiveness in the matrix

After 95, Alibaba P7 published the payroll: it's really heartbreaking

Implementation of online rental system based on SSM

Selenium--WEB自动化测试工具
随机推荐
CV2. Threshold(), CV2. Findcontours(), CV2. Findcontours image contour processing
C语言力扣第45题之跳跃游戏 II。遍历跳跃
ES6 from getting started to mastering 09: symbol type
[openvx] VX for basic use of objects_ image
LeetCode 0141. 环形链表 - 三种方法解决
AI chief architect 12 AICA Baidu OCR vertical large-scale landing practice
Selenium--WEB自动化测试工具
Error no matching function for call to 'std:: exception:: exception (const char [15])' problem solving
Advanced Mathematics (Seventh Edition) Tongji University exercises 3-6 personal solutions
Regression - linear regression
构建“产业大脑”,以“数字化”提升园区运营管理及服务能力!
Leetcode 0141. circular linked list - three solutions
程序人生 | 测试工程师还只会点点点?7个捷径教给你快速学习新技术...
基于SSM实现在线租房系统
数据挖掘-01
numeric_ Limits the range and related attributes of each data type learned
8000 word explanation of OBSA principle and application practice
[wrong question]mocha and railgun
超好用的 PC 端长截图工具
How does MySQL ensure high availability