各个Servlet版本
https://www.cnblogs.com/Jimc/...
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_3_1.xsd"
         version="3.1" metadata-complete="false">

</web-app>

其中metadata-complete="false"表示支持servlet3.0注解

Servlet解析笔记

Servlet(Server Applet)是Java Servlet的简称,称为小服务程序或服务连接器,用Java编写的服务器端程序,具有独立于平台和协议的特性,主要功能在于交互式地浏览和生成数据,生成动态Web内容,Servlet的常见类型有,继承自Httpservlet的普通Servlet类、Servlet过滤器、Servlet监听器

1.Servlet的生命周期


装载和创建Servlet实例 》 初始化 》 执行 》 服务结束

2.代码实现

//Servlet的生命周期:从Servlet被创建到Servlet被销毁的过程
/*
 * 1.实例化(使用构造方法创建对象)
 * 2.初始化  执行init方法
 * 3.服务    执行service方法
 * 4.销毁    执行destroy方法
 */
public class ServletDemo implements Servlet {

    //public ServletDemo(){}

     //生命周期方法:当Servlet第一次被创建对象时执行该方法,该方法在整个生命周期中只执行一次
    public void init(ServletConfig arg0) throws ServletException {
                System.out.println("=======init=========");
        }

    //生命周期方法:对客户端响应的方法,该方法会被执行多次,每次请求该servlet都会执行该方法
    public void service(ServletRequest arg0, ServletResponse arg1)
            throws ServletException, IOException {
        System.out.println("Service is working!");

    }

    //生命周期方法:当Servlet被销毁时执行该方法
    public void destroy() {
        System.out.println("******destroy**********");
    }
    //当停止tomcat时也就销毁的servlet。
    public ServletConfig getServletConfig() {
        return null;
    }

    public String getServletInfo() {
        return null;
    }
    
    //实际开发中最常见的doGet和doPost方法
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("doget method");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("dopost method");
        doGet(req,resp);
    }
}

3.Servlet配置文件web.xml


web.xml配置文件如下

<servlet>
  <servlet-name>ServletDemo</servlet-name>
  <servlet-class>ServletDemo</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>ServletDemo</servlet-name>
  <url-pattern>/ServletDemo</url-pattern>
</servlet-mapping>

Servlet使用请求转发

request.getRequestDispatcher("/test.jsp").forword(request,response); 

Servlet使用重定向

response.sendRedirect("test.jsp");

默认情况下优先使用请求转发

引用:

servlet百度定义https://baike.baidu.com/item/...

Cheryl
13 声望0 粉丝

Java技术栈 [链接]