java servlet的执行流程

时间:2021-12-11 15:18:24

1、先附上代码如下

Servlet1.java
public class Servlet1 implements Servlet {
@Override
public void init(ServletConfig config) throws ServletException { } @Override
public ServletConfig getServletConfig() {
return null;
} @Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
//返回到浏览器
res.getWriter().write("hello servlet"); } @Override
public String getServletInfo() {
return null;
} @Override
public void destroy() { }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
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_2_5.xsd">
<display-name></display-name> <servlet>
<!--定义一个serlvet-->
<servlet-name>servlet1</servlet-name>
<servlet-class>com.rookie.bigdata.Servlet1</servlet-class>
</servlet> <!--对servlet进行映射-->
<servlet-mapping>
<servlet-name>servlet1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

2、整体流程图如下:

java servlet的执行流程

3、针对上面代码的详细流程如下

1、启动tomact加载应用和web.xml文件

2、http访问程序 http://localhost:8080/servlet1,最终通过web.xml文件映射为com.rookie.bigdata.Servlet1

3、实例化Servlet1对象

4、调用Servlet1中的init方法

5、调用service方法接受浏览器请求