Why I can't redirect to jsp in servlet with JS function

Viewed 86

I have an application which validate login in server, if it unique - redirect to user page if login already exists

javascript function, which print error: "username already exists"    
        $(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("username is already exist");                 
       }            
});     
  });    
});

servlet, which validate login

@WebServlet("/validation")
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("username");
        if (username.equals(userService.getUserByUsername(username).getUsername()))
        {
            resp.setStatus(400);
        }
        else
        {
            ServletContext servletContext = getServletContext();
            RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/views/main.jsp");
            requestDispatcher.forward(req, resp);
        }
    }
}

button "submit" in register.jsp:

<button class="w-100 btn btn-outline-secondary" type="button" id="submit">submit</button>

in common, if type of button "button" - user can see exception, but can't see result of successful - page, that were redirected to. If type of button - "submit", success forwarding, but we can see 404 page, not only printed line about existed login.

How to fix it? How to work with AJAX Sending a redirect from servlet? Currently work - validation login in server, if login uniq -> redirect to another jsp(client page, for example), otherwise - "username already exists".

0 Answers
Related