I am trying to write my first JSON servlet as following:
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
import org.json.JSONException;
public class Home extends HttpServlet{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException{
res.setContentType("text/html; charset=UTF-8");
req.setCharacterEncoding("UTF-8");
res.setCharacterEncoding("UTF-8");
StringWriter sWriter = new StringWriter();
PrintWriter out = new PrintWriter(sWriter);
String jsonText = "{\"Name\":\"Vahid\",\"Nickname\":null,\"Salary\":\"15000.0\",\"isPermanent\":true,\"EmployeeId\":\"121\"}";
try{
JSONObject json = new JSONObject(jsonText);
String name = json.getString("Name");
out.println(json.toString()+"<br>"+"Name = "+name);
}catch(JSONException e){
e.printStackTrace();
}
res.getWriter().print(sWriter.toString());
out.flush();
out.close();
}//doGet
}//class
This code is working fine and giving me this output:
{"Name":"Vahid","Nickname":null,"Salary":"15000.0","EmployeeId":"121","isPermanent":true}
Name = Vahid
My question is how can I get JSON Object as a whole (as POST request) in my servlet from client browser e.g. request.getParameter("?????");
//what will be parameter name of JSON object? OR I have to get one by one all elements of JSON object as request.getParameter("name");
UPDATE
Here is my html file:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="/js/jquery.min.js"></script>
<script>
var form = $('#form1');
$(document).ready(function(){
$('body').hide().fadeIn(5000);
$(".submit").click(function (e) {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
console.log(url);
data: $(form).serialize(),
success: function(msg){
var json = msg ;
$('#json').val(json);
}
});
});
});
</script>
<body><br>
<form name="input" action="/JSONServlet" method="POST" id="form1" enctype="text/plain">
First name: <input type="text" name="FirstName" id="Firstname" value=" "><br>
Last name: <input type="text" name="LastName" value=" "><br>
<br>
<input type="submit" value="Submit" class="submit">
</form>
</body>
When I write String name = request.getParameter("name");
then output is null
Here what am trying:
String name = request.getParameter("FirstName");
System.out.println(name);
PrintWriter out= response.getWriter();
try{
JSONObject json = new JSONObject(name);
out.println(json.get("name"));
}catch(JSONException e){
e.printStackTrace();
}
output is null