0

Im building a Java web project and i need to redirect a page, only thing is i cant redirect the page from a jsp file. I tried using the following basic methods SendRedirect | getRequestDispatcher.foward | setStatus & setHeader but none of them work?

IDE is Netbeans 8.2(i heard that java web projects dont run well on version 8.2?)
Database is Mysql

code for .jsp

 <body>
    <h1>Hello World!</h1>
    <input type="button" value="Login" onclick="foo()" />

    <script>
        function foo(){
            var req = new XMLHttpRequest();
            req.open("POST","svLogin",true);
            req.send();
            alert('gg');
        }
    </script>
</body>

code for svLogin.java (servlet)

 protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    try {
        System.out.println("xx");
        response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        response.setHeader("Location", "/project_2/chat.jsp");

/* THIS DOESNT WORK 
String nextJSP = "/project_2/chat.jsp";
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
            dispatcher.forward(req, resp);
*/

/* this doesnt work either
response.sendRedirect("/project_2/chat.jsp");
*/

    } catch (Exception e) {
        e.printStackTrace();
    }

}

Problem: when i use sendRedirect, getrequestdispatcher Or setStatus & setHeader

*if i give the correct url for the redirect, absolutely nothing happens.

*if i give the wrong url for the redirect then it says 404 error on the console and thats it.

*adding a return statement does nothing too btw

honestly at this point im willing to skype just to understand whats wrong and why this is happening

h0lmesxx
  • 53
  • 1
  • 1
  • 9
  • 1
    What do you expect to happen when sending a redirect (or any other response, BTW) as a response to an *AJAX* request, and not doing anything with the response in your JavaScript code? If you send an AJAX request, you're responsible to deal with the response. The browser won't do anything other than invoking your JavaScript response callback. – JB Nizet Mar 12 '18 at 08:02
  • Please correct me if im wrong, if i send an AJAX request to a servlet then i cant use sendRedirect because now im responsible for the response sent back to the AJAX code? @JBNizet – h0lmesxx Mar 12 '18 at 08:19
  • You can use a redirect, but you'll be responsible for handling the response. – JB Nizet Mar 12 '18 at 08:23
  • so the reason im not getting redirected is because im not adding a response to the AJAX code? @JBNizet – h0lmesxx Mar 12 '18 at 09:02
  • No. The reason is that your JS code doesn't do anything with the response. It sends a request and ignores the response. – JB Nizet Mar 12 '18 at 10:24

0 Answers0