Search code examples
javaservletsservlet-mapping

Servlet url-mapping


I'm having some problems to understand how url-mapping works for the servlets.

I watched tons of tutorials online and posts here but without luck.

So, let's say I have a servlet (WelcomeServlet.java), an index page (index.html) and my web.xml file.

The WelcomeServlet.java file is in the src directory while the index.html is in the WebContent one.

My index page is going to be called by web.xml and will display a button that, once pressed, is going to send a get request to the servlet.

Problem is, once i press the button, the page doesn't change in anything beside the url, that goes from

http://localhost:8080/WelcomeServlet

to

http://localhost:8080/WelcomeServlet/?

This is the body of the index page:

<body>
    <form action = "/WelcomeServlet" method = "get">
    <p><label>Click the button to invoke the servlet
            <input type = "submit" value = "Get HTML Document"/>
    </label></p>
    </form>
</body>

And this is the web.xml servlet mapping:

<servlet>
        <servlet-name>welse</servlet-name>
        <servlet-class>WelcomeServlet</servlet-class>
</servlet>

<servlet-mapping>
        <servlet-name>welse</servlet-name>
        <url-pattern>/WelcomeServlet</url-pattern>
</servlet-mapping>

<welcome-file-list>
        <welcome-file>Index.html</welcome-file>
</welcome-file-list>

I'm quite confident the problem is the addressing in the index form action but I really can't wrap my head around what should I put there. I tried several path but with no luck.


Solution

  • You're almost there. Just add ../ in your action, so that it can go back a step. At the moment, it's pointing to the same location as your html file.

    <body>
        <form action = "../WelcomeServlet" method = "get">
        <p><label>Click the button to invoke the servlet
                <input type = "submit" value = "Get HTML Document"/>
        </label></p>
        </form>
    </body>