温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Servlet详解

发布时间:2020-07-21 19:52:08 来源:网络 阅读:769 作者:mirindaRain 栏目:编程语言

为什么要学习Servlet

早期请求的jsp实际上就是一个java类,这个类到底是什么呢?

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
</head>
<body>
<%
    out.println("helloworld");
%>
</body>
</html>

以上jsp生成的部分代码如下

public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {}

发现HttpJspBese这个类的继承结构如下:

public abstract class org.apache.jasper.runtime.HttpJspBase extends javax.servlet.http.HttpServlet implements javax.servlet.jsp.HttpJspPage {}

总结:javax.servlet.http.HttpServlet就是Servlet的核心类,请求一个jsp页面实际上就是请求一个Servlet

什么是Servlet

Servlet 是一个 Java程序,是在服务器上运行以处理客户端请求并做出响应的程序,Java Servlet是和平台无关的服务器端组件,它运行在Servlet容器中Servlet容器负责Servlet和客户的通信以及调用Servlet的方法,Servlet和客户的通信采用“请求/响应”的模式

Servlet可完成如下功能

创建并返回基于客户请求的动态HTML页面。

创建可嵌入到现有 HTML 页面中的部分 HTML 页面(HTML 片段)

与其它服务器资源(如数据库或基于Java的应用程序)进行通信

ServletAPI详解

Servlet详解

Servlet接口

Servlet详解

该类的源代码如下:

package javax.servlet;
import java.io.IOException;
public interface Servlet {
    public void init(ServletConfig config) throws ServletException;
    public ServletConfig getServletConfig();
    public void service(ServletRequest req, ServletResponse res)
    throws ServletException, IOException;
    public String getServletInfo();
    public void destroy();
}

ServletConfig接口

Servlet详解

该接口的源代码如下

package javax.servlet;
import java.util.Enumeration;
public interface ServletConfig {
    public String getServletName();
    public ServletContext getServletContext();
    public String getInitParameter(String name);
    public Enumeration getInitParameterNames();
}

注意:一个Servlet对象与一个ServletConfig对象一一对应

GenericServlet

Servlet详解

源代码如下:

package javax.servlet;
import java.io.IOException;
import java.util.Enumeration;
public abstract class GenericServlet 
    implements Servlet, ServletConfig, java.io.Serializable{
    private transient ServletConfig config;
    public GenericServlet() { }
    public void destroy() {}
    public String getInitParameter(String name) {
        return getServletConfig().getInitParameter(name);
    }
    public Enumeration getInitParameterNames() {
        return getServletConfig().getInitParameterNames();
    }   
    public ServletConfig getServletConfig() {
        return config;
    }
    public ServletContext getServletContext() {
        return getServletConfig().getServletContext();
    }
    public String getServletInfo() {
        return "";
    }
    public void init(ServletConfig config) throws ServletException {
        this.config = config;
        this.init();
    }
    public void init() throws ServletException {
    }
    public void log(String msg) {
        getServletContext().log(getServletName() + ": "+ msg);
    }
    public void log(String message, Throwable t) {
        getServletContext().log(getServletName() + ": " + message, t);
    }
    public abstract void service(ServletRequest req, ServletResponse res)
    throws ServletException, IOException;
    public String getServletName() {
        return config.getServletName();
    }
}

注意:该类是一个抽象类,对Servlet和ServletConfig接口中的大部分方法做了默认的实现,并且增加了log等方法

HttpServlet

Servlet详解

部分源代码如下:

public void service(ServletRequest req, ServletResponse res)
        throws ServletException, IOException {

        HttpServletRequest  request;
        HttpServletResponse response;

        try {
            request = (HttpServletRequest) req;
            response = (HttpServletResponse) res;
        } catch (ClassCastException e) {
            throw new ServletException("non-HTTP request or response");
        }
        service(request, response);
}
protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

        String method = req.getMethod();

        if (method.equals(METHOD_GET)) {
          …
        }else if(method.equals(METHOD_POST)) {
        …
        }
}

如何编写一个Servlet程序

编写一个类继承HttpServlet

package cn.org.kingdom.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //如果在Servlet中用到response对象向客户端响应时,此时要在得到流之前设置contentType
        response.setContentType("text/html;charset=utf-8");
        PrintWriter ps = response.getWriter();
        ps.write("<html>");
        ps.write("<head><title>helloServlet</title></head>");
        ps.write("<body>你好 Servlet</body>");
        ps.write("</html>");
        ps.close();
    }
}

在web.xml中配置该servlet

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>web04</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>cn.org.kingdom.servlet.MyServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/MyServlet</url-pattern>
  </servlet-mapping>
</web-app>

访问该Servlet

Servlet详解

探究Servlet的生命周期

在前面讲解Servlet接口的api中就提到生命周期的概念

This interface defines methods to initialize a servlet, to service requests, and to remove a servlet from the server. These are known as life-cycle methods and are called in the following sequence: 
    The servlet is constructed, then initialized with the init method. 
    Any calls from clients to the service method are handled. 
    The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and finalized. 
In addition to the life-cycle methods, this interface provides the getServletConfig method, which the servlet can use to get any startup information, and the getServletInfo method, which allows the servlet to return basic information about itself, such as author, version, and copyright. 

图解:

Servlet详解

可以设置当服务器启动时,调用构造和init方法,在web.xml中设置以下代码

<servlet>
        <servlet-name>LifeServlet</servlet-name>
        <servlet-class>cn.org.kingdom.servlet.LifeServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
        <servlet-name>LifeServlet</servlet-name>
        <url-pattern>/LifeServlet</url-pattern>
</servlet-mapping>

当访问多次的时候,发现Servlet的构造方法不会执行多次,所以Servlet是一个单例设计,要求不要再servlet中定义成员变量(这个成员变量会被多个线程共享),有可能会产生线程安全问题

Servlet中配置初始化参数

在web.xml中的servlet节点配置初始化参数

<servlet>
        <servlet-name>LifeServlet</servlet-name>
        <servlet-class>cn.org.kingdom.servlet.LifeServlet</servlet-class>
        <init-param>
            <param-name>name</param-name>
            <param-value>hello LifeServlet</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
</servlet>

使用ServletConfig来进行获取初始化参数的值

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println(this.getServletConfig().getInitParameter("name"));
}

获得上下文参数

在web.xml中配置,该节点与Servlet节点处于同一级

<context-param>
    <param-name>name</param-name>
    <param-value>context-value</param-value>
</context-param>

使用ServletContext对象获取上下文参数的值

String name = this.getServletContext().getInitParameter("name");
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI