当前位置:网站首页>servlet使用
servlet使用
2022-07-28 03:54:00 【程序三两行】
概述
是运行在web服务器上的java程序,用来处理前端(客户端)的响应和请求
生命周期
Servlet对象是由tomcat服务器创建的。默认第一次浏览器中输入servlet访问时创建该对象,也可以通过配置服务器一启动就创建对象

服务器关闭servlet就销毁了
使用
方法
/**
* 运行一个项目,当开启服务器是都没有执行,输入地址访问,init()service()运行,
* 刷新一次service执行一次,当关闭服务器tomcat时候,init()service()销毁,destroy执行
*/
public class DemoServlet implements Servlet {
//servlet对象创建的时候执行(并不是tomcat服务器启动的时候 是在浏览器输入的访问servlet类的时候)
@Override
public void init(ServletConfig servletConfig) throws ServletException {
//ServletConfig参数作用 1、获取配置信息 2、获取xml中的参数 3、获取所有的参数名称 4、获取ServletContext对象
servletConfig.getServletName();
servletConfig.getInitParameter("xxx");
servletConfig.getInitParameterNames();
servletConfig.getServletContext();
}
@Override
public ServletConfig getServletConfig() {
return null;
}
//ServletRequest :代表请求 认为ServletRequest 内部封装的是http请求的信息,
// ServletResponse :代表响应 认为要封装的是响应的信息
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
}
@Override
public String getServletInfo() {
return null;
}
//servlet销毁的时候执行
@Override
public void destroy() {
}
}
配置

测试
浏览器输入http://localhost:8080/web02---servlet练习/abc后台就可以看到servlet方法中的内容
执行过程分析

配置说明
url-pattern配置

缺省的servlet
可以将url-pattern配置成一个/,代表该servlet是缺省的servlet,当你访问资源地址所有的servlet都不匹配时 , 缺省的servlet负责处理

全局web.xml

静态资源加载过程

3.0时代
实现
从servlet3.0开始就可以直接使用注解的方式创建servlet,直接new一个servlet




//有了这个注解 就不用再写配置文件,括号内容就是地址栏中path后面跟的内容
@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是否扫描注解 true不扫描 false扫描
<?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>内部方法的调用过程
收到一个servlet请求,tomcat会找到这个servlet对应的service方法,如果没有service方法就会到父类当中去找
如下源码,内部会把ServletRequest参数转成HttpServletRequest,转换完成后继续调用HttpServletRequest的service方法,根据不同的参数类型调用不同的方法
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);
}
}边栏推荐
- Skillfully use stack backtracking to help you quickly locate problems
- Advanced Mathematics (Seventh Edition) Tongji University exercises 3-6 personal solutions
- Analysis of static broadcast transmission process
- Weekly recommended short video: how to correctly understand the word "lean"?
- MangoPapa 的实用小脚本(目录篇)
- Day08 redis的基础知识
- Msgan is used for pattern search of multiple image synthesis to generate confrontation Network -- to solve the problem of pattern collapse
- 【原型与原型链】初识原型与原型链~
- MySQL Basics (create, manage, add, delete, and modify tables)
- LeetCode_409_最长回文串
猜你喜欢

【图像分类】2021-MLP-Mixer NIPS

Ch340 RTS DTR pin programming drives OLED

Day08 redis的基础知识

Build an "industrial brain" and improve the park's operation, management and service capabilities with "digitalization"!

数据挖掘-01

Implementation of online rental system based on SSM

Selenium -- Web automated testing tool

LabVIEW loads and uses custom symbols in tree control projects

【原型与原型链】初识原型与原型链~

《剑指offer》| 刷题小记
随机推荐
【P4】 查看库文件两个历史版本的区别
Convert py file to exe executable file
WordPress simple mkblog blog theme template v2.1
Data rich Computing: m.2 meets AI at the edge
Day08 redis的基础知识
leetcode刷题:动态规划09(最后一块石头的重量 II)
conda虚拟环境总结与解读
ES6 from entry to mastery 07: Deconstruction assignment
Practical scripts of mangopapa (contents)
Input upload file and echo FileReader and restrict the type of file selection
Super easy to use PC end long screenshot tool
Server memory failure prediction can actually do this!
【OPENVX】对象基本使用之vx_lut
【luogu P4590】游园会(DP套DP)
LeetCode_ 409_ Longest palindrome string
LabVIEW loads and uses custom symbols in tree control projects
Data mining-02
Skillfully use stack backtracking to help you quickly locate problems
A 404 page source code imitating win10 blue screen
Simple and easy-to-use performance testing tools recommended