title: Why I can't redirect to jsp in servlet with JS function
body: <p>I have an application which validate login in server, if it unique - redirect to user page <a href="https://i.stack.imgur.com/x4lCv.png" rel="nofollow noreferrer">if login already exists</a></p>
  <pre><code>javascript function, which print error: &quot;username already exists&quot;    
          $(document).ready(function () {          
         #$('#submit').click(function () {          
            let username = $('#username').val();         
             $.ajax({                 
         type: 'POST',              
            data: {username: username},           
               url: '/validation',             
             success: function (response) {          
                    $('#result1').html(response.responseText);           
               },           
               error: function () {               
               $('#result1').html(&quot;username is already exist&quot;);                 
         }            
  });     
    });    
  });
  </code></pre>
  <p>servlet, which validate login</p>
  <pre><code>@WebServlet(&quot;/validation&quot;)
  public class ValidationServlet extends HttpServlet
  {
      private UserDAO userDAO = new UserDAOImpl();
      private UserService userService = new UserServiceImpl(userDAO);
  
      @Override
      protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
      {
      }
  
      @Override
      protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
      {
          String username = req.getParameter(&quot;username&quot;);
          if (username.equals(userService.getUserByUsername(username).getUsername()))
          {
              resp.setStatus(400);
          }
          else
          {
              ServletContext servletContext = getServletContext();
              RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher(&quot;/views/main.jsp&quot;);
              requestDispatcher.forward(req, resp);
          }
      }
  }
  </code></pre>
  <p>button &quot;submit&quot; in register.jsp:</p>
  <pre><code>&lt;button class=&quot;w-100 btn btn-outline-secondary&quot; type=&quot;button&quot; id=&quot;submit&quot;&gt;submit&lt;/button&gt;
  </code></pre>
  <p>in common, if type of button &quot;button&quot; - user can see exception, but can't see result of successful - page, that were redirected to. If type of button - &quot;submit&quot;, success forwarding, but we can see 404 page, not only printed line about existed login.</p>
  <p><strong>How to fix it?
  How to work with AJAX Sending a redirect from servlet?
  Currently work - validation login in server, if login uniq -&gt; redirect to another jsp(client page, for example), otherwise - &quot;username already exists&quot;.</strong></p>