Issue
I am trying to get JSON
response which has been set in servlet
to a JSP
page.
JSP page:
<script>
$(document).ready(function(){
$("#submitBut").click(function(){
var formData=getFormData();
var strUrl="rwcntrlr.do?action=loginForm";
$.post(strUrl, {jsonData: JSON.stringify(formData)},function(response){
response = jQuery.parseJSON( response);
if(response.message=='not ok')
{
alert("not ok");
}
else{
alert('OK');
}
});
});
});
</script>
Servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String formName=request.getParameter("action");
if(formName.equalsIgnoreCase("loginForm")){
String strJSONData = request.getParameter("jsonData");
System.out.println(strJSONData);// data received correctly...
JSONObject jsonResponse = new JSONObject();
try{
JSONObject requestedJSONObject = new JSONObject(strJSONData);
String login_name = requestedJSONObject.getString("login_name");
String password = requestedJSONObject.getString("password");
if(login_name.equalsIgnoreCase("mark")){
response.setContentType("application/json");
jsonResponse.put("status", "OK");
response.getWriter().write(jsonResponse.toString());
}
else{
response.setContentType("application/json");
jsonResponse.put("status", "NOT OK");
response.getWriter().write(jsonResponse.toString());
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
in above code I am able to get form data in a JSON pattern in my servlet controller.
But I am not able show valid alert
boxes back to JSP page based on JSON type message sent by servlet as response.
Solution
To write to the response you should use something like
response.setContentType("application/json");
response.setHeader("cache-control", "no-cache");
PrintWriter out = response.getWriter();
out.println(jsonResponse.toString());
out.flush();
Note, cache control usually prevents the browser from caching the value. And your text written to the out is too small to fill the buffer. Flush the buffer before returning the response.If you set the content type "application/json" you don't need to parse object, unless it converted to text by jQuery. Use dataType: 'json'
option to get the JSON object.
$.post(strUrl, {jsonData: JSON.stringify(formData)},
function(response){
if(response.status=='NOT OK') {
alert("not ok");
} else {
alert('OK');
}
}, 'json');
Answered By - Roman C