Getting started with JSON and Java Web application
UPDATED: 05 February 2013
Tags:
How to
,
J2EE
,
javaScript
What is JSON?
JSON stands for JavaScript Object Notation. Its text-based open standard designed for human-readable data interchange. To know more about JSON read the wikipedia . Here is how JSON object holds the data.
{
"firstName": "Vicky",
"lastName": "Thakor",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumber": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
]
}
Why use JSON in java web-application?
Its time to develop web-application that perform operation faster. Say if you want to process data without refreshing current page/content JSON is perfect solution for you. I'm going to show you quick demo with validating the email.
Download the JSON library for Java from sourceforge https://sourceforge.net/projects/javaqueryapi/files/
validateEmail.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Validate Email Address</title>
</head>
<body>
<input name="email" id="email"/>
<span id="result"></span>
<input type="button" value="check" id="check"/>
<script src="../staticCDN/js/jquery-1.8.2.min.js"></script>
<script>
$("#check").click(function(){
var emailID = $("#email").val();
$.get('emailJSON.jsp',{email:emailID},function(data){
var obj = eval ("(" + data + ")");
var status = obj.status;
if(status=="FAIL"){
alert(obj.notify_error);
}else{
//SUCCESS
$("#result").html("Email is Okay!");
}
})
});
</script>
</body>
</html>
emailJSON.jsp
<%@page import="org.json.JSONObject"%>
<%@page import="javaQuery.validation.validate"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
String email = request.getParameter("email");
validate vEmail = new validate();
JSONObject status = new JSONObject();
if(vEmail.Email(email)){
status.put("status", "SUCCESS");
status.put("notify_error", "Email is Okay!");
out.print(status);
}else{
status.put("status", "FAIL");
status.put("notify_error", "Provide valid email!");
out.print(status);
}
%>
Hope you get proper idea of JSON by checking all above codes. If you have any problem let me know.
Output of Demo:
Tags:
How to
,
J2EE
,
javaScript

0 comments :