JavaWeb学习之Servlet(二)——servletCon

2017-05-01  本文已影响0人  yaannis

1.在servlet配置中添加初始参数(如下配置了用户名和密码两个参数)

 <servlet>
        <servlet-name>FirstServlet</servlet-name>
        <servlet-class>WelcomeServlet</servlet-class>

        <init-param>
            <param-name>username</param-name>
            <param-value>root</param-value>
        </init-param>
        <init-param>
            <param-name>pwd</param-name>
            <param-value>passwordddd</param-value>
        </init-param>

    </servlet>
    <servlet-mapping>
        <servlet-name>FirstServlet</servlet-name>
        <url-pattern>/firstWelcome</url-pattern>
    </servlet-mapping>

2.在servlet的init方法中获取参数名和值

@Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("init");
        Enumeration<String> params = servletConfig.getInitParameterNames();
        while (params.hasMoreElements()){
            String name = params.nextElement();
            String value = servletConfig.getInitParameter(name);
            System.out.println(name+":"+value);
        }
    }

3.servletConfig还可以获取servlet的配置名称,即servlet-name

String servletName = servletConfig.getServletName();
上一篇下一篇

猜你喜欢

热点阅读