当前位置:网站首页>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);
}
}边栏推荐
- 高等数学(第七版)同济大学 习题3-4 个人解答(前8题)
- 数据挖掘-01
- 简单、好用的性能测试工具推荐
- 巧用栈回溯,帮你快速定位问题
- Collection | 0 basic open source data visualization platform flyfish large screen development guide
- Web Security Foundation - Command Execution Vulnerability
- WordPress simple mkblog blog theme template v2.1
- Monotonous stack -- 42. Receiving rain -- a difficult problem that big factories must know
- CV2. Threshold(), CV2. Findcontours(), CV2. Findcontours image contour processing
- 常用的接口测试工具
猜你喜欢

leetcode刷题:动态规划08(分割等和子集)

Embedded development: tips and techniques -- the best practice of defensive programming with C

Interface automation test, complete introduction

【LeetCode】34、在排序数组中查找元素的第一个和最后一个位置

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

基于SSM实现在线租房系统

接口自动化测试,完整入门篇
![Error no matching function for call to 'std:: exception:: exception (const char [15])' problem solving](/img/d1/2fbdf42cf60b5382b5a35c64b172b9.png)
Error no matching function for call to 'std:: exception:: exception (const char [15])' problem solving

Fourier series

test case management tool
随机推荐
Msgan is used for pattern search of multiple image synthesis to generate confrontation Network -- to solve the problem of pattern collapse
conda虚拟环境总结与解读
Web Security Foundation - Command Execution Vulnerability
Input upload file and echo FileReader and restrict the type of file selection
Convert py file to exe executable file
Notes on writing questions in sword finger offer
Simple and easy-to-use performance testing tools recommended
input 上传文件并回显 FileReader并限制选择文件时的类型
[wrong question]mocha and railgun
[wrong question]
基于SSM实现在线租房系统
Recursion and non recursion are used to calculate the nth Fibonacci number respectively
高等数学(第七版)同济大学 习题3-4 个人解答(后8题)
In depth introduction to sap ui5 fileuploader control - why do you need a hidden iframe trial
WordPress简约mkBlog博客主题模板v2.1
【OPENVX】对象基本使用之vx_image
R notes mice
How to solve MySQL deep paging problem
面试必备杀技:SQL查询专项训练!
Selenium -- Web automated testing tool