I am trying to call servlet from html through script, for get the user data(say receipt number) , in servlet, it connects to db and get the document no and document date. when i view the reponsetext, i am getting undefined value. Please help me on how to get response text in proper way.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script>
function showCustomer(num) {
var kkk = document.getElementById("num").value;
alert("this is mango1 "+kkk);
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("pono").innerHTML = xmlhttp.responseText;
alert(demo);
}
};
xmlhttp.open("POST", "callserv1?num="+kkk, true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="">
Receipt no <input type="text" name="num" id="num"/>
<input type="button" onclick="showCustomer(num)" value ="call"/>
<p id="demo">Customer info will be listed here...
PO no <input type="text" name="pono" id="pono"/>
Po date <input type="text" name="podt" id="podt"/></p>
</form>
</body>
</html>
import static java.lang.System.out;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class callserv1 extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String grnxx = request.getParameter("num");
String pono = null;
String podt = null;
System.out.println("I am in Servlet");
System.out.println("input receipt number received: " +grnxx);
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("db connection');
Statement st=con.createStatement();
System.out.println("Connection estabilished"+con);
//Input query to get PO and Itemlist for given GRn
ResultSet rs=st.executeQuery("!!!!DB query!!!");
while(rs.next()) {
pono = rs.getString("doc");
podt = rs.getString("dt");
System.out.println("Pono:---- "+pono);
System.out.println("Podt:---- "+podt);
}
con.close();
System.out.println("DB Connection closed successfully");
request.setAttribute("pono", pono);
request.getRequestDispatcher("index.html").include(request,response);
} catch (Exception e) {
System.out.println("Connection error: "+e);
}
}
}
Related
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.
Why won't the grid populate?
I have JSON string generated dynamically using java. (main . java)
[gif image of json string generation][1]
package com.queryData.main;
import com.queryData.dao.DataDAO;
import com.queryData.services.JsonServices;
import java.sql.ResultSet;
import java.util.List;
import org.json.JSONObject;
public class Main {
ResultSet resultSet = null;
DataDAO datadao = new DataDAO();
public List<JSONObject> getJsonObject() {
resultSet = datadao.getResultSet();
List<JSONObject> resList = JsonServices.getFormattedResult(resultSet);
return resList;
}
public static void main(String[] args) {
Main m = new Main();
List<JSONObject> jObj = m.getJsonObject();
for (int i = 0; i < jObj.size(); i++) {
System.out.println(jObj.get(i));
}
}
}
I have paramQuery grid loading but have a problem with the dataModel to load the data. (index . xhtml)
[gif image of grid loading with no data][2]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head>
<!--jQuery dependencies-->
<link rel="stylesheet"
href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/base/jquery-ui.css" />
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<!--ParamQuery Grid files-->
<h:outputStylesheet name="css/pqgrid.min.css" />
<h:outputScript name="js/pqgrid.min.js" />
<!--Include Touch Punch file to provide support for touch devices-->
<h:outputScript name="js/jquery.ui.touch-punch.js" />
<script>
$(function(){
var obj = {};
obj.width = 700;
obj.height = 400;
obj.colModel = [
{ title: "Person ID", width:100, dataIndx: "person_id"},
{ title: "Full Name", width:200, dataIndx: "fullname"},
{ title: "First Name", width:150, dataIndx: "firstname"},
{ title: "Last Name", width:150, dataIndx: "lastname"}
];
<!-- reference to load remote data -->
var dataModel = {
recIndx: "personid",
location: "remote",
sorting: "local",
paging: "local",
dataType: "JSON",
method: "GET",
sortIndx: "lastname",
sortDir: "up",
url: "main.java"
, getData: function (dataJSON) {
var data = dataJSON.data;
return { data: dataJSON.data };
}
}
<!-- KEY PART TO LOAD DATA -->
$("div#grid_array").pqGrid( obj );
});
</script>
</h:head>
<h:body>
<div id="grid_array"></div>
</h:body>
</html>
I have altered the URL but do not know how the URL reference should be written, below is the script I am currently trying to correct
<h:head>
<!--jQuery dependencies-->
<link rel="stylesheet"
href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/base/jquery-ui.css" />
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<!--ParamQuery Grid files-->
<h:outputStylesheet name="css/pqgrid.min.css" />
<h:outputScript name="js/pqgrid.min.js" />
<!--Include Touch Punch file to provide support for touch devices-->
<h:outputScript name="js/jquery.ui.touch-punch.js" />
<script>
$(function()
{
<!-- reference to load remote data -->
var dataModel =
{
location: "remote",
sorting: "local",
dataType: "JSON",
method: "GET",
url: "json",
getData: function (dataJSON) {return { data: dataJSON.data };}
}
<!-- reference to create column titles -->
var obj = {dataModel:dataModel};
obj.colModel =
[
{ title: "Person ID", width:100, dataIndx: "person_id"},
{ title: "Full Name", width:200, dataIndx: "fullname"},
{ title: "First Name", width:150, dataIndx: "firstname"},
{ title: "Last Name", width:150, dataIndx: "lastname"}
];
<!-- reference to initiate the request -->
$("div#grid_array").pqGrid( obj );
}
);
</script>
</h:head>
<h:body>
<div id="grid_array"></div>
</h:body>
These are the two servlets that generate the JSON string, I need to modify from being a LIST to a string to generate JSON data in this format.
{"data": [ row1, row2, ..] }
and retrievable through a URL via GET HTTP request in my VIEW index . xhtml
The two beans and the one index VIEW:
first bean -
package com.queryData.services;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONObject;
public class JsonServices {
public static List<JSONObject> getFormattedResult(ResultSet rs) {
// List<JSONObject> resList = new ArrayList<JSONObject>();
List<JSONObject> resList = "{\"data\":" + new ArrayList<JSONObject>() + "}";
// above is the attempt to modify
try {
// get column names
ResultSetMetaData rsMeta = rs.getMetaData();
int columnCnt = rsMeta.getColumnCount();
List<String> columnNames = new ArrayList<String>();
// loop to get all column names
for (int i = 1; i <= columnCnt; i++) {
// adding all retrieved column names to List object
columnNames.add(rsMeta.getColumnName(i).toUpperCase());
}
while (rs.next()) {
// convert each object to an human readable JSON object
JSONObject obj = new JSONObject();
for (int i = 1; i <= columnCnt; i++) {
String key = columnNames.get(i - 1);
String value = rs.getString(i);
obj.put(key, value);
}
resList.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return resList;
}
}
second bean -
package com.queryData.main;
import com.queryData.dao.DataDAO;
import com.queryData.services.JsonServices;
import java.sql.ResultSet;
import java.util.List;
import org.json.JSONObject;
public class Main {
ResultSet resultSet = null;
DataDAO datadao = new DataDAO();
public List<JSONObject> getJsonObject() {
resultSet = datadao.getResultSet();
List<JSONObject> resList = JsonServices.getFormattedResult(resultSet);
return resList;
}
public static void main(String[] args) {
Main m = new Main();
List<JSONObject> jObj = m.getJsonObject();
for (int i = 0; i < jObj.size(); i++) {
System.out.println(jObj.get(i));
}
}
}
VIEW index . xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/base/jquery-ui.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"/>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"/>
<h:outputStylesheet name="css/pqgrid.min.css"/>
<h:outputScript name="js/pqgrid.min.js"/>
<h:outputScript name="js/jquery.ui.touch-punch.js"/>
<script>
$(function(){
var obj = {};
obj.width = 700;
obj.height = 400;
obj.colModel = [
{ title: "Person ID", width:100, dataIndx: "person_id"},
{ title: "Full Name", width:200, dataIndx: "fullname"},
{ title: "First Name", width:150, dataIndx: "firstname"},
{ title: "Last Name", width:150, dataIndx: "lastname"}
];
var dataModel = {
recIndx: "personid",
location: "remote",
sorting: "local",
paging: "local",
dataType: "JSON",
method: "GET",
sortIndx: "lastname",
sortDir: "up",
url: "main"
, getData: function (dataJSON) {
var data = dataJSON.data;
return { data: dataJSON.data };
}
}
$("div#grid_array").pqGrid( obj );
});
</script>
</h:head>
<h:body>
<div id="grid_array"></div>
</h:body>
</html>
The deployed test app can be viewed at deployed test run
You can do as follow:
Create a backing bean
Persons.java
#ManagedBean(name="persons")
#SessionScoped
public class Persons {
ResultSet resultSet = null;
DataDAO datadao = new DataDAO();
public List<JSONObject> people = JsonServices.getFormattedResult(datadao.getResultSet());
/** getter and setter **/
}
In your xhtml, you add a hidden element where you put data from backing bean
<h:inputHidden id="hiddenPeople" value="#{persons.people}" />
In your xhtml, javascript section
<script>
$(function() {
var peopleList = $('#hiddenPeople');
var peopleJson = JSON.parse(peopleList)
// display peopleJson
});
</script>
Now, I am not sure if the List people will be converted to a string, so you may want to convert that to a String rather than a List.
I have retrieved database records of dates and filled it into a JSON Object. I am trying to send the JSON to javascript so that the DatePicker UI will be dynamic by having whatever dates that has been saved in the JSON to be unavailable on the calendar.
However, it doesn't seem to be working correctly as all dates on the calendar are unselectable .
index.jsp
<%#page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" type="text/css" media="all" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
var dates;
$.ajax({
url:'dating',
type:'post',
data: {
action: 'unavail_dates',
unavaildates: '2'
},
success: function (data) {
dates = data;
console.log ( dates );
}
});
$('#MyDate').datepicker({
dateFormat: 'dd-mm-yy',
beforeShowDay: function (date) {
var string = $.datepicker.formatDate('yy/mm/dd', date);
return [dates != undefined && $.inArray(string, dates) > -1];
},
onSelect: function (dateText) {
jQuery(this).change();
}
});
});
</script>
</head>
<body>
<tr id="tr1">
<td>Select appointment date: </td>
<td><input type="text" id="MyDate" value="" /></td>
</tr>
</body>
</html>
dating.java
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
import object.Dates;
/**
* Servlet implementation class dating
*/
public class dating extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public dating() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String dbName = "eBooking";
String uname = "user";
String pwd = "user";
String url = "jdbc:mysql://localhost:3306/" + dbName;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(url, uname, pwd);
System.out.println("Connection Established: " + con);
String qry = "select bookedDate from appointment_booked";
st = con.createStatement();
rs = st.executeQuery(qry);
PrintWriter out= response.getWriter();
JSONObject jObj = new JSONObject();
ArrayList < Dates > list = new ArrayList < Dates > ();
Map < String, String > map = new HashMap < String, String > ();
Dates sPojo = null;
while (rs.next()) {
sPojo = new Dates();
sPojo.setDates(rs.getString("bookedDate"));
list.add(sPojo);
}
System.out.println(list);
jObj.put("dates", list);
out.print(jObj);
System.out.println(jObj.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>databaseJson</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>dating</display-name>
<servlet-name>dating</servlet-name>
<servlet-class>servlet.dating</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dating</servlet-name>
<url-pattern>/dating</url-pattern>
</servlet-mapping>
</web-app>
You have async request $.ajax, so success function is executed after datepicker is activated. You have to move its initialization of datepicker inside success function.
This command...i.e.,
$http.get('http://localhost:8084/nggridtest/tasks')
.success(function (data)
{
alert(JSON.stringify(data));
$scope.tasks = data; // <=== not working???
});
... appears to successfully retrieve data - as shown by my alert...i.e.,
However, it appears that the command - $scope.tasks = data; - does not appear assign the data to my "$scope.tasks" variable - resulting in an empty grid... i.e.,
What am I doing wrong here?
Thanks for your help!!
(angularjs newby)
BELOW IS MORE INFO, IF NEEDED...
app.js
/* global angular */
var taskApp = angular.module('taskApp', ['ngGrid']);
var taskController = taskApp.controller('taskController', function taskController($scope, $http)
{
$http.get('http://localhost:8084/nggridtest/tasks')
.success(function (data)
{
alert(JSON.stringify(data));
$scope.tasks = data;
});
$scope.gridOptions = {
data: 'tasks',
columnDefs: [
{field: 'taskId', displayName: 'taskId'},
{field: 'taskName', displayName: 'taskName'},
{field: 'taskDescription', displayName: 'taskDescription'},
{field: 'taskStartTime', displayName: 'taskStartTime'},
{field: 'taskEndTime', displayName: 'taskEndTime'},
{field: 'taskArchived', displayName: 'taskArchived'}
]
};
});
app.css
.gridStyle
{
margin: 0;
width:100em;
height:50em;
}
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!doctype html>
<html ng-app="taskApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC, REST, AngularJS testing</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/webjars/jquery/2.1.4/jquery.css" media="screen">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/webjars/ng-grid/2.0.14/ng-grid.css" media="screen">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/webjars/bootstrap/3.3.1/css/bootstrap.css" media="screen">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/resources/js/app.css" media="screen"/>
<script type="text/javascript" src="${pageContext.request.contextPath}/webjars/jquery/2.1.4/jquery.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/webjars/angularjs/1.4.4/angular.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/webjars/ng-grid/2.0.14/ng-grid.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/webjars/bootstrap/3.3.1/js/bootstrap.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/app.js"></script>
</head>
<body>
<div ng-controller="taskController">
<div class='panel panel-primary row container-fluid' style="margin: 2em; padding:0;">
<div class='panel-heading' style="margin: 0;">
<h1 class='panel-title'>Entries</h1>
</div>
<div class='panel-body' style="padding:0;">
<div class="gridStyle" ng-grid="gridOptions"></div>
</div>
</div>
</div>
</body>
</html>
TaskController.java
package aaa.bbb.ccc.war;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#RestController
#EnableWebMvc
public class TaskController
{
private static final org.apache.logging.log4j.Logger LOG = LogManager.getLogger("TaskController");
TaskService taskmanagerservice = new TaskService();
#RequestMapping(value = "/tasks", method = RequestMethod.GET, headers = "Accept=application/json")
public List<Task> getAllTasks()
{
List<Task> tasks = null;
try
{
tasks = taskmanagerservice.getAllTasks();
}
catch (Exception e)
{
LOG.error("____________________________getAllTasks____________________________Exception encountered - e.getMessage=" + e.getMessage(), e);
}
return tasks;
}
}
TaskService.java
package aaa.bbb.ccc.war;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
public class TaskService
{
private static final org.apache.logging.log4j.Logger LOG = LogManager.getLogger("TaskService");
private Connection connection;
public TaskService()
{
connection = DBUtility.getConnection();
}
public List<Task> getAllTasks()
{
List<Task> tasks = null;
try
{
tasks = new ArrayList<Task>();
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from task_list where task_archived=false");
while (rs.next())
{
Task task = new Task();
task.setTaskId(rs.getInt("task_id"));
task.setTaskName(rs.getString("task_name"));
task.setTaskDescription(rs.getString("task_description"));
task.setTaskPriority(rs.getString("task_priority"));
task.setTaskStatus(rs.getString("task_status"));
tasks.add(task);
}
}
catch (SQLException e)
{
LOG.error("____________________________getAllTasks____________________________Exception encountered - e.getMessage=" + e.getMessage(), e);
}
return tasks;
}
}
DBUtility
package aaa.bbb.ccc.war;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.logging.log4j.LogManager;
public class DBUtility
{
private static final org.apache.logging.log4j.Logger LOG = LogManager.getLogger("DBUtility");
private static Connection connection = null;
public static Connection getConnection()
{
if (connection != null)
{
return connection;
}
else
{
try
{
Properties prop = new Properties();
InputStream inputStream = DBUtility.class.getClassLoader().getResourceAsStream("/config.properties");
prop.load(inputStream);
String driver = prop.getProperty("driver");
String url = prop.getProperty("url");
String user = prop.getProperty("user");
String password = prop.getProperty("password");
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
}
catch (ClassNotFoundException e)
{
LOG.error("____________________________getConnection____________________________ClassNotFoundException", e);
}
catch (SQLException e)
{
LOG.error("____________________________getConnection____________________________SQLException", e);
}
catch (FileNotFoundException e)
{
LOG.error("____________________________getConnection____________________________FileNotFoundException", e);
}
catch (IOException e)
{
LOG.error("____________________________getConnection____________________________IOException", e);
}
return connection;
}
}
}
Task.java
package aaa.bbb.ccc.war;
public class Task
{
private int task_id;
private String task_name;
private String task_description;
private String task_priority;
private String task_status;
public int getTaskId()
{
return task_id;
}
public void setTaskId(int taskId)
{
this.task_id = taskId;
}
public String getTaskName()
{
return task_name;
}
public void setTaskName(String taskName)
{
this.task_name = taskName;
}
public String getTaskDescription()
{
return task_description;
}
public void setTaskDescription(String taskDescription)
{
this.task_description = taskDescription;
}
public String getTaskPriority()
{
return task_priority;
}
public void setTaskPriority(String taskPriority)
{
this.task_priority = taskPriority;
}
public String getTaskStatus()
{
return task_status;
}
public void setTaskStatus(String taskStatus)
{
this.task_status = taskStatus;
}
#Override
public String toString()
{
return "Task{" + "task_id=" + task_id + ", task_name=" + task_name + ", task_description=" + task_description + ", task_priority=" + task_priority + ", task_status=" + task_status + '}';
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="aaa.bbb.ccc.war" />
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
<mvc:default-servlet-handler/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:resources mapping="/static/**" location="/static/" />
<mvc:resources mapping="/webjars/**" location="/webjars/" />
<mvc:resources mapping="/assets/**" location="/assets/" />
<mvc:resources mapping="/resources/**" location="/resources/" />
</beans>
web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<filter>
<filter-name>charEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>charEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
WEB-INF/spring/applicationContext.xml
</param-value>
</context-param>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
WEB-INF/spring/applicationContext.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
config.properties
driver=org.apache.derby.jdbc.ClientDriver
url=jdbc:derby://localhost:1527/taskmanager
user=app
password=app
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="testLogEvent" packages="">
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%-7p %d [%t] %c %x - %m%n"/>
</Console>
<!-- writes log file to the tomee "logs" folder... -->
<File name="appLog" fileName="../logs/nggridtest.log">
<PatternLayout>
<Pattern>%-7p %d [%t] %c %x - %m%n</Pattern>
</PatternLayout>
</File>
<Async name="Async">
<AppenderRef ref="appLog"/>
</Async>
</Appenders>
<Loggers>
<Root level="DEBUG">
<AppenderRef ref="STDOUT"/>
<AppenderRef ref="Async"/>
</Root>
</Loggers>
</Configuration>
used derby database
CREATE TABLE "TASK_LIST"
(
"TASK_ID" INT not null primary key GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
"TASK_NAME" VARCHAR(50),
"TASK_DESCRIPTION" VARCHAR(50),
"TASK_PRIORITY" VARCHAR(100),
"TASK_STATUS" VARCHAR(20),
"TASK_START_TIME" TIMESTAMP,
"TASK_END_TIME" TIMESTAMP,
"TASK_ARCHIVED" BOOLEAN
);
//...NOTE: the task_id column value is auto-generated...
insert into task_list (task_name, task_description, task_priority, task_status, task_start_time, task_end_time, task_archived) values('Gathering Requirement', 'Requirement Gathering', 'MEDIUM', 'ACTIVE', CURRENT TIMESTAMP, {fn TIMESTAMPADD(SQL_TSI_HOUR, 1, CURRENT_TIMESTAMP)}, false);
insert into task_list (task_name, task_description, task_priority, task_status, task_start_time, task_end_time, task_archived) values('Application Designing', 'Application Designing', 'MEDIUM', 'ACTIVE', CURRENT TIMESTAMP, {fn TIMESTAMPADD(SQL_TSI_HOUR, 2, CURRENT_TIMESTAMP)}, false);
insert into task_list (task_name, task_description, task_priority, task_status, task_start_time, task_end_time, task_archived) values('Implementation', 'Implementation', 'MEDIUM', 'ACTIVE', CURRENT TIMESTAMP, {fn TIMESTAMPADD(SQL_TSI_HOUR, 3, CURRENT_TIMESTAMP)}, false);
insert into task_list (task_name, task_description, task_priority, task_status, task_start_time, task_end_time, task_archived) values('Unit Testing', 'Unit Testing', 'LOW', 'ACTIVE', CURRENT TIMESTAMP, {fn TIMESTAMPADD(SQL_TSI_HOUR, 4, CURRENT_TIMESTAMP)}, false);
insert into task_list (task_name, task_description, task_priority, task_status, task_start_time, task_end_time, task_archived) values('Maintenance', 'Maintenance', 'LOW', 'ACTIVE', CURRENT TIMESTAMP, {fn TIMESTAMPADD(SQL_TSI_HOUR, 5, CURRENT_TIMESTAMP)}, false);
PROJECT STRUCTURE
As Lrossy mentioned, it could be that the object has not been defined yet. so at the beginning of your controller or link function (before the get request), define it:
$scope.tasks = []
then, perhaps it needs a nudge to apply the scope? Not likely since $http knows to do this, but it may help to put this in your success handler:
if (!$scope.$$phase) {
$scope.$apply();
}
I have some problem whith WebView. Javascript doesn't work. On android 2.2 whith loadUrl(), it works well. But when I run it on android 4 using loadDataWithBaseURL, it doesn't work. What am I doing wrong?
MainActivity
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.webkit.WebView;
import android.widget.Toast;
public class MainActivity extends Activity {
String webData = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webData = getHtmlFromAsset();
WebView webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
//webView.loadUrl("file:///android_asset/index.html");
//webView.loadData(webData, "text/html", "UTF-8");
webView.addJavascriptInterface(new JavaScriptIntefeise(this), "Android");
webView.loadDataWithBaseURL(getAssets().toString(), webData, "text/html", "UTF-8", null);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private String getHtmlFromAsset() {
InputStream is;
StringBuilder builder = new StringBuilder();
String htmlString = null;
try {
is = getAssets().open(getString(R.string.index));
if (is != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
htmlString = builder.toString();
}
} catch (IOException e) {
e.printStackTrace();
}
return htmlString;
}
class JavaScriptIntefeise {
Context ctx;
public JavaScriptIntefeise(Context ctx) {
this.ctx = ctx;
}
public void showToast() {
Toast.makeText(ctx, "ping", 3000).show();
}
}
}
simple sgnalR client index.html
<html>
<head>
<title>Insert title here</title>
<script type="text/javascript" src="json2.js" ></script>
<script type="text/javascript" src="jquery-1.9.0.js" ></script>
<script type="text/javascript" src="jquery.signalR.js" ></script>
<script type="text/javascript" src="http://192.168.0.100/FloorSpy.DuplexService/signalr/hubs/"></script>
</head>
<body>
<span>signalR</span>
<script type="text/javascript">
if(!window.jQuery) document.body.style.backgroundColor = '#ff8000';;
$.connection.hub.url = "http://192.168.0.100/FloorSpy.DuplexService/signalr";
var connection = $.connection.notif;
connection.client.pong = function(data) {
Android.showToast();
};
$.connection.hub.start()
.done(function() {
// Android.showToast();
})
.fail(function(data) {
//Android.showToast();
});
</script>
</body>
</html>
I think the error in connecting libraries.
Thanks for advice!