Can't understand why when using request.getParameter ("..."), do I get null ?? An example of a tutorial where the same construction is used ..

If anyone faced pliz help ..

@WebServlet(urlPatterns = "/Servlet") public class Servlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String firstname = request.getParameter("firstName"); System.out.println(firstname); String lastname = request.getParameter("lastName"); System.out.println(lastname); String email = request.getParameter("emailAddress"); System.out.println(email); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } } 

 $("#sudmitId").click(function () { var firstName = $("[name=firstName]").val(); var lastName = $("[name=lastName]").val(); var emailAddress = $("[name=emailAddress]").val(); var user = { firstName:this.firstName, lastName:this.lastName, emailAddress:this.emailAddress } $.ajax({ url:"http://localhost:9090/Demo/Servlet", method:"post", data:user, contentType:"application/text", error:function (message) { console.log(message); }, success:function (data) { console.log(data); } }) }); 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form> <label>FirstName: </label> <input name="firstName" type="text"><br> <label>LastName: </label> <input name="lastName" type="text"><br> <label>Email: </label> <input type="email" name="emailAddress"><br> <input type="button" name="submit" id = "sudmitId" value="Send!"> </form> <script src="jquery-3.1.0.js"></script> <script src="formhandler.js"></script> </body> </html> 

    1 answer 1

    You incorrectly send the form to the server. If you want these forms to be available via request.getParameter() , they need to be sent to the server not with contentType:"application/text" , but with contentType:"application/x-www-form-urlencoded" :

     $.ajax({ url: "https://localhost:8443/Demo/Servlet", method: "post", contentType: "application/x-www-form-urlencoded", data: user }); 

    If you want to send the data in JSON, then, first, you need to serialize the object being sent to the string:

     data: JSON.stringify(user) 

    And secondly, you need to read it on the server not through request.getParameter() , but through request.getInputStream() :

     InputStream in = request.getInputStream(); Scanner s = new Scanner(in); String data = s.next(); // Опционально: десериализуем полученный JSON в Map. Здесь я использовал библиотеку Gson. Map map = new Gson().fromJson(data, Map.class);