Can we write an argument constructor in a Servlet?
Yes, you can but it is useless since the servlet container won't invoke it.
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");
// ...
}
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
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…