转发到页面时如何更改 url

How could i change the url when forwarding to a page

我正在尝试转发到 .jsp,但 url 没有改变。我很清楚redirect和forward的区别,但是我需要从servlet中获取error信息,并在jsp中显示出来,例如: login.jsp

 <c:choose>
    <c:when test="${error=='username'}">
       <div class="msg error" style="display:block">invalid username</div>
    </c:when>
    <c:when test="${error=='password'}">
       <div class="msg error" style="display:block">incorrect password</div>
    </c:when>
    <c:otherwise>
       <div class="msg error" style="display:block"></div>
    </c:otherwise>
 </c:choose>
 <form id="login-form" action="LoginAction" method="post" autocomplete="off" name="loginform" onsubmit="Check()">
    <ul class="scr-log-form-list">
       <li class="scr-form-item">
           <label for="username" class="prefix">username</label> 
           <input id="username" class="ipt" name="passport" type="text" placeholder="用户名" />
       </li>
       <li class="scr-form-item"><label for="password" class="prefix">password</label>
           <input id="password" class="pwd" name="password" type="password" /> 
           <input id="remember" class="remPwd" name="remember" value="true" type="checkbox" />
           <label for="remember" class="remPwdLabel">remember me</label>
       </li>
       <li class="scr-log-item">
           <a id="login" class="log-btn" onclick="javascript:document.loginform.submit();" style="cursor: hand" href="#"></a> 
           <span class="log-ing-btn"></span>
        </li>
    </ul>
 </form> 

这里是 LoginServlet:

        String username = (String) request.getParameter("passport");
        String password = (String) request.getParameter("password");
        AjaxRequest ar = new AjaxRequest();
        User u = ar.getUserByName(username.trim());
        if (u == null) {
            //response.sendRedirect("index1.jsp?error=usename");
            request.setAttribute("error", "username");
            request.getRequestDispatcher("index1.jsp").forward(request,
                    response);
        } else if (!u.getPasswd().equals(password.trim())) {
//          response.sendRedirect("index1.jsp?error=password");
            request.setAttribute("error", "password");
            request.getRequestDispatcher("index1.jsp").forward(request,
                    response);
        } else {
            request.getRequestDispatcher("/WEB-INF/mapviewer.jsp").forward(
                    request, response);
        }    

我不知道如何在使用forward时更改url,但这是必不可少的。例如,如果用户输入 localhost:8080/project/LoginServlet,将出现 404 错误,如何解决此问题

request.getRequestDispatcher("/WEB-INF/mapviewer.jsp").forward(

                request, response); ####

将“/WEB-INF/mapviewer.jsp”替换为“mapviewer.jsp” 它会解决你的问题 谢谢 SP

你可以用 javascript 来代替它。

<script>
 //get The current URL
 var currURL = ${requestScope['javax.servlet.forward.request_uri']}
 //Push the current URL to window history
 window.history.pushState("object or string", "mapviewer", currURL );
</script>

将它放在 <body> 中 JSP 的顶部,以便它首先执行,或者您可以将它放在 <body> 中的任何位置。