简体   繁体   中英

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.

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>

Assuming that your default source directory set in your IDE is /src and your default web content directory is /web then in your servlet-context just write your servlet name without the "/".Make sure that your default web content directory is WebContent. After that remove "/" from the action attribute from the form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM