您的位置:首页 > 其它

Servlet简述

2015-07-26 18:18 351 查看
Servlet生命周期

Servlet是一个继承了HttpServlet的类文件
servlet是服务器小应用程序
Servlet API为Servlet提供了统一的编程接口
Servlet一般在容器中运行
常见的Servlet容器Tomcat, Jetty / Resin

Servlet生命全过程: 指Servlet对象在服务器内存中从创建到调用,到销毁的整个过程
1: ClassLoader ---加载
2: new ---实例化:当客户端通过URL请求的时候,web容器根据web.xml配置自动调用该Servlet的构 造方法,实例化对象
3: init() ---初始化:通过该servlet对象调用init()方法,读取web.xml中该servlet的配置信息,为service方法提供相关数据
4: service ---处理请求通过该对象调用service()方法,如果是继承HttpServlet,则根据请求头信息中的请求方法,调用对应的doGet()/doPost()
5: destory() ---退出服务: 不是在service()方法调用完后,立即调用,而是由JVM来决定。当JVM需要销毁一些对象、释放内存空间的时候,才会去调用该实例的destroy()方法

想要运行Servlet,必须还需要配置一个web.xml文件

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//@WebServlet("/ServletLife") //----如果添加注解姐可以不用web.xml文件
public class ServletLife extends HttpServlet {

 public void init() throws ServletException {    //----初始化变量
    System.out.println("---init--");
 }

  protected void doGet(HttpServletRequest req, HttpServletResponse resp)    //----根据请求信息调用doGet()或者doPost()
   throws ServletException, IOException {
    System.out.println("----doGet()---");
 }

  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
System.out.println( "---dopost()----" );
      super.doPost(req, resp);       //----方法的调用
 }

 public void destroy() {          //-----退出服务
   System.out.println("----destroy()----");
 }
}

WEB.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
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">
<servlet>
<!--为了安全的需要,给要访问类文件去一个别名-->
<servlet-name>HS</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<!--为了安全的需要,给url路径建一个映射(取别名)-->
<servlet-name>HS</servlet-name>
<url-pattern>/abc</url-pattern>
</servlet-mapping>
</web-app>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: