I have a small web project assembled in maven , it has a simple login window that accesses the servlet using an ajax request. The problem is that the request fails, the servlet is not called. However, if you directly access the servlet, it works as it should (regardless of the request data, the servlet sends a test string to the server). So the reason for the ajax request.

Window code

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Log In</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <script> $(document).ready(function(){ $("#login-button").click(function(){ var userPassword = $("input#userPassword").val(); var userLogin = $("input#userLogin").val(); var dataString = "log_in " + userLogin + " " + userPassword; $.ajax({ type: "POST", url: "/login", data: dataString, success: function(data) { alert("Successful request"); alert(data); }, error: function() { alert("Unsuccessful request"); }, dataType: "text" }); }); }); </script> </head> <body> <form class="login-form"> <h1>Login Form</h1> <input id="userLogin" type="text" name="user-login" placeholder="Enter login"/> <input id="userPassword" type="password" name="user-password" placeholder="Enter password"/> <input id="login-button" type="submit" value="Log in"/> </form> </body> </html> 

Servlet written in java , thus registered in web.xml

 <servlet> <servlet-name>Login</servlet-name> <servlet-class>LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Login</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> 
  • 3
    Maybe it's the url: "/ login"? What is your application's contextPath? Most often, the url should be of the type such / app-name / login, where app-name is the context path. It is also possible that the server address should be. http // server: port / contextPath / login. $ .ajax at best tries to get through to http // server: port / login - Sergey
  • This was the case, you should specify the full address, including the server address - http//server:port/contextPath/login - will_hunting
  • You can make an answer to your question. Strangely, a server address is also required. I assumed that jquery follows the rule when the base address is automatically added to the request (in our case http // server: port) Then in JSF, for example, it would be very easy to generate the URL programmatically, avoiding hard coding.url = "# {request.contextPath } / login ". With the server will be a little more complicated. - Sergey

1 answer 1

The reason is the wrong url , it is necessary to specify the server, port, contextPath of the application, that is, it will take the following form - url :"http//server:port/contextPath/login"