Ajax response does not parse LocalDate - javascript

I need to pass Localdate as part of the Ajax response to jquery datatables. LocalDate field does not display its value. Instead it prints [object,Object]. Obviously, it means LocalDate was not deserialized. Can some one please explain how to deserialize Localdate to display it properly.
Below is my Jquery Code:
var table = $("#example").DataTable({
"bProcessing" : true,
"bServerSide" : true,
"sAjaxSource" : "jsonSource.web",
"aoColumns" : [
{
"mData" : "name"
}, {
"mData" : "position"
}, {
"mData" : "office"
}, {
"mData" : "phone"
}, {
"mData" : "salary"
}, {
"mData" : "dob"
}
],
columnDefs : [ {
targets : [ 5 ],
render : function(data, type, row) {
var json = JSON.stringify(data);
var date = JSON.parse(json);
console.log("json: " + json + "date : " + row);
return data;
}
}
} ]
});
Server Side code:
#RequestMapping(value = "/springPaginationDataTables.web", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody String springPaginationDataTables(HttpServletRequest request) throws IOException {
//Fetch search parameter
String searchParameter = request.getParameter("sSearch");
final String sortColumn = request.getParameter("iSortCol_0");
final String sortOrder = request.getParameter("sSortDir_0");
//Fetch Page display length
Integer pageDisplayLength = Integer.valueOf(request.getParameter("iDisplayLength"));
//Fetch the page number from client
Integer pageNumber = 0;
if (null != request.getParameter("iDisplayStart"))
pageNumber = (Integer.valueOf(request.getParameter("iDisplayStart"))/pageDisplayLength)+1;
System.out.println("sSearch : "+searchParameter);
System.out.println("pageDisplayLength : "+pageDisplayLength);
System.out.println("pageNumber : "+pageNumber);
System.out.println("iSortCol_0 : "+sortColumn);
System.out.println("sSortDir_0 : "+sortOrder);
List<Person> personsList = new ArrayList<Person>();
Person person2 = new Person();
person2.setName("John Landy");
person2.setPosition("System Architect");
person2.setSalary("$320,800");
person2.setOffice("NY");
person2.setPhone("999999999");
person2.setStart_date("05/05/2010");
person2.setDob(LocalDate.parse("1989-07-09"));
personsList.add(person2);
//apply server side search
//apply server side sort
//BuildDataTable object
PersonJsonObject personJsonObject = new PersonJsonObject();
//Set Total display record
personJsonObject.setiTotalDisplayRecords(500);
//Set Total record
personJsonObject.setiTotalRecords(500);
personJsonObject.setAaData(personsList);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json2 = gson.toJson(personJsonObject);
return json2;
}

I solved it. had to extend SimpleModule from codehaus to implement serialisation/deserialisation for LocalDate. Below is my code:
public class LocalDateSimpleModule extends SimpleModule{
public LocalDateSimpleModule(String name, Version version) {
super(name, version);
addSerializer(LocalDate.class, new JsonSerializer<LocalDate>() {
#Override
public void serialize(LocalDate value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
ToStringSerializer.instance.serialize(value, jgen, provider);
}
});
addSerializer(LocalDateTime.class, new JsonSerializer<LocalDateTime>() {
#Override
public void serialize(LocalDateTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
ToStringSerializer.instance.serialize(value, jgen, provider);
}
});
addDeserializer(LocalDate.class, new JsonDeserializer<LocalDate>() {
#Override
public LocalDate deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
return LocalDate.parse(jp.getText());
}
});
addDeserializer(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
#Override
public LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
return LocalDateTime.parse(jp.getText());
}
});
}
}
Register this module in servlet-springs.xml
<bean id="objectMapper" class="org.codehaus.jackson.map.ObjectMapper"/>
<bean name="localDateModule" class="packge.LocalDateSimpleModule">
<constructor-arg name="name" value="LocalDateModule" />
<constructor-arg name="version" ref="version" />
</bean>
<bean name ="version" class="org.codehaus.jackson.Version">
<constructor-arg value="1"/>//some value
<constructor-arg value="1"/>
<constructor-arg value="1"/>
<constructor-arg value=" "/>
</bean>

Related

Spring Boot - JQuery AJAX not doing anything

Hello I am facing problems with doing my first webclient working with jquery AJAX JSON
Actually if I am pressing submit at my webclient to add a contact to a contact List it is not doing anything for me someone can help me here?
If am using postman to send a request it is working but the informations doesnt display in the index (videolist [html]) it is just showing as usual text in
/url/{id}
This is my HTML
<!DOCTYPE html>
<html>
<head>
<title>Contact Archiv HTML</title>
<meta charset="utf-8">
<link rel="stylesheet" href="css/styles.css">
<link rel="stylesheet"
href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script type="text/javascript"
src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js">
</script>
<script type="text/javascript" src="ajaxfunctions.js"></script>
</head>
<body>
<div class="centerdiv">
<header><h1>Video Archiv</h1></header>
<section class="left">
<h1>Neues Video anlegen</h1>
<p>
<form id="newVideo">
<label>id:</label>
<input type="text" name="id" required="required" >
<label>vorname:</label>
<input type="text" name="vorname" required="required" >
<label>nachname:</label>
<input type="text" name="nachname" required="required" >
<label>anrede:</label>
<input type="text" name="anrede" required="required" >
<label>adresse:</label>
<textarea name="adresse" required="required" rows="10"></textarea>
<label>telefon:</label>
<input type="text" name="telefon" required="required">
<label>email:</label>
<input type="text" name="email" required="required">
<label>handy:</label>
<input type="text" name="handy" required="required" >
<br>
<input type="submit" id="newVideoButton">
</form>
</p>
</section>
<section class="right">
<h1>Meine Videos</h1>
<p>
<button id="loadtable">Laden</button>
<table id="videotable" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>id</th>
<th>vorname</th>
<th>nachname</th>
<th>anrede</th>
<th>adresse</th>
<th>telefon</th>
<th>email</th>
<th>handy</th>
</tr>
</thead>
</table>
</p>
</section>
<footer>Tested</footer>
</div>
</body>
</html>
This is my ajaxfunction:
//On Page load - register listeners and load existing videos in datatable
$(document).ready(function() {
loadDataTable();
//process the form newVideo
$("#newVideo").submit(function(event) {
postVideo(event);
});
//Load Datatable
$('#loadtable').click(function() {
loadDataTable();
});
});
function postVideo(event) {
// get the form data
var formData = {
'id' : $('input[name=id]').val(),
'vorname' : $('textarea[name=vorname]').val(),
'nachname' : $('input[name=nachname]').val(),
'anrede' : $('input[name=anrede]').val()
'adresse' : $('input[name=adresse]').val(),
'telefon' : $('textarea[name=telefon]').val(),
'email' : $('input[name=email]').val(),
'handy' : $('input[name=handy]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to
use (POST for our form)
contentType : 'application/json',
url : '/kontakte', // url where we want to POST
data : JSON.stringify(formData), // data we want to POST
success: function( data, textStatus, jQxhr ){
loadDataTable();
},
error: function( jqXhr, textStatus, errorThrown ){
console.log(errorThrown);
}
});
// stop the form from submitting the normal way and refreshing the
page
event.preventDefault();
}
function loadDataTable() {
var table = $('#videotable').DataTable({
destroy: true,
"ajax": {
"url": "/kontakte", //URL
"dataSrc": "" // Cause of flat JsonObjects
},
"columns": [
{ "data": "id" },
{ "data": "vorname" },
{ "data": "nachname" },
{ "data": "anrede" },
{ "data": "adresse" },
{ "data": "telefon" },
{ "data": "email" },
{ "data": "handy"}
]
});
}
Class Contact:
package RestPackage;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
public class Kontakte {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String vorname;
private String nachname;
private String anrede;
private String adresse;
private String telefon;
private String email;
private String handy;
public Kontakte() {}
public Kontakte(int id, String vorname, String nachname, String anrede,
String adresse, String telefon, String email, String handy) {
super();
this.id = id;
this.vorname = vorname;
this.nachname = nachname;
this.anrede = anrede;
this.adresse = adresse;
this.telefon = telefon;
this.email = email;
this.handy = handy;
}
public long getID() {
return id;
}
public void setID(int id) {
this.id = id;
}
public String getVorname() {
return vorname;
}
public void setVorname(String vorname) {
this.vorname = vorname;
}
public String getNachname() {
return nachname;
}
public void setNachname(String nachname) {
this.nachname = nachname;
}
public String getAnrede() {
return anrede;
}
public void setAnrede(String anrede) {
this.anrede = anrede;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public String getTelefon() {
return telefon;
}
public void setTelefon(String telefon) {
this.telefon = telefon;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getHandy() {
return handy;
}
public void setHandy(String handy) {
this.handy = handy;
}
}
My Controller:
package RestPackage;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import RestPackage.Kontakte;
#RestController
public class VerwaltungsController {
#Autowired
VerwaltungsService verwaltungsService;
#RequestMapping ("/kontakte")
public List<Kontakte> getKontakteList(){
return verwaltungsService.getKontakteList();
}
#RequestMapping("/kontakte/{id}")
public Kontakte getKontakt(#PathVariable Integer id) {
return verwaltungsService.getKontakt(id);
}
#RequestMapping(method=RequestMethod.POST, value="/kontakte")
public void addKontakt(#RequestBody Kontakte k) {
verwaltungsService.addKontakt(k);;
}
#RequestMapping(method=RequestMethod.PUT, value="/kontakte/{id}")
public void updateKontakt(#PathVariable Integer id, #RequestBody Kontakte
kontakt) {
verwaltungsService.updateKontakt(id, kontakt);
}
#RequestMapping(method=RequestMethod.DELETE, value="/kontakte/{id}")
public void deleteKontakt(#PathVariable Integer id) {
verwaltungsService.deleteKontakt(id);
}
}
Service Class:
package RestPackage;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import RestPackage.Kontakte;
#Service
public class VerwaltungsService {
#Autowired
private KontakteRepository kontakteRepository;
public List<Kontakte> getKontakteList() {
ArrayList<Kontakte> mylist= new ArrayList<>();
Iterator<Kontakte> it = kontakteRepository.findAll().iterator();
while(it.hasNext())
mylist.add(it.next());
return mylist;
}
public Kontakte getKontakt(#PathVariable Integer id) {
return kontakteRepository.findOne(id);
}
public void addKontakt(#RequestBody Kontakte kontakt) {
kontakteRepository.save(kontakt);
}
public void updateKontakt(#PathVariable Integer id, #RequestBody Kontakte
kontakt) {
Kontakte k = kontakteRepository.findOne(id);
k.setVorname(kontakt.getVorname());
k.setNachname(kontakt.getNachname());
k.setAdresse(kontakt.getAdresse());
k.setAnrede(kontakt.getAnrede());
k.setEmail(kontakt.getEmail());
k.setHandy(kontakt.getHandy());
k.setTelefon(kontakt.getTelefon());
kontakteRepository.save(k);
}
public void deleteKontakt(#PathVariable Integer id) {
kontakteRepository.delete(id);
}
}
CrudRep. Interface:
package RestPackage;
import org.springframework.data.repository.CrudRepository;
import RestPackage.Kontakte;
public interface KontakteRepository extends CrudRepository<Kontakte,
Integer> {
}
There is , missing in the mapping of the input properties. I also advice you to start using the console (key F12) to debug the code and discover problems easly.

Filtering datatable with dropdown select

I am trying to filter datatable by select.
I can see the data in select but don't know how to filter it.
Here's my code.
Thanks
function getSearchList() {
$.post('#(Url.Action("GetSearchList", "ESR"))')
.success(function (data) {
if (data.length > 0) {
$.each(data, function () {
$('#Search_Id').append($('<option>', {
value: this.ID,
text: this.S_ID
}));
});
}
$(window).unblock();
})
}
and
$(document).ready(function () {
$('#Search_Id').select2({
placeholder: "Search",
allowClear: true,
});
});
and
<div class="col-sm-2">
<select class="select" id="Search_Id"></select>
</div>
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
public List<SearchId> GetSearchIdData()
{
string strSQL = string.Format(#"SELECT ID, S_ID FROM TBR");
using (var conn = SqlUtility.GetDBConnection())
{
conn.Open();
return conn.Query<SearchId>(strSQL).ToList();
}
}
and
public ActionResult GetSearchIdList()
{
JsonResult result;
List<SearchId> List = service.GetSearchIdList();
result = Json(List);
result.MaxJsonLength = int.MaxValue;
return result;
}
and
public class SearchId
{
public int ID { get; set; }
public string S_ID{ get; set; }
}
and
public List<SearchId> GetSearchIdList()
{
return repo.GetSearchIdData();
}

issue in display of html content stored in database in java

Here i am trying to display html content stored in database.When i try it to display in js it gives me "Uncaught ReferenceError: VAR_1 is not defined" in console.
Database:
<div id="dashboard-greeting" class="museo">
<div class="dashboard-greeting-instructions">
<span>Track Progress</span>
<div class="dashboard-greeting-counter round">
<div class="dashboard-counter-label">Courses Completed</div>
<div class="dashboard-counter-value">VAR_1</div>
</div>
<div class="dashboard-greeting-counter round">
<div class="dashboard-counter-label">Courses Needed</div>
<div id="subNeeded" class="dashboard-counter-value"></div>
<script>
var subNeedVar = VAR_2 - VAR_1;
$("#subNeeded").html(subNeedVar);
</script>
</div>
</div>
</div>
.js
<div class="tool-button-container">
<input type="submit" name="View" value="LookUp" id="campaignSubmit" class="buOrange large" onClick="validateConfigValues('configKeyName');"/> </div>
function validateConfigValues(id1){
$.ajax({
type: 'POST',
url: '<%=request.getContextPath()%>/adminConfigTest',
data: ({configKeyName:configKeyName, clientId :clientId ,batchId : batchId, languageId : languageId}),
cache: false,
success: function(data) {
var deleteCachingBtn = $('<br><div id="deleteBtn"><Button id="deleteCaching" name="deleteCaching" class="buOrange large" onClick=deleteFromCaching(\'' + configKeyName + '\')> Remove from Cache </div>');
var displayStringAppData = "";
var obj = JSON.parse(data);
$.each(obj, function(index,value) {
displayStringAppData = displayStringAppData+"<br>"+value+"<br>";
alert("displayStringAppData"+displayStringAppData);
});
$("#dbModelWindow").html(displayStringAppData);
if(~data.indexOf("Config is not found in DB also.")) {
} else {
$("#dbModelWindow").append(deleteCachingBtn);
}
$('#dbModelWindow').modal({
"escClose": true,
"overlayClose": true,
"onShow": function() { $.modal.setContainerDimensions();},
});
},
error: function(xhr, textStatus, error){
alert("Error occured. Please try after some time.");
}
});
}
}
.java
#RequestMapping(value="/adminConfigTest", method= RequestMethod.POST)
#PreAuthorize("hasPermission(#adminConfigTest,'ADMIN_TEXT_CONFIG')")
#ResponseBody
public String getAdminConfigTestPost(HttpServletRequest request) throws Exception {
String configKeyName = request.getParameter("configKeyName");
String clientId = request.getParameter("clientId");
String batchId = request.getParameter("batchId");
String language = request.getParameter("languageId");
List<String> arrList = new ArrayList<String>();
try{
Number languageId = null;
if(StringUtils.isBlank(language)){
languageId = RCConstants.ENGLISH_LANGUAGE_ID;
} else {
languageId = Long.parseLong(language);
}
if(StringUtils.isBlank(clientId)){
configManager.getConfigValue(configKeyName, null, "", false, true, languageId, arrList);
}
if(!StringUtils.isBlank(clientId) && StringUtils.isBlank(batchId)){
configManager.getConfigValue(configKeyName, Long.parseLong(clientId), "", false, true, languageId, arrList);
}
if(!StringUtils.isBlank(batchId)){
configManager.getConfigValue(configKeyName, Long.parseLong(batchId), languageId, arrList);
}
} catch (Exception e) {
logger.error(e ,e);
throw e;
}
return JSONSerializer.toJSON(arrList).toString();
}
public String getConfigValue(String configKey, Number batchId, Number languageId, List<String> arrList)throws Exception{
if(arrList != null){
arrList.add("Get config value for : "+ configKey);
arrList.add("batch Id : "+ batchId);
arrList.add("Language : "+ StringUtils.getLanguageCode(languageId));
}
try{
String configKeyValue = null;
String localConfigKeyWithBatchId = batchId+"-"+configKey+"-"+StringUtils.getLanguageCode(languageId);
String queryString = "from Config as model where model.configKeyName = ? and model.batchMetaDataId = ? and model.languageId = ? and model.isDeleted = 0" ;
List<Config> configList = getHibernateTemplate().find(queryString, configKey , batchId ,languageId);
if(!configList.isEmpty()) {
for (Config config : configList) {
configKeyValue = config.getConfigKeyValue();
}
CacheUtil.put(RCConstants.LOCAL_CACHE_WITH_BATCH,localConfigKeyWithBatchId, configKeyValue);
logger.debug("Returning value from db : "+configKey+" - "+configKeyValue);
if(arrList != null){
arrList.add("Db: returning batch and language specific value : " + configKeyValue );
}
}
return configKeyValue;
} catch (RuntimeException re) {
log.error(re, re);
throw re;
}
}
CacheUtil.java
public static Cache localEhCache = null;
public static Cache localEhCacheWithBatchId = null;
public static void put(int cacheNumber, Object key, Object value) {
if (cacheNumber == RCConstants.LOCAL_CACHE) {
localEhCache.put(new Element(key, value));
} else if (cacheNumber == RCConstants.LOCAL_CACHE_WITH_BATCH) {
localEhCacheWithBatchId.put(new Element(key, value));
}
}
But if i rewrite VAR_1 again by erasing VAR_1. It wont show this error.
I googled about this topic but didn't find any solution.
Please help me or suggest me what is going wrong here.

How to get selected item from AUI autocomplete list

I want to show address in my database to an autocomplete aui input field.Everything seems working fine.But im not able to retrive the address number of the record.How to use the on change event of autocomple-list or how can i access the selected item's json object
#Override
public void serveResource( ResourceRequest resourceRequest, ResourceResponse resourceResponse ) throws IOException,
PortletException
{
String cmd = ParamUtil.getString(resourceRequest, "get_address");
String myInputNode = ParamUtil.getString(resourceRequest, "addressAutocomplete");
System.out.println("addressAutocomplete"+myInputNode);
if (cmd.equals("get_address")) {
getUsers(resourceRequest, resourceResponse,myInputNode);
}
}
private void getUsers(ResourceRequest resourceRequest, ResourceResponse resourceResponse, String myInputNode) throws IOException, PortletException {
JSONArray usersJSONArray = JSONFactoryUtil.createJSONArray();
ThemeDisplay themeDisplay = (ThemeDisplay)resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);
JSONObject userJSON=null;
try {
List<AddressMaster> userList=AddressMasterLocalServiceUtil.getAllAddressBySearchKey( myInputNode );
for(AddressMaster addressMaster:userList){
userJSON=JSONFactoryUtil.createJSONObject();
userJSON.put("addressNumber",addressMaster.getAdrNummer());
userJSON.put( "address", addressMaster.getAddress())
);
usersJSONArray.put(userJSON);
}
} catch (Exception e) {
}
PrintWriter out=resourceResponse.getWriter();
out.println(usersJSONArray.toString());
System.out.println("usersJSONArray"+usersJSONArray.toString());
}
Jsp File
<portlet:resourceURL var="getAddress">
<portlet:param name="get_address" value="get_address" />
</portlet:resourceURL>
<aui:input id="addressAutocomplete" name="addressAutocomplete" label="group_choose_address" style="width:700px"/>
<aui:script>
AUI().use('autocomplete-list','aui-base','aui-io-request','autocomplete-filters','autocomplete-highlighters',function (A) {
A.io.request('<%=getAddress%>',{
dataType: 'json',
method: 'GET',
on: {
success: function() {
//continents=this.get('responseData');
//alert(continents[0].name);
new A.AutoCompleteList(
{
allowBrowserAutocomplete: 'true',
activateFirstItem: 'true',
inputNode: '#<portlet:namespace/>addressAutocomplete',
resultTextLocator: 'address',
resultHighlighter:['phraseMatch'],
resultFilters:['phraseMatch'],
render: 'true',
source:this.get('responseData'),
});
}}
});
});
</aui:script>
It's a bit tricky to see exactly what'll be coming, but I think you could do:
var address_ac = new A.AutoCompleteList({... as you have it...});
address_ac.on('select', function (e) {
var selected_node = e.itemNode,
selected_data = e.result;
});
Docs here: http://alloyui.com/versions/1.5.x/api/classes/AutoCompleteList.html#events

Cant call a servlet from ExtJs controller

i have a controller in extjs application, from where i have to call a servlet. But i am unable to call that servlet from controller here is my controller code .....
when i am running the application always failure part is showing "server-side failure with status code" this is the problem:
Ext.define('Gamma.controller.ControlFile', {
extend : 'Ext.app.Controller',
//define the stores
stores : ['BarColumn',
'RadarView',
'VoiceCallStore',
'SMSCallStore',
'MMSCallStore',
'GPRSUsageStore'],
//define the models
models : ['BarCol',
'radar',
'VoiceCallModel',
'SMSCallModel',
'MMSCallModel',
'GPRSUsageModel'],
//define the views
views : ['BarColumnChart',
'LineChart',
'RadarChart',
'VoicePie',
'SMSPie',
'MMSPie',
'GPRSPie'],
initializedEvents: false,
init: function() {
this.control({
'#barColumnChart': {
afterlayout: this.afterChartLayout
}
});
},
afterChartLayout: function(){
var me=this;
if(this.initializedEvents==true) return;
this.initializedEvents=true;
Ext.getCmp('barColumnChart').series.items[0].on('itemmousedown',function(obj){
// alert(obj.storeItem.data['source']+ ' &' + obj.storeItem.data['count']);
var barData=obj.storeItem.data['source']+ ' &' + obj.storeItem.data['count'];
me.dataBaseCall(obj.storeItem.data['source'],obj.storeItem.data['count']);
});
},
dataBaseCall: function(source,count){
//alert(barData);
Ext.Ajax.request({
url: "CallRatiosAnalysis",
success: function(response, opts){
//do what you want with the response here
console.log("hiiiiiiiiiiii");
},
failure: function(response, opts) {
alert("server-side failure with status code " + response.status);
},
params: {
source: source,
count: count
}
});
}
});
and this is my Servlet:
public class CallRatiosAnalysis extends HttpServlet {
public CallRatiosAnalysis() {
super();
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String start = request.getParameter("start");
String limit = request.getParameter("limit");
PrintWriter out = response.getWriter();
response.setContentType("text/html");
ArrayList<IndCallType> ratios = new ArrayList<IndCallType>();
ratios.add(new IndCallType("Voice", "40"));
ratios.add(new IndCallType("SMS", "30"));
ratios.add(new IndCallType("MMS", "5"));
ratios.add(new IndCallType("GPRS", "20"));
ratios.add(new IndCallType("Others", "5"));
Gson gson = new Gson();
JsonArray arrayObj = new JsonArray();
for (int i = 0; i < ratios.size(); i++) {
IndCallType count = ratios.get(i);
JsonElement linObj = gson.toJsonTree(count);
arrayObj.add(linObj);
}
JsonObject myObj = new JsonObject();
myObj.addProperty("success", true);
myObj.add("allCalls", arrayObj);
myObj.addProperty("allCallsRatio", ratios.size());
out.println(myObj.toString());
out.close();
}
}
This is the servlet where I have some dummy data and made json object to that data

Categories

Resources