Ads Inside Post

Search in This Blog

Post multiple and return values from JSON in JSP

JSON is very lightweight than XML. Here is the some hard JSON example with multiple values post and
multiple return values.
I have used "json-simple-1.1.1.jar" , so you need to download it.

index.jsp
---------------------
<%@ page import="org.json.JSONObject"%>
<%@ page import="java.io.PrintWriter"%>
<script src="jquery-1.10.2.js" type="text/javascript"></script>
<input type="button" value="send" onclick="dook();"/>
<script>
function dook() {
    var article = new Object();
    article.title = "Title Name";
    article.url = "Url Name";
    article.categories ="Categories  Name";
    article.tags = "Tags Name";
    var jsonobj=JSON.stringify(article);
    $.ajax({
        data: {para:jsonobj},
        dataType: 'json',
        url: 'newjsp1.jsp',
        type: 'POST',
        success: function(jsonObj){
            alert(jsonObj.title);
            alert(jsonObj.url);
            alert(jsonObj.categories);
            alert(jsonObj.tags);
            alert(jsonObj.rate); 
        },
        error: function() {
            alert('readyState: '+xhr.readyState+'\nstatus: '+xhr.status + ' ' + err);
        }
    });
}
</script>



newjsp1.jsp
=======================
<%@ page import="java.io.PrintWriter"%>
<%@ page import="org.json.simple.JSONObject"%>
<%@ page import="org.json.simple.JSONValue"%>
<%
request.setCharacterEncoding("utf8");
response.setContentType("application/json");
PrintWriter outt = response.getWriter();
JSONObject jsonObj = (JSONObject) JSONValue.parse(request.getParameter("para"));
String title=jsonObj.get("title").toString();
String url=jsonObj.get("url").toString();
String categories=jsonObj.get("categories").toString();
String tags=jsonObj.get("tags").toString();
String rate="450.00";
System.out.println(jsonObj.get("title"));
JSONObject obj = new JSONObject();
obj.put("title", title);
obj.put("url", url);
obj.put("categories", categories);
obj.put("tags", tags);
obj.put("rate", rate);
out.print(obj);
%>