JavaWEB(三)--ServletConfig对象

ServletConfig:

封装了Servlet的配置信息,并且可以获取ServletContext对象;

配置Servlet的初始化参数:

<servlet>
    
        <servlet-name>helloServletservlet-name>
        
        <servlet-class>com.servlet.javaweb.HelloServletservlet-class>

        
        <init-param>
            
            <param-name>userparam-name>
            
            <param-value>wanghaoparam-value>
        init-param>
        <init-param>
            <param-name>passwordparam-name>
            <param-value>123456param-value>
        init-param>

        
        <load-on-startup>-1load-on-startup>

    servlet>

获取初始化参数:

1:getInitParameter(String name):获取指定参数名的初始化参数;
2:getInitParameterNames(String name):获取参数名组成的Enumeration对象;

HelloServlet.java :

package com.servlet.javaweb;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class HelloServlet implements Servlet {

    @Override
    public void destroy() {
            System.out.println("destroy");      
    }

    public ServletConfig getServletConfig() {
        System.out.println("getServletConfig");
        return null;
    }

    @Override
    public String getServletInfo() {
        System.out.println("getServletInfo");
        return null;
    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("init");

        String user = servletConfig.getInitParameter("user");
        System.out.println("user:  "+user);

        Enumeration names= servletConfig.getInitParameterNames();
        while(names.hasMoreElements()){
            String name = names.nextElement();  
            String value = servletConfig.getInitParameter("user");
            System.out.println("name:  "+name+ ":"+value);
        }
        String servletName = servletConfig.getServletName();
        System.out.println(servletName);
    }

    @Override
    public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
        System.out.println("service");
    }
    public HelloServlet(){
        System.out.println("Hello Servlet ");
    }

}

输出结果:

JavaWEB(三)--ServletConfig对象_第1张图片

你可能感兴趣的:(JavaWEB,JavaWEB)