Java servlet。登录后如何访问上一个URL

时间:2014-09-08 21:32:42

标签: java servlets request forward

我有简单的应用程序,在主页上我创建了登录表单

<form action="login" method="post">
        <input type="hidden" name="ReturnUrl" value='${requestScope["javax.servlet.forward.request_uri"]}' />
        <input type="text" name="login" />
        <input type="password" name="password" />
        <input type="checkbox" name="RememberMe" checked/>
        <input type="submit" value="Make login" />
 <form/>

想法非常简单。登录后我想重定向到主页(从我测试的主页返回ReturnUrl的值&#34; /&#34;和&#34; / home&#34; - 结果是一样的)

登录servlet包含覆盖的doPost

@WebServlet("/login")
public class Login extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        String name = request.getParameter("login");
        String password = request.getParameter("password");
        // get value of remember me checkbox
        String rm = request.getParameter("RememberMe");
        boolean rememberMe = !(rm == null || rm.isEmpty());
        // get return url
        String ReturnUrl = request.getParameter("ReturnUrl");

        // make login here
        /*.....*/

        RequestDispatcher dispatcher = request.getRequestDispatcher(ReturnUrl);
        dispatcher.forward(request, response);
     }

 }

我希望这段代码会调用我的home servlet来显示相应的jsp。

@WebServlet("/home")
public class Home extends HttpServlet
{
    private static final long serialVersionUID = 1L;
    private final String page = "/WEB-INF/jsp/homePage.jsp";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        RequestDispatcher dispatcher = request.getRequestDispatcher(page);
        dispatcher.forward(request, response);
    } 

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        RequestDispatcher dispatcher = request.getRequestDispatcher(page);
        dispatcher.forward(request, response);
    }

}

显示主页但网址仍包含&#34; / login&#34;。我希望它应该是&#34; / home&#34;因为我将请求从一个servlet转发给其他servlet。 为什么网址没有改变? 是否会改变网址?

1 个答案:

答案 0 :(得分:1)

您需要用户重定向returnURL而不是转发

response.sendRedirect(returnURL);