dataModel URL javascript function does not populate grid - javascript

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.

Related

Access to a model attribute in Javascript with Spring MVC

I have some problem accessing to model attribute in Javascript; in particular I have this controller:
#RequestMapping(value = "/dashboard")
public ModelAndView home(HttpServletRequest request, HttpServletResponse
res, Model model) {
// Return answer's dictionary from DB to dashboard view
CompQuest dizRisp = new CompQuest();
dizRisp.setDizComp(dashDao.getRispEnd());
model.addAttribute("dizRisp", dizRisp);
return new ModelAndView("dashboard");
}
and I have this Javascript file (here: only the part with the code for my chart where I want to refer to model attribute) where I want to access to model attribute "dizRisp" from my controller:
var ctx1 = document.getElementById('myChart1').getContext('2d');
var myRadarChart = new Chart(ctx1, {
type: 'radar',
data: {
labels: ['Valori e identità del SCN', 'La cittadinanza attiva',
'Il giovane volontario nel sistema del SC', 'Lavorare',
'Prevenzione e protezione', 'Normativa sicurezza',
'Rischi sulla salute in tema di ambiente'
],
datasets: [{
label: "Civiche",
data: [4, 5, 5, 2, 4, 5, 4],
fill: true,
borderJoinStyle: "round"
}],
},
options: {
maintainAspectRatio: false,
scale: {
ticks: {
stepSize: 1,
step: 1,
beginAtZero: true,
max: 5
}
}
}
});
My classes are (here: no getters and setters):
public class CompQuest {
private HashMap <String, CompRisp> dizComp;}
public class CompRisp {
private ArrayList <Risposte> rispList = new ArrayList <Risposte> ();}
public class Risposte {
int id;
Domande domande;
int valore;
int momento; }
public class Domande {
int id;
String testo;
String descrizione;
Questionario questionario; }
My .jsp file:
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js" ></script>
<script src="resources/dashboard.js" type="text/javascript"></script>
<link rel="stylesheet" href="${pageContext.request.contextPath}/resources/dashboard.css">
<title>Dashboard</title>
<style>
#import url('https://fonts.googleapis.com/css?family=Bitter|Roboto+Condensed');
#import url('https://fonts.googleapis.com/css?family=Roboto');
</style>
In particular I would want to access to my model attribute (Hashmap) in order to put in label and datasets field of my Javascript chart values from my Hashmap that contains data from my Database.
Thanks in advance to everyone that can help me!
Spring controller
#RequestMapping(value = "/dashboard")
public ModelAndView home(HttpServletRequest request,
HttpServletResponse
res, Model model) {
// Return answer's dictionary from DB to dashboard view
CompQuest dizRisp = new CompQuest();
dizRisp.setDizComp(dashDao.getRispEnd());
Gson gson = new Gson() ;
// Use Gson dependency to convert hashmap to String
String strmap = gson.toJson(dizRisp)
model.addAttribute("dizRisp", strmap);
return new ModelAndView("dashboard");
}
Javascript
<script>
$(document).ready(function(){
var element = JSON.parse('${dizRisp}');
$.each( element , function( key, value ) {
console.log(key);
console.log(value);
});
});
</script>
Hope this is what your trying to achieve.

building a chart from a backing bean using google chart tools

I'm trying to draw a chart using google chart tools. I'd like to know if there is a way to take the array values from my backing bean using Javascript. I have the following code but, when I test it, it looks like it doesn't get the backing bean:
my xhtml:
<?xml version="1.0" encoding="UTF-8" ?>
<!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:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:fn="http://java.sun.com/jsp/jstl/functions">
<ui:composition template="/pages/menu.xhtml">
<ui:define name="conteudo">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the corechart package.
google.charts.load('current'); // Don't need to specify chart libraries!
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
var wrapper = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
dataTable: ["#{chartBean.countries}", "#{chartBean.numbers}"],
options: {'title': 'Countries'},
containerId: 'vis_div'
});
wrapper.draw();
}
</script>
<div id="vis_div" style="width: 600px; height: 400px;"></div>
</ui:define>
</ui:composition>
</html>
my backing bean:
#ManagedBean
#RequestScoped
public class ChartBeean {
private String[] countries = {"","Germany","USA","Brazil","Canada","France","Russia"};
private int[] numbers = {0,700,300,400,500,600,800};
public String[] getCountries() {
return countries;
}
public void setCountries(String[] countries) {
this.countries = countries;
}
public int[] getNumbers() {
return numbers;
}
public void setNumbers(int[] numbers) {
this.numbers = numbers;
}
}
Can anyone help me with this?
PS:I know there is a specific api to use google charts in primefaces, but I would like to use the pure google chart api.
for your query regarding "..it looks like it doesn't get the backing bean"
Your are using #{chartBean.countries} and your Managed Bean name is ChartBeean.
You need to use #{chartBeean.countries} and "#{chartBeean.numbers}"
Working Code for Charts -
You do not need the " " on
dataTable : [ #{chartBeean.countriesString}, #{chartBeean.numbersString} ])
I have added ' in the String for countries.
XHTML
<h:head>
<title>Charts Test</title>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the corechart package.
google.charts.load('current'); // Don't need to specify chart libraries!
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
var wrapper = new google.visualization.ChartWrapper(
{
chartType : 'ColumnChart',
dataTable : [ #{chartBeean.countriesString},
#{chartBeean.numbersString} ],
options : {
'title' : 'Countries'
},
containerId : 'chart_div'
});
wrapper.draw();
}
</script>
</h:head>
<h:body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</h:body>
</html>
ManagedBean
package com;
import java.util.Arrays;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
#ManagedBean
#RequestScoped
public class ChartBeean {
private String[] countries = { "'Germany'", "'USA'", "'Brazil'", "'Canada'", "'France'", "'Russia'" };
private String[] numbers = { "700", "300", "400", "500", "600", "800" };
public ChartBeean() {
super();
System.out.println("ChartBeean..");
}
#PostConstruct
public void init() {
System.out.println("ChartBeean init..");
}
public String getCountriesString() {
// ['Germany', 'USA', 'Brazil', 'Canada', 'France', 'Russia']
String deepToString = Arrays.deepToString(countries);
System.out.println(deepToString);
return deepToString;
}
public String getNumbersString() {
// [700, 300, 400, 500, 600, 800]
String deepToString = Arrays.deepToString(numbers);
System.out.println(deepToString);
return deepToString;
}
}

I want to show table data using Ajax in Asp.Net MVC. What is wrong with this Ajax syntax?

I want to show table data using Ajax request.
Here is my Ajax Syntax:
$(document).ready(function() {
var table = $("#attendance").DataTable({
ajax: {
url: '#Url.Action("GetAttendance", new {id = Model.Student.Id})',
dataSrc: ""
},
columns: [
{
data: "Date",
render: function(data) {
return data;
}
},
{
data: "Status.StudentStatus",
render: function(data) {
return data;
}
}
]
});
Here is my action method:
public JsonResult GetAttendance(int id)
{
var studentAttendance = _context.Attendances.ToList().Where(m => m.StudentId == id);
return Json(studentAttendance, JsonRequestBehavior.AllowGet);
}
Now, where am I wrong?
Please plug in the following example. If you don't mind, please just follow my example, and then you will be able to fix your issue.
Controller/Model:
public class AjaxViewModel
{
public string theDate { get; set; }
public string StudentStatue { get; set; }
}
public class HomeController : Controller
{
public string GetAttendance()
{
AjaxViewModel aViewModel = new AjaxViewModel { StudentStatue = "stat4", theDate = "12/24/2005" };
AjaxViewModel aViewModel2 = new AjaxViewModel { StudentStatue = "stat5", theDate = "12/24/2005" };
AjaxViewModel aViewModel3 = new AjaxViewModel { StudentStatue = "stat6", theDate = "12/24/2005" };
IList<AjaxViewModel> data = new List<AjaxViewModel>();
data.Add(aViewModel);
data.Add(aViewModel2);
data.Add(aViewModel3);
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(data);
json = "{ \"data\": " + json;
json = json + " }";
return json;
}
View:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index2020</title>
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<link href="~/Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(function () {
$("#uiDataTable").DataTable({
"ajax": '#Url.Action("GetAttendance")',
columns: [
{
"data": "theDate"
},
{
"data": "StudentStatue"
}
]
});
})
</script>
</head>
<body>
<table id="uiDataTable" class="display table table-striped table-bordered">
<thead>
<tr>
<th>
Date
</th>
<th>
Status
</th>
</tr>
</thead>
</table>
</body>
</html>

How to pass Dictionary from c#(server) to javascript(client)

I have a function in c# that builds dictionary ,I need to pass this dictionary to my java-script function.
This is what I have tried
My server function
public partial class login : System.Web.UI.Page
{
protected Dictionary<string, string> GetTradingTypeToSelect()
{
Dictionary<string, string> dict = new Dictionary<string, string>();
try {
string Types =GetString("some text);
var items = Types.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Split(new[] { '=' }));
foreach (var item in items)
{
dict.Add(item[1], item[0]);
}
//this working 100%
}
catch (Exception ex)
{
}
return dict;
}
}
My client:
$(document).ready(function () {
$("#Account").keyup(function () {
var TradingTypeToSelect = '<%=GetTradingTypeToSelect();%>';
//TradingTypeToSelect is equals to string '<%=GetTradingTypeToSelect();%>'
var test = TradingTypeToSelect[0].key;
var test2 = TradingTypeToSelect[0].value;
});
});
What am I missing here?
You can create a [WebMethod] in the code behind and call it from javascript using $.ajax.Below is a complete example:
Code behind:
[System.Web.Services.WebMethod]
public static Dictionary<string, string> GetTradingTypeToSelect()
{
var dict = new Dictionary<string, string>();
dict.Add("1", "Item 1");
dict.Add("2", "Item 2");
return dict;
}
.ASPX:
<head runat="server">
<title></title>
<script src="//code.jquery.com/jquery-1.12.3.min.js"></script>
<script type="text/javascript">
$(function () {
$("#Account").keyup(function () {
$.ajax({
type: "POST",
url: "AjaxCallExample.aspx/GetTradingTypeToSelect",
contentType: "application/json;charset=utf-8",
success: function (data) {
alert(data.d["1"]);
alert(data.d["2"]);
},
error: function (errordata) {
console.log(errordata);
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<input id="Account" type="text" />
</form>
</body>
How about exposing the dictionary in the view model:
public Dictionary<string, string> TradingTypesToSelect { get; set; }
And iterate over the dictionary inside the <script> block, creating a JavaScript associative array, like so:
<script>
var tradingTypesToSelect = {};
<% foreach (var tradingType in Model.TradingTypesToSelect) { %>
tradingTypesToSelect["<%= tradingType.Key %>"] = "<%= tradingType.Value %>";
<% } %>
</script>
At least this way you don't have to make another call (via AJAX) to retrieve additional data.
I believe you need to make a WebMethod to enable the server function to be called from the client side. Here is an example:
Calling ASP.Net WebMethod using jQuery AJAX

why is the "data" parameter in my gridOptions (ng-grid) always empty?

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();
}

Categories

Resources