title: Cannot handle POST request with this servlet
body: <p>this is my servlet</p>
  
  <pre><code>import java.io.IOException;
  import java.io.PrintWriter;
  import java.sql.Connection;
  import java.sql.DriverManager;
  import java.sql.PreparedStatement;
  import java.sql.ResultSet;
  import java.sql.SQLException;
  
  import javax.servlet.Servlet;
  import javax.servlet.ServletConfig;
  import javax.servlet.ServletContext;
  import javax.servlet.ServletException;
  import javax.servlet.annotation.WebServlet;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  
  //import org.json.JSONObject;
  import org.json.simple.JSONObject;
  
  import com.mysql.jdbc.Statement;
  /**
   * Servlet implementation class Login
   */
  @WebServlet("/Login")
  public class Login extends HttpServlet {
      private static final long serialVersionUID = 1L;
      private Connection connection;
      /**
       * @see HttpServlet#HttpServlet()
       */
      public Login() {
          super();
          // TODO Auto-generated constructor stub
      }
  
      public void init(ServletConfig config) throws ServletException {
          ServletContext context = config.getServletContext();
          String url = context.getInitParameter("dbUrl");
          String dbUser = context.getInitParameter("dbUser");
          String dbPassword = context.getInitParameter("dbPassword");
          try {
              Class.forName("com.mysql.jdbc.Driver");
              connection = DriverManager.getConnection(url, dbUser, dbPassword);
          } catch (ClassNotFoundException | SQLException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
      }
  
      public void destroy() {
          if (connection != null) {
              try {
                  connection.close();
              } catch (SQLException e) {
              }
          }
      }
      /**
       * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
       */
      @Override
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          doPost(request, response);
  
      }
  
      /**
       * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
       */
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          response.setContentType("plain/text");
  
          JSONObject json = new JSONObject();
          PrintWriter out = response.getWriter(); 
          String usernameV = request.getParameter("usernameV");
          String passwordV = request.getParameter("passwordV");
  
          json.put("ris", 0);
          try {
              String sql = "SELECT * FROM user WHERE username = ? AND password = ? ";         
              PreparedStatement stmt = connection.prepareStatement(sql);
              stmt.setString(1, usernameV);
              stmt.setString(2, passwordV);
              json.put("password", usernameV);
              json.put("username", usernameV);
  
              out.print(json.toJSONString());
              ResultSet rs = stmt.executeQuery();
              if (rs.next()) {
                  json.replace("ris", 1);
                  out.print(json.toJSONString());
                  stmt.close();
                  rs.close();
                  return;
              }
              stmt.close();
              rs.close();
          } catch (SQLException e) {
              json.replace("err", e.getMessage());
              out.print(json.toJSONString());
  
          }
  
  
          out.print(json.toJSONString());``
      }
  
      }
  </code></pre>
  
  <p>and here's my javascript</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
   $(window).keydown(function(event){//impedisco l'invio del form premendo invio
    if(event.keyCode == 13) {
     event.preventDefault();
     return false;
    }
   });
   
   $("#bottone").click(function(){
    $("#risultato").attr("style", "color: black;");
    $("#risultato").html("Caricamento..."); 
    var username = $("#username").val();
    var password = $("#password").val();
    $.ajax({
     type: "POST",
     url: "Register",
     //data: {"username" : username, "password": password},
     data: "username=" + username + "&amp;password=" + password,
     dataType: "text",
     success: function(msg)
     {    
      var result = $.parseJSON(msg);    
      if(result.error){
       switch (result.error) {
       case 1:
        Step();
              
        break;
       default:
        $("#risultato").html(msg);
       break;
       }
      }else{
       $("#bottone").prop('disabled', true);
       $("#risultato").attr("style", "color: black;");
       $("#risultato").html("Benvenuto " + username + "!");
      }             
     },
     error: function()
     {
      $("#risultato").attr("style", "color: red;");
      $("#risultato").html("Errore di connessione!");
     }
    });
   });
  });
  
  function Step() {
   $("#risultato").attr("style", "color: red;");
   $("#risultato").html("Username gi&amp;agrave; esistente!&lt;br&gt;");
   $("#risultato").append("&lt;p&gt;Inserisci la tua password : &lt;input type='password' name='passwordV' id='passwordV'&gt; &lt;input type='button' id='bottone1' value='Login'&gt; &lt;/p&gt;");
   
   $("#bottone1").click(function(){
    $("#res").attr("style", "color: black;");
    $("#res").html("Caricamento..."); 
    var username = $("#username").val();
    var password = $("#passwordV").val();
   $.ajax({
    type: "POST",
    url: "Login",
    data: "usernameV=" + username + "&amp;passwordV=" + password,
    dataType: "text",
    success: function(msg)
    {    
     var resulto = $.parseJSON(msg);    
     if(resulto.ris){
      switch (resulto.ris) {
      case 1:
       $("#res").attr("style", "color: red;");
       $("#res").html("Benvenuto " + username + "!");
             
       break;
      default:
       $("#res").html(msg);
      break;
      }
     }else{
      $("#bottone1").prop('disabled', true);
      $("#res").attr("style", "color: black;");
      $("#res").html("password errata:"+ password);
      $("#stack").attr("style", "color: black;");
      $("#stack").html(msg);
     }             
    },
    error: function()
    {
     $("#res").attr("style", "color: red;");
     $("#res").html("Errore di connessione!");
    }
   });
   });
  }
  
   
      
   
   
   </code></pre>
  </div>
  </div>
  
   if it helps, i post also the default.jsp page:</p>
  
  <pre><code>&lt;%@ page language="java" contentType="text/html; charset=ISO-8859-1"
      pageEncoding="ISO-8859-1"%&gt;
  &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
  &lt;html&gt;
  &lt;head&gt;
  &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt;
  &lt;title&gt;Chat Room&lt;/title&gt;
  &lt;script type="text/javascript" src="jquery-3.2.0.js"&gt;&lt;/script&gt;
  &lt;script type="text/javascript" src="script.js"&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  
      &lt;form name="modulo" action=""&gt;
          &lt;p&gt;
              Nome utente: &lt;input type="text" name="username" id="username"&gt;
              Password:    &lt;input type="password" name="password" id="password"&gt;
              &lt;input type="button" id="bottone" value="Registrati!"&gt;
          &lt;/p&gt;
      &lt;/form&gt;
      &lt;div id="risultato"&gt;&lt;/div&gt;
      &lt;div id ="res"&gt;&lt;/div&gt;
      &lt;div id="stack"&gt;&lt;/div&gt;
  
  
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>i add also the Register.java servlet.. This one does work, and, as you  can see, it is almost the same as the login one.</p>
  
  <pre><code>package it.marco.chat.servlets;
  
  import java.io.IOException;
  import java.io.PrintWriter;
  import java.sql.Connection;
  import java.sql.DriverManager;
  import java.sql.PreparedStatement;
  import java.sql.ResultSet;
  import java.sql.SQLException;
  
  import javax.servlet.Servlet;
  import javax.servlet.ServletConfig;
  import javax.servlet.ServletContext;
  import javax.servlet.ServletException;
  import javax.servlet.annotation.WebServlet;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  
  //import org.json.JSONObject;
  import org.json.simple.JSONObject;
  
  import com.mysql.jdbc.Statement;
  
  /**
   * Servlet implementation class Register
   */
  @WebServlet("/Register")
  public class Register extends HttpServlet {
      private static final long serialVersionUID = 1L;
      private Connection connection;
  
      /**
       * @see HttpServlet#HttpServlet()
       */
      public Register() {
          super();
      }
  
      /**
       * @see Servlet#init(ServletConfig)
       */
      public void init(ServletConfig config) throws ServletException {
          ServletContext context = config.getServletContext();
          String url = context.getInitParameter("dbUrl");
          String dbUser = context.getInitParameter("dbUser");
          String dbPassword = context.getInitParameter("dbPassword");
          try {
              Class.forName("com.mysql.jdbc.Driver");
              connection = DriverManager.getConnection(url, dbUser, dbPassword);
          } catch (ClassNotFoundException | SQLException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
      }
  
      /**
       * @see Servlet#destroy()
       */
      public void destroy() {
          if (connection != null) {
              try {
                  connection.close();
              } catch (SQLException e) {
              }
          }
      }
  
      @Override
      protected void doGet(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
          doPost(request, response);
      }
  
      /**
       * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
       *      response)
       */
      protected void doPost(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
          response.setContentType("plain/text");
  
          JSONObject json = new JSONObject();
          PrintWriter out = response.getWriter();
          json.put("error", 0);
  
  
          String username = request.getParameter("username");
          String password = request.getParameter("password");
  
  
          try {
              String sql = "SELECT * FROM user WHERE username = ?";           
              PreparedStatement stmt = connection.prepareStatement(sql);
              stmt.setString(1, username);
              ResultSet rs = stmt.executeQuery();
              if (rs.next()) {
                  json.replace("error", 1);
                  out.print(json.toJSONString());
                  stmt.close();
                  rs.close();
                  return;
              }
              stmt.close();
              rs.close();
          } catch (SQLException e) {
          }
  
  
          int uid = -1;
  
          try {
              String sql = "INSERT INTO user(username,password) VALUES(?,?)";
              PreparedStatement stmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
              stmt.setString(1, username);
              stmt.setString(2, password);
              stmt.execute();
              ResultSet rs = stmt.getGeneratedKeys(); 
              if (rs.next()) {
                  uid = rs.getInt(1);
              }
              stmt.close();
              rs.close();
          } catch (SQLException e) {
              e.printStackTrace();
          }
  
  
          json.put("uid", uid);
  
          out.print(json.toJSONString());
      }
  
  }
  </code></pre>
  
  <p>i cannot understand why the servlet is not able to handle the POST request.. I mean, i have already set up one servlet that hanldles the register part and it works perfectly.
  I have tried all the evening to make it work, and i am pretty sure there's a stupid mistake i am not able to see, that's why i have come here.
  I hope that someone is able to help me.
  Thank you </p>