in my servlet i called an instance of a class.java( a class that construct an html table) in order to create this table in my jsp.
the servlet is like the following:
String report=request.getParameter("selrep");
String datev=request.getParameter("datepicker");
String op=request.getParameter("operator");
String batch =request.getParameter("selbatch");
System.out.println("report kind was:"+report);
System.out.println("date was:"+datev);
System.out.println("operator:"+op);
System.out.println("batch:"+batch);
if(report.equalsIgnoreCase("Report Denied"))
{
DeniedReportDisplay rd = new DeniedReportDisplay();
rd.ConstruireReport();
}
else if(report.equalsIgnoreCase("Report Locked"))
{
LockedReportDisplay rl = new LockedReportDisplay();
rl.ConstruireReport();
}
request.getRequestDispatcher("EspaceValidation.jsp").forward(request, response);
in my jsp i can not display this table even empty or full.
note: exemple a class that construct denied Report has this structure:
/*constructeur*/
public DeniedReportDisplay() {}
/*Methodes*/
#SuppressWarnings("unchecked")
public StringBuffer ConstruireReport()
{
StringBuffer retour=new StringBuffer();
int i = 0;
retour.append("<table border = 1 width=900 id=sheet align=left>");
retour.append("<tr bgcolor=#0099FF>" );
retour.append("<label> Denied Report</label>");
retour.append("</tr>");
retour.append("<tr>");
String[] nomCols ={"Nom","Prenom","trackingDate","activity","projectcode","WAName","taskCode","timeSpent","PercentTaskComplete","Comment"};
//String HQL_QUERY = null;
for(i=0;i< nomCols.length;i++)
{
retour.append(("<td bgcolor=#0066CC>")+ nomCols[i] + "</td>");
}
retour.append("</tr>");
retour.append("<tr>");
try {
s= HibernateUtil.currentSession();
tx=s.beginTransaction();
Query query = s.createQuery("select opcemployees.Nom,opcemployees.Prenom,dailytimesheet.TrackingDate,dailytimesheet.Activity," +
"dailytimesheet.ProjectCode,dailytimesheet.WAName,dailytimesheet.TaskCode," +
"dailytimesheet.TimeSpent,dailytimesheet.PercentTaskComplete from Opcemployees opcemployees,Dailytimesheet dailytimesheet " +
"where opcemployees.Matricule=dailytimesheet.Matricule and dailytimesheet.Etat=3 " +
"group by opcemployees.Nom,opcemployees.Prenom" );
for(Iterator it=query.iterate();it.hasNext();)
{
if(it.hasNext()){
Object[] row = (Object[]) it.next();
retour.append("<td>" +row [0]+ "</td>");//Nom
retour.append("<td>" + row [1] + "</td>");//Prenom
retour.append("<td>" + row [2] + "</td>");//trackingdate
retour.append("<td>" + row [3]+ "</td>");//activity
retour.append("<td>" + row [4] +"</td>");//projectcode
retour.append("<td>" + row [5]+ "</td>");//waname
retour.append("<td>" + row [6] + "</td>");//taskcode
retour.append("<td>" + row [7] + "</td>");//timespent
retour.append("<td>" + row [8] + "</td>");//perecnttaskcomplete
retour.append("<td><input type=text /></td>");//case de commentaire
}
retour.append("</tr>");
}
//terminer la table.
retour.append ("</table>");
tx.commit();
} catch (HibernateException e)
{
retour.append ("</table><H1>ERREUR:</H1>" +e.getMessage());
e.printStackTrace();
}
return retour;
}
thanks for help.
1) The instances of DeniedReportDisplay and LockedReportDisplay are created locally, no way to refer them once outside the if..else block.
2) The method invoked ( rd.ConstruireReport() ) returns a StringBuffer and you should store it somewhere. Try to use Response.getWriter() and put all the response string into this writer.
3) Suggest you to find some good tutorial books about how to design Servlets/JSP, the solution you tried to build is quite wried.
The problem is that you are not doing anything with the return value from ConstruireReport(), so it just get's lost. You should set it as a request attribute so your JSP can find the string.
EDIT: Suggestion to use getWriter() on the servlet removed - misunderstood scenario.
Related
I am trying to store some data in a arraylist in each users session however when I try and grab the list it is apparently null...
Code:
<%
List<String> attacks = new ArrayList<>();
if (request.getSession().getAttribute("attackList") != null){
attacks = (List<String>) request.getAttribute("attackList");
int x = 1;
for (String attack : attacks){
String[] attacc = attack.split(":");
out.print("" +
"<tr>\n" +
" <th scope=\"row\">"+x+"</th>\n" +
" <td>"+attacc[0]+"</td>\n" +
" <td>"+attacc[1]+"</td>\n" +
" <td>"+attacc[2]+"</td>\n" +
" <td>"+attacc[3]+"</td>\n" +
" </tr>");
x++;
}
}else{
out.print("empty");
}
%>
That ^ is the code I am using to fetch the data, it is printing "empty", so its essentially null...
How I am adding the data:
if (request.getAttribute("attackList") != null) {
attacks = (List<String>) request.getAttribute("attackList");
request.removeAttribute("attackList");
}
attacks.add("data here");
request.setAttribute("attackList", attacks);
I have not tried anything due to me not knowing what to try here.
First, I suggest you, if it is possible, you can start working with expression language, instead of jsp directly, because turn your code more readable.
Look your problem, do you want to work with a List in a Request our a Session scope?
I ask because sometimes you get your list from request scope but your IF is verifying the Session.
And at no time are you adding your list to the session.
You could do this, after your logic, with:
request.getSession().setAttribute("attackList", attacks);
Here is more about session methods:
https://beginnersbook.com/2013/11/jsp-implicit-object-session-with-examples/
I returned a list<object> from my controller,it successfully captured in ajax's success(), as it is list so it can have n-number of objects, I want to create tabular data dynamically and populated the same by iterating data, but I am not able to access the elements inside data object, as console data shows, the actual elements are wrapped inside an outer object and my for loop outer one. please see the screenshot attached
Please refer to this link for image reference: Console log
Ajax call of the controller:
function getSelectedTableRecords(tableId) {
if (tableId != null && tableId != '') {
$.ajax({
type: "POST",
url: baseUrl + "search",
data: {
tableId: tableId
},
success: function (data) {
for (var i = 0; i < data.length; i++) {
var item = data[i];
$('#applicationList > tbody').append(
'<tr>'
+ '<td><h4>' + item.userId + '</h4></td>'
+ '<td><h4>' + item.firstName + '</h4></td>'
+ '<td><h4>' + item.lastName + '</h4></td>'
+ '<td><h4>' + item.rollNo + '</h4></td>'
+ '<td><h4>' + item.contact + '</h4></td>'
+ '<td><h4>' + item.email + '</h4></td>'
+ '<td><h4>' + item.gender + '</h4></td>'
+ '</tr>');
insideData(data);
}
},
fail: function (data) {
alert('Failed to fetch records.');
}
});
} else {
// ...
}
}
My Controller code:
#RequestMapping(value = "/search", method = RequestMethod.POST)
#ResponseBody
public List<Object> fetchTableData(#RequestParam("tableId") String tableId) {
List<Object> userList = new ArrayList<>();
try {
System.out.println(" table id id " + tableId);
if (tableId != null) {
List<UserInfo> l = userInfoDao.findById(tableId);
userList.add(l);
}
return userList;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
As per screenshot, I only got one row with all undefined values, what I want to do, in the image I have 7 elements, so I want to iterate and I want seven rows and their corresponding columns populated with values. Please suggest me the solution.
Well, as far as I see from your log, the structure is an array of array. An element might be accessible using:
success: function (data) {
for (var i = 0; i < data[0].length; i++) { // access the first item data[0] of outer array
var item = data[0][i]; // and get the nth object
$('#applicationList > tbody').append(
// code skipped
);
insideData(data);
}
},
Why does it happen?
Because you return List<Object> which has one element List<UserInfo>. This brief sequence of operation adds a list to a list and returns it:
List<Object> userList = new ArrayList<>(); // Creates a List
List<UserInfo> l = userInfoDao.findById(tableId); // Creates another of users
userList.add(l); // Adds List to List
return userList; // Returns the List to List
Since the return type is List<Object>, you might not notice that the returned type is actually List<List<UserInfo>>.
How to fix it?
There are two ways, yet I recommend you the second one:
I suppose that you wanted to add all the elements to the outer List and keep the flat structure. For this, you have to use method List::addAll which passes all the elements from the List to another one. You have used List::add which adds an element to the list as is - in your case the added element was a new entire List and not its elements.
A better way is to return the result directly. If nothing is found, return an empty List:
#RequestMapping(value = "/search", method = RequestMethod.GET)
#ResponseBody
public List<UserInfo> fetchTableData(#RequestParam("tableId") String tableId) {
try {
List<UserInfo> userList = new ArrayList<>();
System.out.println(" table id id " + tableId);
if (tableId != null) {
userList = userInfoDao.findById(tableId);
}
return userList;
} catch (Exception e) {
// log it, don't print the stacktrace...
return Collections.emptyList()
}
}
What more?
I noticed you use the POST method, however since you receive data from the server, you should use GET method regardless you pass a parameter which identifies the entity to be returned. From W3Schools:
GET is used to request data from a specified resource.
POST is used to send data to a server to create/update a resource.
I have a list of group names which the app is reading from external .txt.
I want to pass to method as a List <String> group names and to execute dql query something like:
for (String s : groupnames) {
dql = "DROP GROUP " + s;
System.out.println("dropped group: " + s;
}
How to write/execute DQL?
I have done it by myself:
private static void deleteGroups(List<String> groupsToDelete) {
try {
DfClientX clientX = new DfClientX();
IDfQuery query = clientX.getQuery();
for (String s : groupsToDelete){
query.setDQL("DROP GROUP '" + s + "'");
printInfo("Executing DQL: " + query.getDQL());
query.execute(_session, 0);
}
} catch (DfException e) {
printError(e.getMessage());
DfLogger.error("app", "DQL DROP GROUP execution", null,e);
}
}
Not quite sure does CS permit to delete group via DFC but it should be like:
IDfQuery query = new DfQuery();
query.setDQL("DROP GROUP <group_name>");
query.execute(getSession(), IDfQuery.DF_EXEC_QUERY);
There is for sure way to instantiate group object in memory and call .delete() method. I'll try to check it out.
I have a table with 3 columns say type,name and value.
For example my table has the following values:
Type Name Value
+++++++++++++++++++++++
Int id 0
String name null
How to get these values from the table and set to a list.
TableItem[] items = voTable.getItems();
List<VogenBean> lstTableValue = new ArrayList<VogenBean>();
for (int i = 0; i < items.length; i++) {
System.out.println("Items length--" + items.length);
VogenBean bean = new VogenBean();
bean.setClassName(domainName);
bean.setAttrName(typeLabel.getText());
bean.setMethodName(nameLabel.getText());
bean.setAttrInit(valueLabel.getText());
/*
* tableValue = domainName + ":" + typeLabel.getText() + ":" +
* nameLabel.getText()+":"+valueLabel.getText();
* System.out.println("Value--"+tableValue);
*/
lstTableValue.add(bean);
}
for (Iterator iterator = lstTableValue.iterator(); iterator.hasNext();) {
VogenBean vo = (VogenBean) iterator.next();
System.out.println("Class Name--" + vo.getClassName());
System.out.println("Attr Name--" + vo.getAttrName());
System.out.println("Method Name--" + vo.getMethodName());
System.out.println("Attr Init--" + vo.getAttrInit());
}
return lstTableValue;
This is my code. I'm getting only last field in the table. Please help.
If you want to get the value of a certain row in table based on selection, you can use Table#getSelection(). In case you are using a TableViewer, you have to do a TableViewer#getSelection().
But if you want to just iterate through a table and get all values, just use Table#getItems(). Each item is a TableItem and you can get values for each column by using TableItem#getText(int columnIndex).
Does that answer your question?
I'm using Java and Jena API. I have a class Marriage which have 3 Object Properties called "hasHusband", "Haswife" and "dateOfMarriage". The first two are associated with a class Person which has the datatypeproperties hasFirstName, hasLastName, dateOfBirth....
Through the code below I can access the hasFirstName property of the husband.
StmtIterator iter = onto.model.listStatements(null,onto.hasHusband,(RDFNode)null);
while (iter.hasNext()) {
Statement stmt = iter.nextStatement();
Resource P = ((Resource) stmt.getObject());
StmtIterator iter2 = onto.model.listStatements(((Resource) P),onto.hasFirstName,(RDFNode)null);
while (iter2.hasNext()) {
Statement stmt2 = iter2.nextStatement();
firstnameHusband = stmt2.getObject().toString();
}}
I would like to modify this line
StmtIterator iter2 = onto.model.listStatements(((Resource) P),onto.hasFirstName,(RDFNode)null);
in order to access also the hasLastName and hasDateofBirth...
Can you explain me how can I do this?
Thanks
EDITED:
#Pierre
Now it concerns only the class Person.
In case of womans I want to output in a new file (text file) this line below for each woman:
[label= \"" +firstName+ " \"\n\n\"D.Naiss:"+dnai1+"\", "+shape2+"]
And for each man this:
[label= \"" +firstName+ " \"\n\n\"D.Naiss:"+dnai1+"\", "+shape+"]
The diference is in the value of shape.
The problem I have is that he only outputs one woman and one man.
A person is represented like this in my rdf file:
<rdf:Description rdf:about="http://www.fam.com/FAM#Bruno04/02/1980 ">
<j.0:FAMhasGender>H</j.0:FAMhasGender>
<j.0:FAMhasDateOfBirth>04/02/1980</j.0:FAMhasDateOfBirth>
<j.0:FAMhasLastName>DS </j.0:FAMhasLastName>
<j.0:FAMhasFirstName> Bruno</j.0:FAMhasFirstName>
</rdf:Description>
Here is the relevant code:
public void accessProp() {
readFile(inputFile); // rdf
String fname;
String dd;
String gen;
ExtendedIterator instances = onto.person.listInstances();
Individual instance = null;
Individual firstInstance = null;
while (instances.hasNext()) {
instance = (Individual) instances.next();
gen = instance.getPropertyValue(onto.hasGender).toString();
fname = instance.getPropertyValue(onto.hasFirstName).toString();
dd = instance.getPropertyValue(onto.hasDateOfBirth).toString();
writeFile(fname, dd, genr);
}
}
// Write text file
public void writeFile(String fn, String dbir, String gn) {
String fileout = "D:/file1.txt";
String firstName = fn;
String dateB = dbir;
String gender = gn;
BufferedWriter out;
try {
out = new BufferedWriter(new FileWriter(fileout, true));
if (gender.equals("F")) {
out.write("[label= \"" + firstName + " \"\n\n\"D.Naiss:" + dnai1 + "\", " + shape + "]");
}
else if (gender.equals("M")) {
out.write("[label= \"" + firstName + " \"\n\n\"D.Naiss:" + dnai1 + "\", " + shape2 + "]");
}
out.newLine();
// flushes and closes the stream
out.close();
} catch (IOException e) {
System.out.println("There was a problem:" + e);
}
}
Can you tell me what should I do to solve my problem?
Thanks
If I understand the intent of the question, you want an iterator that gives you the first name, last name, date of birth etc for each Resource. The iterator would be one row per Resource.
This is what SPARQL can do for you.
In outline:
PREFIX : ...
SELECT *
{ ?z :hasHusband ?p .
?p :hasFirstName ?firstName ;
:hasLastName ?lastName ;
:hasDateOfBirth ?dob ;
.
}
and query onto.model.
create a helper function to get a specific property:
public RDFNode getProperty(Resource subject,Property prop)
{
RDFNode object=null;
StmtIterator iter2 = this.onto.model.listStatements(subject,prop,(RDFNode)null);
while (iter2.hasNext()) {
object = iter2.nextStatement().getObject();
break;
}}
iter2.close();
return object;
}
public String getPropertyAsString(Resource subject,Property prop)
{
RDFNode object=getProperty(subject,prop);
return object==null?null:object.toString();
}
(...)
String s1=getPropertyAsString(P,onto.hasFirstName);
String s2=getPropertyAsString(P,onto.hasLastName);
(...)