javaservletsweb.xmlinit-parameters

@WebServlet with init parameters from xml


I am checking new annotations for web servlets but what I do not understand how can you pass initial parameters (init-param) from easily modified location. Yes, I found annotation @WebInitParam, but that means you must write value into code, which i guess misses the point for easy change in web.xml.

So whats deal here? Do not use @WebServlet in such case?


Solution

  • An interesting use case, and it turns out you can (my configuration: JBoss 7.1.1):

    Servlet:

    @WebServlet(name="fooServlet", urlPatterns="/foo")
    public class FooServlet extends HttpServlet
    {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String flip = getInitParameter("flip");
            resp.getWriter().println("<html>" +
                "<head><title>" + getServletName() + "</title></head>" +
                "<body>From " + getServletName() + ": " + flip + "</body>" +
                "</html>"
            );
        }
    }
    

    Inside web.xml (note the name is the same, and no <servlet-class> is specified):

    <servlet>
        <servlet-name>fooServlet</servlet-name>
        <init-param>
            <param-name>flip</param-name>
            <param-value>flop</param-value>
        </init-param>
    </servlet>
    

    The value of flip = getInitParameter("flip") is set to flop, as specified in the web.xml!


    By the way, I was wondering if this is a feature of JBoss, or standard. It is standard, see Servlet 3.0 specification, chapter 8.2.1 "Modularity of web.xml".