How to print the values to user interface from spring data jpa? - javascript

I created a team and player rest service using spring boot and mysql. I want to move it to user experience using javascript ajax.
Players come up without a problem,
but the team doesn't.
How do I bring in team players when the team button is clicked?
What do I need to change?
Player
#Entity
#Table(name = "player")
public class Player{
#Id
#GeneratedValue
#NotNull
#Column
private int id;
#NotNull
#Column
private String playerName;
#NotNull
#Column
private String playerSurname;
#Column
private int playerAge;
public String getPlayerName() {
return playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
public String getPlayerSurname() {
return playerSurname;
}
public void setPlayerSurname(String playerSurname) {
this.playerSurname = playerSurname;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPlayerAge() {
return playerAge;
}
public void setPlayerAge(int playerAge) {
this.playerAge = playerAge;
}
}
Team
#Entity
#Table(name = "team")
public class Team {
#Id
#GeneratedValue
#NotNull
#Column
private int id;
#NotNull
#Column
private String teamName;
#Column
private String teamCountry;
public Team(){
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public String getTeamCountry() {
return teamCountry;
}
public void setTeamCountry(String teamCountry) {
this.teamCountry = teamCountry;
}
#OneToOne
private Player player;
public Player getPlayer() {
return player;
}
public void setPlayer(Player player) {
this.player = player;
}
}
Controller
#CrossOrigin(origins = "http://localhost:8000/")
#RestController
public class TeamController {
#Autowired
PlayerRepository playerRepository;
#Autowired
TeamRepository teamRepository;
#RequestMapping("/")
public void main() {
//create players by manual
Player messi = new Player();
Player ronaldo = new Player();
Player ozil = new Player();
messi.setPlayerName("Lionel");
messi.setPlayerSurname("Messi");
messi.setPlayerAge(31);
ronaldo.setPlayerName("Cristiano");
ronaldo.setPlayerSurname("Ronaldo");
ronaldo.setPlayerAge(32);
ozil.setPlayerName("Mesut");
ozil.setPlayerSurname("Ozil");
ozil.setPlayerAge(29);
this.playerRepository.save(messi);
this.playerRepository.save(ronaldo);
this.playerRepository.save(ozil);
//create teams by manual
Team barcelona = new Team();
Team juventus = new Team();
Team arsenal = new Team();
barcelona.setTeamName("Barcelona");
barcelona.setTeamCountry("Spain");
barcelona.setPlayer(messi);
juventus.setTeamName("Juventus");
juventus.setTeamCountry("Italy");
juventus.setPlayer(ronaldo);
arsenal.setTeamName("Arsenal");
arsenal.setTeamCountry("England");
arsenal.setPlayer(ozil);
this.teamRepository.save(barcelona);
this.teamRepository.save(juventus);
this.teamRepository.save(arsenal);
}
//**PLAYER**
#GetMapping(value="/getAllPLayers")
public List<Player> getAllPlayers(){
return playerRepository.findAll();
}
#PostMapping(value="getPlayerByName")
public List<Player> getPlayerByName(#RequestParam("playerName") String playerName){
return playerRepository.findByPlayerName(playerName);
}
#PostMapping(value="getPlayerBySurname")
public List<Player> getPlayerBySurname(#RequestParam("playerSurname") String playerSurname){
return playerRepository.findByPlayerSurname(playerSurname);
}
#PostMapping(value="getPlayerByAge")
public List<Player> getPlayerByAge(#RequestParam("playerAge") int playerAge){
return playerRepository.findByPlayerAge(playerAge);
}
//**TEAM**
#GetMapping(value="/getAllTeams")
public List<Team> getAllTeams(){
return teamRepository.findAll();
}
#PostMapping(value = "/getTeamsByName")
public List<Team> getTeamByName(#RequestParam("teamName") String teamName){
return teamRepository.findByTeamName(teamName);
}
#PostMapping(value = "/getTeamsByCountry")
public List<Team> getTeamByCountry(#RequestParam("teamCountry") String teamCountry){
return teamRepository.findByTeamCountry(teamCountry);
}
}
Ajax request
$( document ).ready(function() {
$("#getAllTeams").click(function(event){
event.preventDefault();
ajaxGet();
});
function ajaxGet(){
$.ajax({
type : "GET",
url : "http://localhost:8080/getAllTeams/",
dataType : 'json',
contentType:'application/x-www-form-urlencoded',
success: function(result){
alert("Teams loaded!");
$('#getResultDiv2 ul').empty();
var tableTitle = "<h2><strong>Team List</strong></h2>";
var teamList = "<table border='1'>";
teamList += "<tr><td><strong>Team Name</strong></td><td><strong>Team Country</strong></td><td><strong>Player Name</strong></td><td><strong>Player Surname</strong></td><td><strong>Player Age</strong></td></tr>";
$.each(result, function(i, teams){
teamList +="<tr>";
teamList +="<td>"+teams.teamName +"</td>";
teamList +="<td>"+teams.teamCountry+"</td>";
teamList +="<td>"+teams.playerList[i]["playerName"]+"</td>";
teamList +="<td>"+teams.playerList[i]["playerSurname"]+"</td>";
teamList +="<td>"+teams.playerList[i]["playerAge"]+"</td>";
teamList +="</tr>";
});
teamList +="</table>";
$('#getResultDiv2').append(tableTitle, teamList)
console.log("Success: ", result);
},
error : function(e) {
$("#getResultDiv2").html("<strong>Error</strong>");
console.log("ERROR: ", e);
}
});
}
})
HTML
<!-- Players -->
<h3 style="color: darkolivegreen" ><strong>Team System</strong></h3>
<div class="col-sm-7" style="margin:20px 0px 20px 0px">
<button id="getAllPlayers">Get Players</button>
<button id="getAllTeams">Get Teams</button>
<div id="getResultDiv1" style="padding:20px 10px 20px 50px">
<ul class="list-group">
</ul>
</div>
<!-- Teams -->
<div id="getResultDiv2" style="padding:20px 10px 20px 50px">
<ul class="list-group">
</ul>
</div>
</div>
</div>
</div>
<!-- *** -->
I share with you my error log :
Here is the another url for error log:
https://pasteboard.co/IqdScuY.png

$.each(result, function(i, teams){
teamList +="<tr>";
teamList +="<td>"+teams.teamName +"</td>";
teamList +="<td>"+teams.teamCountry+"</td>";
teamList +="<td>"+teams.player.playerName+"</td>";
teamList +="<td>"+teams.player.playerSurname+"</td>";
teamList +="<td>"+teams.player.playerAge+"</td>";
teamList +="</tr>";
});

Related

Passing Values from Checkboxes from View to Controller

I am having trouble passing data from my view to my controller. I am using checkboxes. For my view, I created a class that takes in all my checkboxes (Mon-Fri) and putting them into a list (so I can use the data someplace else). My problem is that when I debug and click the checkboxes on the website, the code does not change whether I click the checkbox or not, so my code doesn't recognize the checkbox data
I'm not sure if I have implemented the View incorrectly but any help to the right direction would be appreciated !
ViewModel:
public List<cDay> _cDays = new List <cDay>();
public List<cDay> cDays
{
get {return _cDays;}
set {_cDays = value;}
}
public class cDay
{
public bool Monday { get; set; }
public bool Tuesday { get; set; }
public bool Wednesday { get; set; }
public bool Thursday { get; set; }
public bool Friday { get; set; }
}
CSHtml file:
#Html.Label("M")
#Html.CheckBox("Monday", false, new { #class = "availability" })
// this is basically the same code for Tuesday-Friday as well.
'<label for="M">M</label> +
'<input class="availability" id="Monday" name="Monday" type="checkbox" value="true">' +
'input name="Monday" type="hidden" value="false">'
// this is basically the same code for Tuesday-Friday, but the "name" corresponds to each day
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(string inputValue, Model viewModel)
{
if(ModelState.IsValid)
//
}
Consider to use the following data model:
public class DaysViewModel
{
public List<CDay> Days { get; set; } = new List<CDay>();
}
public class CDay
{
public CDay()
{
Name = string.Empty;
Selected = false;
}
public CDay(string name)
{
Name = name;
Selected = false;
}
[Required]
public string Name { get; set; }
[Required]
public bool Selected { get; set; }
}
Then you can use the default ASP.NET MVC data binding without a JS support:
#model Models.DaysViewModel
#using (Html.BeginForm("Edit", "Home"))
{
#Html.AntiForgeryToken()
for(int i=0; i < Model.Days.Count; i++)
{
<div class="form-group row">
#Html.CheckBox("Days[" + i + "].Selected", Model.Days[i].Selected)
#Html.Hidden("Days[" + i + "].Name", Model.Days[i].Name)
<span>#Model.Days[i].Name </span>
</div>
}
<input type="submit" value="Save" />
}
And on the server side:
public ActionResult Edit()
{
var model = new DaysViewModel();
model.Days.AddRange( new List<CDay> {
new CDay("Monday"),
new CDay("Tuesday"),
new CDay("Wednesday"),
new CDay("Thursday"),
new CDay("Friday")
});
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(List<CDay> days)
{
if(ModelState.IsValid)
{
// ... you_code here
}
var model = new DaysViewModel() { Days = days };
return View(model);
}
Test screen shots
The view:
On the controller side:
You can do it using jQuery
Add a button bellow your checkboxes
<input type="button" value="Your_Value" class="btn btn-default" />
When click on a button create a post request and sends checked status via querystring
$(document).ready(function () {
$("input[type=button]").click(function () {
var queryString = 'Monday=' + $("input[name=Monday]").is(":checked") + '&Tuesday=' + $("input[name=Tuesday]").is(":checked") + '&Wednesday=' + $("input[name=Wednesday]").is(":checked") + '&Thursday=' + $("input[name=Thursday]").is(":checked") + '&Friday=' + $("input[name=Friday]").is(":checked");
$.ajax({
type: "Post",
url: "/Home/Edit?" + queryString,
success: function (data) {
},
error: function (data) {
}
});
});
});
And inside controller create Edit Post Method like this
[HttpPost]
public ActionResult checkboxespost(string Monday, string Tuesday, string Wednesday, string Thursday, string Friday)
{
...
}

String array doing math operations in JavaScript

I am trying to populate a DataTable from google chart to generate a chart. So far, I was able to get the information to travel from the database (MySQL) to the controller, and from there to the view using an ArrayList but when reading the dates, something happens and controls are subtracted:
In summary: I am sending an Array with data in the 2019-05-21 format and JavaScript interprets it as a mathematical operation, leaving 1,993.
I understand that it may be seen as a basic error, but it is my first time working with JavaScript and I have already spent several hours reading documentation and have not found any solution.
Controller:
#Controller
#RequestMapping
public class indexController {
#Autowired
private IAccionService service;
#GetMapping("chart_index")
public String profileSettings(Model model) {
String msg="holasoyundatodeprueba";
String msg2="Fecha1";
model.addAttribute("msg", msg);
model.addAttribute("msg2", msg2);
List<Acciones>accioneslst=service.listar_acciones();
Acciones[] arrayAcciones = new Acciones[accioneslst.size()];
arrayAcciones=accioneslst.toArray(arrayAcciones);
ArrayList<String> arrayFechas = new ArrayList<String>();
ArrayList<Integer> arrayOpen = new ArrayList<Integer>();
ArrayList<Integer> arrayClose = new ArrayList<Integer>();
for (Acciones acciones : arrayAcciones) {
arrayFechas.add(acciones.getFecha().toString());
arrayOpen.add(acciones.getOpen_value());
arrayClose.add(acciones.getClose_value());
System.out.println(arrayFechas.toString());
}
model.addAttribute("fechaGrafico",arrayFechas);
model.addAttribute("openGrafico",arrayOpen);
model.addAttribute("closeGrafico",arrayClose);
return "chart_index";
}
JavaScript code (Google Chart: Line Chart) added to the view:
<!DOCTYPE html>
<html>
<head xmlns:th="http://www.thymeleaf.org">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Gráfico de acciones</title>
<link rel="stylesheet" type="text/css" href="CSS/styles_chart.css" />
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var Fecha=[[${fechaGrafico}]];
var Open=[[${openGrafico}]];
var Close=[[${closeGrafico}]];
var data = new google.visualization.DataTable(); //Cambiado a DataTable
data.addColumn('string','Fecha');
data.addColumn('number','Open');
data.addColumn('number','Close');
for(i=0;i<Fecha.length;i++)
data.addRow(["'"+Fecha[i]+"'",Open[i],Close[i]]);
console.log(Fecha);
var options = {
title : "[[${msg}]]",
curveType : 'function',
backgroundColor : '#EDEEF0',
width : '1323',
height : '855',
legend : 'none',
chartArea : {
width : '1200',
height : '800'
},
colors : [ '#A6CEE3', '#1F78B4' ]
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
Class:
Package com.amsterdam.springboot.v1.app.models;
import java.sql.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table (name="accion") //Nombre de la tabla
public class Acciones {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Date fecha;
private int open_value;
private int high_value;
private int low_value;
private int close_value;
private int adj_close;
private int volume;
private String enterprise;
public Acciones() {
// TODO Auto-generated constructor stub
}
public Acciones(Date fecha, int open_value, int high_value, int low_value, int close_value, int adj_close,
int volume, String enterprise) {
super();
this.fecha = fecha;
this.open_value = open_value;
this.high_value = high_value;
this.low_value = low_value;
this.close_value = close_value;
this.adj_close = adj_close;
this.volume = volume;
this.enterprise = enterprise;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public int getOpen_value() {
return open_value;
}
public void setOpen_value(int open_value) {
this.open_value = open_value;
}
public int getHigh_value() {
return high_value;
}
public void setHigh_value(int high_value) {
this.high_value = high_value;
}
public int getLow_value() {
return low_value;
}
public void setLow_value(int low_value) {
this.low_value = low_value;
}
public int getClose_value() {
return close_value;
}
public void setClose_value(int close_value) {
this.close_value = close_value;
}
public int getAdj_close() {
return adj_close;
}
public void setAdj_close(int adj_close) {
this.adj_close = adj_close;
}
public int getVolume() {
return volume;
}
public void setVolume(int volume) {
this.volume = volume;
}
public String getEnterprise() {
return enterprise;
}
public void setEnterprise(String enterprise) {
this.enterprise = enterprise;
}
}

Update panel does not work after calling the function loginByFacebook()

I'm using Facebook Graph JSON responses in my code to deserialize the JSON string.
I created the class as follow.
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div id="fb-root"></div>
Login with Facebook
<br /> <br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
window.fbAsyncInit = function () {
FB.init({ appId: '<%= ecommerce.fblogin.FaceBookAppKey %>',
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true, // parse XFBML
oauth: true // enable OAuth 2.0
});
};
(function () {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
} ());
function loginByFacebook() {
FB.login(function (response) {
if (response.authResponse) {
FacebookLoggedIn(response);
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, { scope: 'email' });
}
function FacebookLoggedIn(response) {
var loc = '/fblogin.aspx';
if (loc.indexOf('?') > -1)
window.location = loc + '&authprv=facebook&access_token=' + response.authResponse.accessToken;
else
window.location = loc + '?authprv=facebook&access_token=' + response.authResponse.accessToken;
}
</script>
</form>
namespace ecommerce
{
public partial class fblogin : System.Web.UI.Page
{
public const string FaceBookAppKey = "xxxxxxxxxx";
protected void Page_Load(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(Request.QueryString["access_token"])) return; //ERROR! No token returned from Facebook!!
//let's send an http-request to facebook using the token
string json = GetFacebookUserJSON(Request.QueryString["access_token"]);
//and Deserialize the JSON response
JavaScriptSerializer js = new JavaScriptSerializer();
FacebookUser oUser = js.Deserialize<FacebookUser>(json);
if (oUser != null)
{
Response.Write("Welcome, " + oUser.name);
Response.Write("<br />id, " + oUser.id);
Response.Write("<br />email, " + oUser.email);
Response.Write("<br />first_name, " + oUser.first_name);
Response.Write("<br />last_name, " + oUser.last_name);
Response.Write("<br />gender, " + oUser.gender);
Response.Write("<br />link, " + oUser.link);
Response.Write("<br />updated_time, " + oUser.updated_time);
Response.Write("<br />birthday, " + oUser.birthday);
Response.Write("<br />locale, " + oUser.locale);
Response.Write("<br />picture, " + oUser.picture);
if (oUser.location != null)
{
Response.Write("<br />locationid, " + oUser.location.id);
Response.Write("<br />location_name, " + oUser.location.name);
}
}
}
private static string GetFacebookUserJSON(string access_token)
{
string url = string.Format("https://graph.facebook.com/me?access_token={0}&fields=email,name,first_name,last_name,link", access_token);
WebClient wc = new WebClient();
Stream data = wc.OpenRead(url);
StreamReader reader = new StreamReader(data);
string s = reader.ReadToEnd();
data.Close();
reader.Close();
return s;
}
public class FacebookUser
{
public long id { get; set; }
public string email { get; set; }
public string name
{ get; set; }
public string first_name
{ get; set; }
public string last_name
{ get; set; }
public string gender
{ get; set; }
public string link
{ get; set; }
public DateTime updated_time
{ get; set; }
public DateTime birthday
{ get; set; }
public string locale
{ get; set; }
public string picture
{ get; set; }
public FacebookLocation location
{ get; set; }
}
public class FacebookLocation
{
public string id
{ get; set; }
public string name
{ get; set; }
}
static int a = 0;
protected void Button1_Click(object sender, EventArgs e)
{
a++;
Label1.Text = Convert.ToString(a);
}
}
}
After added update panel my Facebook login function not working after the link is clicked.
I added AJAX page request manager. The post Back settings function it not work as what I expected.
After I remove added update panel works is working as I expect.
/** This is what I try, but not work */
function loginByFacebook() {
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm != null) {
prm._postBackSettings(function (sender, e) {
if (sender.loginByFacebook.panelsToUpdate != null) {
loginByFacebook();
}
});
};
}
*/
Below is the screenshot issues i'm stuck.
Update panel events are rendered partially hence the events will looses.
After Login or Register Button is click. The Facebook login will not work as expected. The dialog box will not close automatically.

How to Retrieve data from oracle database using Ajax Jquery with spring Mvc?

I am working with spring batch , I have configured my job to be executed by clicking on a button (spring MVC).
all information about my job are in BATCH_JOB_EXECUTION in the database.
I want to have this scenario:
-when I load the page , the table contains all the records existing in the database
-when I click on the button to execute my job, the last record added in the database is added in the front end of my table.
This is what I have done But still not working!
Here is the content of BATCH_JOB_EXECUTION.java file :
public class BATCH_JOB_EXECUTION {
private int JOB_EXECUTION_ID ;
private int VERSION;
private int JOB_INSTANCE_ID;
private Time CREATE_TIME ;
private Time START_TIME;
private Time END_TIME;
private String STATUS;
private String EXIT_CODE;
private String EXIT_MESSAGE;
private Time LAST_UPDATED;
public BATCH_JOB_EXECUTION(){
}
public int getJOB_EXECUTION_ID() {
return JOB_EXECUTION_ID;
}
public void setJOB_EXECUTION_ID(int jOB_EXECUTION_ID) {
JOB_EXECUTION_ID = jOB_EXECUTION_ID;
}
public int getVERSION() {
return VERSION;
}
public void setVERSION(int vERSION) {
VERSION = vERSION;
}
public int getJOB_INSTANCE_ID() {
return JOB_INSTANCE_ID;
}
public void setJOB_INSTANCE_ID(int jOB_INSTANCE_ID) {
JOB_INSTANCE_ID = jOB_INSTANCE_ID;
}
public Time getCREATE_TIME() {
return CREATE_TIME;
}
public void setCREATE_TIME(Time cREATE_TIME) {
CREATE_TIME = cREATE_TIME;
}
public Time getSTART_TIME() {
return START_TIME;
}
public void setSTART_TIME(Time sTART_TIME) {
START_TIME = sTART_TIME;
}
public Time getEND_TIME() {
return END_TIME;
}
public void setEND_TIME(Time eND_TIME) {
END_TIME = eND_TIME;
}
public String getSTATUS() {
return STATUS;
}
public void setSTATUS(String sTATUS) {
STATUS = sTATUS;
}
public String getEXIT_CODE() {
return EXIT_CODE;
}
public void setEXIT_CODE(String eXIT_CODE) {
EXIT_CODE = eXIT_CODE;
}
public String getEXIT_MESSAGE() {
return EXIT_MESSAGE;
}
public void setEXIT_MESSAGE(String eXIT_MESSAGE) {
EXIT_MESSAGE = eXIT_MESSAGE;
}
public Time getLAST_UPDATED() {
return LAST_UPDATED;
}
public void setLAST_UPDATED(Time lAST_UPDATED) {
LAST_UPDATED = lAST_UPDATED;
}
}
and here is my view :
<div>
<table id="contactTableResponse" class="table tr">
<thead>
<tr>
<th>JOB_INSTANCE_ID</th>
<th>START_TIME</th>
<th>END_TIME</th>
<th>EXIT_CODE</th>
</tr>
</thead>
<tfoot>
<tr>
<th scope="row">Spring-Ajax</th>
<td colspan="4">JQuery Ajax</td>
</tr>
</tfoot>
<tbody>
<c:forEach items="${jobs}" var="BATCH_JOB_EXECUTION">
<tr>
<td>${BATCH_JOB_EXECUTION.JOB_INSTANCE_ID}</td>
<td>${BATCH_JOB_EXECUTION.START_TIME}</td>
<td>${BATCH_JOB_EXECUTION.END_TIME}</td>
<td>${BATCH_JOB_EXECUTION.EXIT_CODE}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
The ajax call:
$('#JobBtn').click( function() {
$('#JobBtn').click( function() {
alert('in submit function');
$.ajax({
type: 'GET',
url: 'load',
success : function(response) {
alert(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
});
Updated
this is my controller:
public class AjacController {
#Inject
#Named(value = "dataSource")
private DataSource dataSource1;
#RequestMapping(value="/load" )
public ModelAndView connect(){
ModelAndView model = new ModelAndView("");
BATCH_JOB_EXECUTION batch=null;
List<BATCH_JOB_EXECUTION> list =null;
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
Connection connection = null;
String select= "select JOB_INSTANCE_ID, START_TIME,END_TIME,EXIT_CODE from BATCH_JOB_EXECUTION";
try {
connection = dataSource1.getConnection();
preparedStatement = connection.prepareStatement(select);
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
batch.setJOB_EXECUTION_ID(resultSet.getInt("JOB_INSTANCE_ID")) ;
batch.setSTART_TIME(resultSet.getTime("START_TIME")) ;
batch.setEND_TIME(resultSet.getTime("END_TIME")) ;
batch.setEXIT_CODE(resultSet.getString("EXIT_CODE")) ;
list.add(batch);
model.addObject("listJobs", list);
}
return model ;
}
but data is not displayed in my table!
Any help will be appreciated.

Struts2 jQuery Plugin Doubleselect initial value for second dropdown

I have a little (i hope) problem trying to use Doubleselect element from Struts2 jQuery plugin. I have followed the sample without problems, and the behaviour is as expected when I add a new record (add new record to database), but when i try to edit an existing one the second select does not load the stored value for the record being edited.
Any help?
Code and configuration follows:
JSP code
<s:form id="ingresoForm" action="saveIngreso" method="post" validate="true" cssClass="well form-horizontal">
<s:hidden key="ingreso.id"/>
<s:hidden key="cliente" id="cliente"/>
<div class="type-text">
<label for="cliente">Cliente: </label>
<s:url var="remoteurl" action="ajax/clienteProyectoSelectSource"/>
<sj:select
href="%{remoteurl}"
id="clienteSelect"
onChangeTopics="reloadsecondlist"
name="ingreso.cliente.id"
list="clientes"
listKey="id"
listValue="nombre"
emptyOption="false"
headerKey="-10"
headerValue="Por favor seleccione un cliente"/>
</div>
<div class="type-text">
<label for="Proyecto">Proyecto: </label>
<sj:select
href="%{remoteurl}"
id="proyectoSelect"
formIds="ingresoForm"
reloadTopics="reloadsecondlist"
name="ingreso.proyecto.id"
list="proyectos"
listKey="id"
listValue="nombre"
emptyOption="false"
/>
</div>
Action Code
public class ClienteProyectoSelectSourceAjaxAction extends BaseAction {
private List<Cliente> clientes;
private List<Proyecto> proyectos;
private String cliente;
private GenericManager<Cliente, Long> clienteManager;
#Override
public String execute() {
clientes = clienteManager.getAll();
if (cliente != null && cliente.length() > 0 && !cliente.equals("-10")) {
proyectos = clienteManager.get(new Long(cliente)).getProyectos();
}
return Action.SUCCESS;
}
Action Declaration
<package name="example" extends="json-default" namespace="/ajax">
<action name="clienteProyectoSelectSource" class="com.queres.smtm.webapp.action.ajax.ClienteProyectoSelectSourceAjaxAction">
<result type="json"/>
</action>
</package>
Ingreso entity (model)
#Entity
#Table(name = "ingreso")
public class Ingreso extends BaseObject {
// Campos comunes
private Long id;
private TipoIngreso tipo;
private String observaciones;
private BigDecimal importe;
private BigDecimal tipoIVA;
private Date fechaPrevistaCobro;
private Date fechaEfectivaCobro;
// Campos para facturas
private String numeroFactura;
private Cliente cliente;
private Proyecto proyecto;
private TipoServicio servicio;
private Date fechaEmision;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Enumerated(EnumType.STRING)
public TipoIngreso getTipo() {
return tipo;
}
public void setTipo(TipoIngreso tipo) {
this.tipo = tipo;
}
public String getObservaciones() {
return observaciones;
}
public void setObservaciones(String observaciones) {
this.observaciones = observaciones;
}
public BigDecimal getImporte() {
return importe;
}
public void setImporte(BigDecimal importe) {
this.importe = importe;
}
public BigDecimal getTipoIVA() {
return tipoIVA;
}
public void setTipoIVA(BigDecimal tipoIVA) {
this.tipoIVA = tipoIVA;
}
#Temporal(javax.persistence.TemporalType.DATE)
#Field
public Date getFechaPrevistaCobro() {
return fechaPrevistaCobro;
}
public void setFechaPrevistaCobro(Date fechaPrevistaCobro) {
this.fechaPrevistaCobro = fechaPrevistaCobro;
}
#Temporal(javax.persistence.TemporalType.DATE)
#Field
public Date getFechaEfectivaCobro() {
return fechaEfectivaCobro;
}
public void setFechaEfectivaCobro(Date fechaEfectivaCobro) {
this.fechaEfectivaCobro = fechaEfectivaCobro;
}
public String getNumeroFactura() {
return numeroFactura;
}
public void setNumeroFactura(String numeroFactura) {
this.numeroFactura = numeroFactura;
}
#ManyToOne
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
#ManyToOne
public Proyecto getProyecto() {
return proyecto;
}
public void setProyecto(Proyecto proyecto) {
this.proyecto = proyecto;
}
#Enumerated(EnumType.STRING)
public TipoServicio getServicio() {
return servicio;
}
public void setServicio(TipoServicio servicio) {
this.servicio = servicio;
}
#Temporal(javax.persistence.TemporalType.DATE)
#Field
public Date getFechaEmision() {
return fechaEmision;
}
public void setFechaEmision(Date fechaEmision) {
this.fechaEmision = fechaEmision;
}
#Override
public int hashCode() {
int hash = 3;
hash = 43 * hash + (this.numeroFactura != null ? this.numeroFactura.hashCode() : 0);
hash = 43 * hash + (this.fechaEmision != null ? this.fechaEmision.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Ingreso other = (Ingreso) obj;
if ((this.numeroFactura == null) ? (other.numeroFactura != null) : !this.numeroFactura.equals(other.numeroFactura)) {
return false;
}
if (this.fechaEmision != other.fechaEmision && (this.fechaEmision == null || !this.fechaEmision.equals(other.fechaEmision))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Ingreso{" + "id=" + id + ", tipo=" + tipo + ", observaciones=" + observaciones + ", importe=" + importe + ", tipoIVA=" + tipoIVA + ", fechaPrevistaCobro=" + fechaPrevistaCobro + ", fechaEfectivaCobro=" + fechaEfectivaCobro + ", numeroFactura=" + numeroFactura + ", cliente=" + cliente + ", proyecto=" + proyecto + ", servicio=" + servicio + ", fechaEmision=" + fechaEmision + '}';
}
}
Thx in advance
Problem solved. It seems that jquery-plugin work perfectly, as usual the error was between the keyboard and the chair...
I forgot to load the data list for the second select, so jquery was unable to select the aproppiate value.
So, the solution was to ensure that the second list (proyectos) was loaded when the user edits an element.
I add a flag (cliente) as a hidden element on JSP and preloaded it from the main action, so I can check from the Ajax Action if it is necessary to populate the second list.
Ingreso Action (main action for the view)
public class IngresoAction extends BaseAction implements Preparable {
private String cliente;
public String edit() {
if (id != null) {
ingreso = ingresoManager.get(id);
cliente = Long.toString(ingreso.getCliente().getId());
} else {
ingreso = new Ingreso();
}
return SUCCESS;
}
public String getCliente() {
return cliente;
}
public void setCliente(String cliente) {
this.cliente = cliente;
}
<...>

Categories

Resources