-1

I'm trying to make page redirection from Servlet but it doesn't work I don't know why, if anyone could help I'll be grateful, I spent 2 hours searching but I didn't get a result.

the JS code

$("#login_form_submit").click(function(){
var form = $('#login_form');
    $.ajax({
            type: "Post",
            url: "AccountServlet",
            data: form.serialize(),
            dataType: "json",

            //if received a response from the server
            success: function( data, textStatus, jqXHR) {
                 if(data.success){
                    $("#ajaxResponse").html("");
                    console.log(data);

                    if (data.User.role == 1){
                        main.user = data.User; 
                        //window.location.href = "Student_home.jsp";
                    }
                 } 
                 //display error message
                 else {
                    $("#ajaxResponse").html("<div><b>Something goes wrong check your email or password</b></div>");

                 }
            },

            //If there was no response from the server
            error: function(jqXHR, textStatus, errorThrown){
                 $("#ajaxResponse").html("<div><b>Something goes wrong check your email or password</b></div>");
                 $("#ajaxResponse").html(jqXHR.responseText);
            },

            //capture the request before it was sent to server
            beforeSend: function(jqXHR, settings){
                //disable the button until we get the response
                $('#login_form_submit').attr("disabled", true);
            },

            //this is called after the response or error functions are finsihed
            //so that we can take some action
            complete: function(jqXHR, textStatus){
                //enable the button 
                $('#login_form_submit').attr("disabled", false);
            }

        });        

});

the servlet code

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    response.setHeader("Cache-control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");


    String userName = request.getParameter("userName");
    String password = request.getParameter("password");
    DatabaseWrapper context = new DatabaseWrapper();
    User user = context.Check_login(userName, password);
    session.current_user = user;
    Gson gson = new Gson(); 
    JsonObject myObj = new JsonObject();

    if (user == null){
        myObj.addProperty("success", false);
        out.println(myObj.toString());
    }else if (user instanceof Student){
        JsonElement userObject = gson.toJsonTree((Student)user);
        myObj.addProperty("success", true);
        myObj.add("User", userObject);
        out.println(myObj.toString());

        out.close();
        //response.setStatus(HttpServletResponse.SC_FOUND); 
        response.sendRedirect("Student_home.jsp");
        return;


    }

I tried also to use

RequestDispatcher dispatcher = request.getRequestDispatcher("/Student_home.jsp");
        dispatcher.forward(request, response);

but it didn't succeeded, any suggestion !

only using javascript works fine with me, but I need redirect from the servlet!

I used this line in javascript

window.location.href = "Student_home.jsp";

Guys I found the answer but for some reason I can't post it in solutions?!

the problem was I'm redirecting the ajax call and there is no way to prevent it, the idea is from the response in the jquery success I'll redirect using another call which create form element and submit it in natural way

my solution :

function Redirect (servlet , method_type){
var form = $(document.createElement('form'));
$(form).attr("action", servlet);
$(form).attr("method", method_type);
$(form).css("display", "none");
form.appendTo( document.body );
$(form).submit();

};

it is done, thanks every one.

Ahmed Ghazey
  • 479
  • 1
  • 9
  • 22
  • 2
    If you want to use ajax then the javascript has to handle the redirect. The browser will only handle the redirect if you do a "normal" submit. – BevynQ Apr 26 '16 at 00:56
  • You're merely redirecting the ajax request, not the main request. Just let the servlet return the desired redirect URL as JSON response, and then let JavaScript redirect to it. – BalusC Apr 26 '16 at 07:44
  • how to keep date returned from ajax call with the redirect ?! because i tried this but the data disappeared after redirect ?! – Ahmed Ghazey Apr 26 '16 at 11:56

1 Answers1

0

You cannot do anything to response after close().

When it comes to header, you cannot even write them after response is committed. In your case, you should not even write anything to response if you are redirecting.

The same applies for RequestDispatcher.forward(). You should not write anything to the response before forwarding. And, never close().

Ramesh PVK
  • 15,200
  • 2
  • 46
  • 50