This question has already been answered:
there is a page:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"/> <title>L2.1</title> <script> function signUpAction(){ console.log("Sign Up"); var xhr; if (window.XMLHttpRequest) { // Mozilla, Safari, ... xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE xhr = new ActiveXObject("Microsoft.XMLHTTP"); } var log = document.getElementById('login').value; var pas = document.getElementById('password').value; xhr.open('POST', '/reg', true); var body = 'login=' + encodeURIComponent(log) + '&password=' + encodeURIComponent(pas); xhr.setRequestHeader('Content-Type', 'multipart/form-data'); xhr.onreadystatechange = function() { if (xhr.status != 200) { alert( xhr.status + ': ' + xhr.statusText ); } else { alert( xhr.responseText ); } }; xhr.send(body); } </script> </head> <body> <p>Welcome</p> <form action="" method="POST"> Login: <input id="login" type="text" name="login"/> Password: <input id="password" type="password" name="password"/> </form> <button name="SignUp" onclick="signUpAction()">Sign Up </button> </body> </html> And the servlet is written to accept requests by URI /reg :
public class SingUpServlet extends HttpServlet { AccountService accountService; public SingUpServlet(AccountService accountService){ this.accountService = accountService; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Map<String, Object> requestParams = getRequestParameters(req); resp.getWriter().print("SIGNING UP doGET"); resp.setStatus(HttpServletResponse.SC_OK); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Map<String, Object> requestParams = getRequestParameters(req); resp.getWriter().print("SIGNING UP"); resp.setStatus(HttpServletResponse.SC_OK); } private Map<String, Object> getRequestParameters(HttpServletRequest req) throws IOException { Map<String, Object> map = new HashMap<>(); map.put("pathInfo", req.getPathInfo()); map.put("context", req.getContextPath()); map.put("method", req.getMethod()); map.put("session", req.getSession().getId()); map.put("URL", req.getRequestURI().toString()); map.put("body", req.getReader().lines().collect(Collectors.joining(System.lineSeparator()))); System.out.println("dobody: " + map.get("body")); return map; } } After clicking on the button, the request flies to the server and returns the answer. In theory, an alert should work once and display a message from the server, but it works 3 times:
First an alert with an empty message, then 2 alerts with text from the response.
Why is this happening and how to fix it?