How to obtain <servlet><init-param> inside a servlet? getServletContext().getInitParameter() does not seem to find them [duplicate]

爱⌒轻易说出口 提交于 2019-12-31 05:48:07

问题


In web.xml I have two initial parameters name Premier and Regular. To show you the code this is it.

<servlet>
    <servlet-name>StockServelt</servlet-name>
    <servlet-class>test.StockServelt</servlet-class>
    <init-param>
        <param-name>Premier</param-name>
        <param-value>/Premier</param-value>
    </init-param>
    <init-param>
        <param-name>Regular</param-name>
        <param-value>/Regular</param-value>
    </init-param>
</servlet>

I have Create two constants (named PREMIER AND REGULAR) and I want to retrieve the configuration intial parameters name "Regular" and "Premier".

This is my code for that. I am not sure I am doing this part right or not

final String PREMIER = getServletContext().getInitParameter("Premier");
final String REGULAR = getServletContext().getInitParameter("Regular");

Here I print both to the console make sure that I retrieved correctly. But I am getting a null for both

System.out.println("This is the value for Premier: " + PREMIER + " "
            + "and this is the value for Regular: " + REGULAR);

Can someone please help me out her what I am doing wrong.


回答1:


If you are doing all this in a JSF request (which I don't understand if you are) you can get the init-parameters with

<context-param>
    <param-name>Premier</param-name>
    <param-value>/Premier</param-value>
</context-param>

(note: not inside the servlet-tag)

and

final String PREMIER = FacesContext.getCurrentInstance().getExternalContext().getInitParameter("Premier");

This is just a comment as I don't know if it solves anything and/or there are other problems.



来源:https://stackoverflow.com/questions/42036330/how-to-obtain-servletinit-param-inside-a-servlet-getservletcontext-getini

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!