简体   繁体   中英

How do I control the address generated in address bar of browser after executing a servlet?

I have written, for practice, a simple webpage that will display to the user a drop down menu. The user will select a number and hit the Submit button.

After that, the servlet will be executed and will send back a list of even numbers.

在此处输入图片说明

Looking at the address in the address bar of the web browser, it is:

http://localhost:8080/FindEvenOdd/FindEvenOdd

I want it to be http://localhost:8080/FindEvenOdd/Result

How do I do that ?
My DD looks like this:

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    web-app_2_4.xsd"
    version="2.4">

    <servlet>
        <servlet-name>Evens</servlet-name>
        <servlet-class>FindIt</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Evens</servlet-name>
        <url-pattern>/FindEvenOdd</url-pattern>
    </servlet-mapping>
</web-app>  

my HTML:

<html>
    <head>
        <title> List of Even/Odd Numbers </title>
    </head>

    <body>
        <form method="POST" action="FindEvenOdd">
        <center>
            <select name="number" size="1">
                <option> <50
                <option> <100
                <option> <150
            </select>
        </center>
            <center>
                <input type="SUBMIT">
            </center>
        </form>
    </body>
</html>  

What I tried

  • I changed the action="FindEvenOdd" to action="Result"
  • i changed the <url-pattern> to Result

  • I did the above two things simultaneously but got a 404.
    So,
    What do I do to get http://localhost:8080/FindEvenOdd/Result

    What you tried is almost correct. The url-pattern must be set to /Result .

    Some notes though:

    • always put your classes in a package. Not in the default package
    • generate valid HTML5. center is a tag that shouldn't be used for a long time, and your select box is invalid HTML.
    • Learn servlet 3.0 rather than servlet 2.4.

    将网址格式更改为/FindEvenOdd/Result并尝试

    In order to change URL, you need a redirect in the servlet.

    String contextPath = request.getContextPath();
    response.sendRedirect(response.encodeRedirectURL(contextPath + "/Result") );
    

    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