简体   繁体   English

使用AJAX登录后重定向到JSP页面

[英]Redirect to a JSP page after login using AJAX

I have a login.jsp page where users type in username and password. 我有一个login.jsp页面,用户在其中输入用户名和密码。 Username and password are sent to the server using ajax ($.post). 用户名和密码使用ajax($ .post)发送到服务器。 When the authentication is complete, I want to redirect user to an index.jsp page. 认证完成后,我想将用户重定向到index.jsp页面。

js: js:

function Login()
{
    var traderName = document.getElementById('username').value;
    var traderPass = document.getElementById('password').value;

    //SetLoginLoading();

    data = {action:'login',username:traderName,password:traderPass};

    $.post('TraderServlet',$.param(data),function(response){
    });
    return false;
}

Servlet Servlet

     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              ....
              login(request, response);
              ....
     }       
   private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter(PARAMETER_NAME);
        String pass = request.getParameter(PARAMETER_PASS);
        traderBean.login(name, pass);

        response.sendRedirect("index.jsp");
    }

I tried to use response.sendRedirect() but it does not work. 我试图使用response.sendRedirect(),但是它不起作用。 Should I use jQuery to redirect user using ajaxCallback ? 我应该使用jQuery使用ajaxCallback重定向用户吗?

Thank you. 谢谢。

In general, if you are just going to redirect anyway, there is really no point in using AJAX as you can accomplish this by just having the servlet handle directly from the form. 通常,如果无论如何都将重定向,那么使用AJAX确实没有意义,因为仅通过直接从表单处理servlet就可以实现这一点。

To your question, first check the url pattern of your servlet. 对于您的问题,首先检查servlet的url模式。 Make sure it is actually being called. 确保它实际上是在被调用。 If so, then if it has a url pattern like 如果是这样,则它的网址格式如下

/TraderServlet

Then it expects index.jsp to be also in the root folder under Web . 然后,它希望index.jsp也位于Web下的根文件夹中。 It could be that you are simply not redirecting to where you are expecting to go. 可能是您根本没有重定向到期望的位置。

One way to check is (if you're in Chrome) use the debugger tools (F12 on Windows/Nix, Ctrl-Shift-I on Macs), and see what error it is giving. 一种检查方法是(如果您使用的是Chrome)(使用调试器工具)(在Windows / Nix上为F12,在Mac上为Ctrl-Shift-I),然后查看它给出了什么错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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