获取web.xml中的init-param定义的值

为了在web容器启动时运行指定的类,我们可以在web.xml中配置一个自定义的servlet,复写init方法即可,如下:
web.xml

<servlet>
<servlet-name>testServlet</servlet-name>
<servlet-class>vip.kwin.test.TestServlet</servlet-class>
  <load-on-startup>3</load-on-startup>
</servlet>

TestServlet.java

public class TestServlet extends HttpServlet {
    public void init(ServletConfig config) throws ServletException {
        //在这里做相应的处理
    }

    public void destroy() {
    }
}

 


在启动时,若要为其配置相应的参数又该如何处理呢?以下介绍几种常用的方法。

1、在servlet中获取参数:
web.xml

<servlet>
    <servlet-name>testServlet</servlet-name>
    <servlet-class>vip.kwin.test.TestServlet</servlet-class>
    <init-param>
        <param-name>username</param-name>
        <param-value>tom</param-value>
    </init-param>
    <load-on-startup>3</load-on-startup>
</servlet>
TestServlet.java
public class TestServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(TestServlet.class);

    public void init(ServletConfig servletConfig) throws ServletException {
        super.init(config);
        String username = servletConfig.getInitParameter("username");
        // ……
    }

    public void destroy() {
    }
}


2、在jsp中获取参数:
web.xml

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

jsp

<%
String username = application.getInitParameter("username");
%>

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值