not able to get JSON string in servlet

I am trying to pass some variables through JSON from JSP to servlet through ajax call. But i am getting null value at servlet side. Please some one help me on to find out where i am making mistake/ what i missed

//JSON	
		var masterdata = new Object();
	    masterdata.grn = $('#grn').val();
	    masterdata.pono = $('#pono').val();
	    masterdata.podt = $('#podt').val();
      
//call the servlet to insert the data only when error = 0
		if (error != 1){
			$.ajax({
				url : 'insertserv',
				type: 'POST',
				dataType: 'json',
		        data: {test : JSON.stringify(masterdata)},
		        contentType: 'application/json',
		        mimeType: 'application/json',
				success : function(data) {
							alert('Hi');
						}			
		          });
		    }
		else{
			alert("Save cannot be performed. Please check the entered data!");
		}
	  	});

public class insertserv extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		System.out.println("I am inside insert");
		String masterdata = request.getParameter("test");
		System.out.println("masterdata :  "+masterdata);
		
		response.setContentType("text/plain");
	}
}

Answers 1

  • Replace your ajax code with my code...

    //JSON	
    		var masterdata = new Object();
    	    masterdata.grn = $('#grn').val();
    	    masterdata.pono = $('#pono').val();
    	    masterdata.podt = $('#podt').val();
          
    //call the servlet to insert the data only when error = 0
    		if (error != 1){
    			$.ajax({
    				url : 'insertserv',
    				type: 'POST',
    				dataType: 'json',
    		        data: JSON.stringify({"test" :masterdata}),
    		        contentType: 'application/json',
    		        mimeType: 'application/json',
    				success : function(data) {
    							alert('Hi');
    						}			
    		          });
    		    }
    		else{
    			alert("Save cannot be performed. Please check the entered data!");
    		}
    	  	});

    To get data in servlet

     BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
          String json = "";
    
                if (br != null) {
                    json = br.readLine();
                }
     JSONObject wholedata= new JSONObject(json);
    

    now the object wholedata has a your json..

    if you are using JSON.stringify() then you have to use BufferedReader in servlet , You can use request.getparameter in servlet when you are passing data in URL of servlet.


Related Articles