如何在启动期间使用参数初始化 Servlet? [英] How to initialize a Servlet during startup with parameters?

查看:21
本文介绍了如何在启动期间使用参数初始化 Servlet?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以在 Servlet 中编写参数构造函数吗?如果是,你怎么打电话?

Can we write an argument constructor in a Servlet? If yes, how can you call?

推荐答案

我们可以在 Servlet 中编写参数构造函数吗?

是的,您可以,但它没有用,因为 servlet 容器不会调用它.

Yes, you can but it is useless since the servlet container won't invoke it.

正确的做法是使用 init() 方法:

The proper way to do it is to use the init() method:

@Override
public void init() throws ServletException {
    String foo = getInitParameter("foo");
    String bar = getServletContext().getInitParameter("bar");
    // ...
}

在本例中,getInitParameter("foo") 返回特定的值web.xmlgetServletContext().getInitParameter("bar") 返回中独立的的值代码>web.xml.

In this example, getInitParameter("foo") returns the value of the <init-param> of the specific <servlet> entry in web.xml, and getServletContext().getInitParameter("bar") returns the value of the independent <context-param> in web.xml.

这篇关于如何在启动期间使用参数初始化 Servlet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆