How to use the servlet to respond to this ajax request and redirect the user to another html page.

On the login.html page login.html is such a jquery script

 $(document).ready(function () { $("#login-button").click(function () { var userPassword = $("input#userPassword").val(); var userLogin = $("input#userLogin").val(); $.ajax({ type: "POST", url: "login", data: {login: userLogin, password: userPassword}, success: function (data) { alert("Successful request! Data is " + data.toString()); } }, dataType: "text", error: function (jqXHR) { console.log(jqXHR); } }); }); }); 

I need the servlet to respond to the request and redirect the same (servlet) to another html page. What should it look like?

 protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); response.getWriter().print("message"); response.getWriter().close(); // Так он передает управление обратно скрипту и не перенаправляет на welcome.html response.sendRedirect("welcome.html"); } 
  • one
    Transfer url to client and assign document.location.href = url there. - Vladimir Morulus
  • Here I just do not need it, because then the data from the HttpSession and response will be lost (for the sake of simplicity, I removed the code that was not relevant) - will_hunting
  • AJAX / XMLHttpRequest will not redirect. Although the specification says it should, until now there was no such support in browsers. Therefore, everyone has long sent the URL to the client and redirected from it - as you said above. - enzo

1 answer 1

There is a misunderstanding of how servlets work.
The entire client-server session is a request-response, a request-response ...
To process the request, an instance of the servlet is created. This copy should give the answer and only one answer. Redirection is also the answer. After the answer the copy is destroyed.

Servlets are not programs that everyone is used to writing when they control when they start, when they do something, when they finish work.
These are event handlers with strict rules. They are called by the server when it considers it necessary, and expects certain behavior from them.

  response.getWriter().close(); // Так он передает управление обратно скрипту и не перенаправляет на welcome.html response.sendRedirect("welcome.html"); 

So sendRedirect cannot work in principle. In the previous line (no comments) you have already closed the answer. Either right away, or never.

To maintain the session, as correctly noted, the HttpSession used. When processing each request, you can create a session. Subsequent requests from the same client will be automatically linked to this session and will have access to shared memory. All the data needed to support the session is added and retrieved from the HttpSession .

How ajax works with redirects itself did not check, but people say something like this.
If redirect goes in response to ajax, then the browser intercepts it, performs this redirect itself, and as a result, ajax gives the entire page to which it was redirected.
Probably this is not the best option for ajax, so Vladimir writes in the comments:

Transfer url to client and assign document.location.href = url there

In the login servlet you need to create a session, fill it with the necessary data, perform ajax-redirect

 protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); session.setAttribute("user", user); response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); response.getWriter().print("welcome.html"); } 

How to handle welcome.html in ajax will not tell. Think of it yourself. javascript is clearly not my fad.

Welcome servlet continues to work with httpsession

 protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(flase); // false не создавать сессию, использовать которая уже открыта или null когда сессии нет if (session == null) { // здесь тем или иным образом перенаправить на login return; } String user = (String)session.getAttribute("user", user); session.setAttribute("Для кучи", new Object()); response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); response.getWriter().print("welcome " + user); } 

Thus, nothing should be lost. Only cookies do not forget to allow in the browser.

For servlets came up with a bunch of all sorts of useful things that direct communication with HttpSession is reduced to a minimum. For example, CDI introduces into the servlets ready-made objects that may have different scope. One live throughout the session, others are created only during the processing of the current request. Also connect the database. Only tinkering in the configuration will have.