Servlet——ServletConfig

一、ServletConfigjavax.servlet.ServletConfig包;

  //对应jsp中的config;

  //用于获取web.xml中的<init-param>配置的初始化参数;

二、获取ServletConfig对象:

  ServletConfig config=getServletConfig();

三、获取资源方法:

(1String getServletName();//获取当前Servlet在web.xml中配置的名称;

(2String getInitParameter(String name);//获取当前Servlet指定名称的初始化参数的值;

(3Enumeration getInitParameterNames();//获取当前Servlet所有初始化参数的名字组成的枚举;

(4ServletContext getServletContext();//获取代表当前web应用的ServletContext对象;

1)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_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>Test</servlet-name>
        <servlet-class>com.qf.controller.Test</servlet-class>
        <init-param>
            <param-name>initParam</param-name>
            <param-value>initParam</param-value>
        </init-param>
    </servlet>
    <context-param>
        <param-name>contextParam</param-name>
        <param-value>contextParam</param-value>
    </context-param>
    <servlet-mapping>
        <servlet-name>Test</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>
</web-app>

2)测试类:

public class Test extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 拿到init方法中的ServletConfig对象
        ServletConfig config = getServletConfig();

        // --获取当前Servlet 在web.xml中配置的名称(用的不多)
        String sName = config.getServletName();
        System.out.println("当前Servlet 在web.xml中配置的名称:" + sName);

        // --获取当前Servlet中配置的初始化参数
         String value = config.getInitParameter("initParam");
         System.out.println(value);

        //获取当前Servlet所有初始化参数的名字组成的枚举;
        Enumeration enumeration = config.getInitParameterNames();
        while (enumeration.hasMoreElements()) {
            String name = (String) enumeration.nextElement();
            String v = config.getInitParameter(name);
            System.out.println(name + ":" + v);
        }

        //获取代表当前web应用的ServletContext对象;
        ServletContext servletContext = config.getServletContext();
        System.out.println(servletContext);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}

 

 

 

posted @ 2019-07-29 13:35  开拖拉机的拉风少年  阅读(138)  评论(0编辑  收藏  举报