简体   繁体   中英

Redirect to a JSP page after login using AJAX

I have a login.jsp page where users type in username and password. Username and password are sent to the server using ajax ($.post). When the authentication is complete, I want to redirect user to an index.jsp page.

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

     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. Should I use jQuery to redirect user using 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.

To your question, first check the url pattern of your servlet. 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 . 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.

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