For smart Primates & ROBOTS (oh and ALIENS ).

Blogroll

Sunday, November 10, 2013

Simple JSON in JSP

Simple JSON in JSP

JSON is very lightweight than XML.Here is the simple example of JSON with java.
I have used "json-simple-1.1.1.jar" , so you need to download it.

index.jsp
---------------------
<%@ page import="org.json.JSONObject"%>
<%@ page import="javax.json.Json"%>
<%@ 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 datas = ({"msg":'Test Message'});
    var jsonobj=JSON.stringify(datas);
    $.ajax({
        data: {para:jsonobj},
        dataType: 'json',
        url: 'newjsp.jsp',
        type: 'POST',
        success: function(ans){
            alert(ans.res);    
        },
        error: function() {
            alert('Ajax readyState: '+xhr.readyState+'\nstatus: '+xhr.status + ' ' + err);
        }
    });
}
</script>


newjsp.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"));
System.out.println(jsonObj.get("msg"));
JSONObject obj = new JSONObject();
obj.put("res", "hello...");
out.print(obj);
%>


Share:

0 comments:

Post a Comment

How to make center align child div

 How to make center align child div?   Suppose you have 2 Div tag. And want the make inner tag center <div id="d1">      ...

Ads Inside Post

Powered by Blogger.

Arsip