Javaweb-servlet-ServletConfig和ServletContext初始化参数的区别

示例代码:

package com.qust.stumis.controller;

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


public class ReadServletConfig extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //读取初始化参数
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();

        ServletContext context = req.getServletContext();
        String tmp = context.getInitParameter("zhangsan");
        out.println("初始化参数:" + tmp);

        //读取初始配置
        ServletConfig config = getServletConfig();
        String param = config.getInitParameter("encoding");
        out.println("初始化的encoding:" + param);

    }
}

示例结果:

在这里插入图片描述

主要区别:

最主要的区别是在web.xml的配置的节点位置不同。
ServletContext是属于整个web的,ServletConfig是配置单个servlet的。
二者在web.xml的配置如下:

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

    <servlet>
        <servlet-name>read</servlet-name>
        <servlet-class>com.qust.stumis.controller.ReadServletConfig</servlet-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>read</servlet-name>
        <url-pattern>/read</url-pattern>
    </servlet-mapping>

详细的讲解参考:
https://blog.csdn.net/durenniu/article/details/81063585
https://blog.csdn.net/u013815649/article/details/50435819

你可能感兴趣的:(Java,servlet,java,前端)