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/
Related
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've read a lot about the same question, I tried to follow the answers but it never work.
I have a servlet name: get_import.java
I have a jsp name: import.jsp
First, in processRequest(), i initiated a String s = "abcdef", then i wrote:
s=request.setAttribute("validate", s);
RequestDispatcher rd = getServletContext().getRequestDispatcher("import.jsp");
rd.forward(request,response);
Then, in import.jsp, i wrote:
<% String st = (String)request.getAttribute("validate");
out.println("<h1>Result: " +st+ "</h1>");
%>
Then output was: Result: null
I can't explain why the variable's value is null in jsp, please help me to solve this problem or find other way out. Thanks a lot!!
You have a number of options:
1.Store it in the session.
String username = request.getParameter("username");
if (username != null && username.length() > 0)
{
session.setAttribute("username", username);
}
2.Store it as a hidden field in the form.
<input name="filter" type="hidden" value=""/>
3.Store it in a cookie.
username = getCookie(userCookieName);
// Get from cookie.
function getCookie(name) {
if (document.cookie) {
index = document.cookie.indexOf(name);
if (index !== -1) {
f = (document.cookie.indexOf("=", index) + 1);
t = document.cookie.indexOf(";", index);
if (t === -1) {
t = document.cookie.length;
}
return(document.cookie.substring(f, t));
}
}
return ("");
}
4.Not really another option but a mechanism - pass it in the URL:
.... onclick="window.location = 'details.jsp?filter=...'
try storing the value in session like this way
session.setAttribute("validate", s);
Then, in import.jsp, :
<% String st = (String)session.getAttribute("validate");
out.println("<h1>Result: " +st+ "</h1>");
%>
One side note try avoiding writing java in jsp pages.Best alternate is JSTL/EL
I've searched for this but can't find anything.
Please correct my question if it's incorrect english.
This is my code:
EDIT: The code is within my .jsp file!
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Beoordeling', 'Stage Opleider', 'Student'],
['1', '1', '4'],
<% ArrayList < Stelling > alleStellingenLijst2 = new ArrayList < Stelling > ();
alleStellingenLijst2 = (ArrayList < Stelling > ) request.getAttribute("stellingen");
for (Stelling s: alleStellingenLijst2) {
out.println("['1', '" + s.getDeStelling() + "' , '" + s.getDeWaarde() + "'],");
} %> ]);
var options = {
title: 'Laatste competenties',
hAxis: {
title: 'Score',
titleTextStyle: {
color: 'green'
}
},
vAxis: {
title: 'Beoordeling nummer',
titleTextStyle: {
color: 'green'
}
},
// Allow multiple simultaneous selections.
selectionMode: 'multiple',
colors: ['#BEF781', 'green']
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
For some reason, it wont execute the code between the <% %> (from the jsp).
This page online: http://project-omega.appspot.com/grafieken.jsp
The google app engine logs say the error is on the last line of my page. It's a nullpointerexception.
I have no idea what it means and I really hope someone can help me.
Thanks a lot and sorry for my english.
EDIT
The rendered output looks as follows
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Beoordeling', 'Stage Opleider', 'Student'],
for (Stelling s : alleStellingenLijst2) {
out.println("['1', '" + s.getDeStelling() + "' , '" + s.getDeWaarde() + "'],");
}
]);
NEW CODE:
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Beoordeling', 'Stage Opleider', 'Student'],
['1', 1, 4],
<%
ArrayList<Stelling> alleStellingenLijst2 =(ArrayList<Stelling>) getServletContext().getAttribute("stellingen");
for (Stelling s : alleStellingenLijst2) {
out.println("['1', " + s.getDeStelling() + " , " + s.getDeWaarde() + "],");
}
%>
['2', 2, 2]
]);
These are JSP markups, you cannot use them in JavaScript!
That's because JSP files are compiled to the .java classes during compilation, and JavaScript is executed on the client side.
You could do the opposite - generate a JavaScript code in the JSP file, that way you could pass some data you want to the JS variables.
I suppose you haven't set the stellingen request attribute.
You usually set the request attributes in a servlet, before forwarding the request to jsp:
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
ArrayList<Stelling> list = ...;
req.setAttribute("stellingen", list);
req.getRequestDispatcher("/grafieken.jsp").forward(req, resp);
}
Also make sure the attribute is set in the JSP code:
<%
List<Stelling> stellingen = (List<Stelling>) getServletContext().getAttribute("stellingen");
if(stellingen == null) {
out.println("stellingen attribute not set!");
}else{
for (Stelling s : stellingen) {
out.println("['1', " + s.getDeStelling() + " , " + s.getDeWaarde() + "],");
}
}
%>
I have the following functions to mark attendance of an employee:
public void updateDailyAttendance(ActionRequest areq, ActionResponse aRes) throws Exception {
int totalEmployees = EmployeeLocalServiceUtil.getEmployeesCount();
List<Employee> employeeAttendanceDetails = MISPortalActionUtil.getEmployeeData();
String datt = areq.getParameter("datt");
String Imatt = areq.getParameter("matt");
String yatt = areq.getParameter("yatt");
int Lmatt = Integer.parseInt(Imatt);
String matt = Integer.toString(Lmatt +1);
String dateOfAttendance = datt +"/"+ matt +"/"+ yatt;
SimpleDateFormat dateOfAttendanceFormat = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date date_Of_Attendance = dateOfAttendanceFormat.parse(dateOfAttendance);
System.out.println("Today's attendance date is: " + date_Of_Attendance);
ArrayList<String> attNames = new ArrayList<String>();
for (Employee emp: employeeAttendanceDetails) {
long empId = emp.getEmpId();
String name = "updateattendance" + " " +Long.toString(emp.getEmpId());
System.out.println("updateattendance name : " + name);
String value = getAttendanceValue(areq,name);
System.out.println("updateattendance value : " + value);
long attPKey = CounterLocalServiceUtil.increment(Employee.class.getName());
Attendance newAttendanceInstance = new AttendanceImpl();
String checkAttMarkStatus = newAttendanceInstance.getAttStatus();
System.out.println("checkAttMarkStatus: " + checkAttMarkStatus);
//loop to mark the attendance if it has not been pre marked
if(checkAttMarkStatus != "Absent" || checkAttMarkStatus != "Half Day" ) {
newAttendanceInstance.setAttId(attPKey);
newAttendanceInstance.setAttDate(date_Of_Attendance);
newAttendanceInstance.setAttStatus(value);
newAttendanceInstance.setAttANStatus(value);
newAttendanceInstance.setAttFNStatus(value);
newAttendanceInstance.setEmpId(empId);
AttendanceLocalServiceUtil.addAttendance(newAttendanceInstance);
}//loop to mark the attendance if it has not been pre marked
}
}
/**
* The getAttendanceValue() is used to fetch parameter values and pass the values to updateDailyAttendance function
* #param areq
* #return
* #throws SystemException
*/
private String getAttendanceValue(ActionRequest areq, String paramName) {
Enumeration parameters = areq.getParameterNames();
System.out.println("updateattendance paramName : " + paramName);
while (parameters.hasMoreElements()) {
System.out.println("updateattendance paramName inside while : " + paramName);
String parameterName = parameters.nextElement().toString();
System.out.println("updateattendance paramName new : " + paramName);
System.out.println("the paramName " + paramName + " parameterName " + parameterName);
if (paramName.equals(parameterName)) {
return areq.getParameter(parameterName);
}
}
throw new IllegalStateException("Parameter updateattendance is not found");
}
In my jsp the list of employees is populated and user is allowed to mark attendance through radio button. This approach works well when I am marking attendance for all the employees.
But problem comes when I have pre marked attendance status.
Whenever a user applies for leave his attendance status is premarked and the attendance form for marking attendance for this employee is shown as marked and disabled.. So when I try to mark attendance when pre marked attendance exists, it doesnt mark attendance for other employees. ex. Suppose if the 4th entry is pre marked as absent, and I mark attendance for other employees, then only first three entries are added in the database and then it doesnt find the fourth entry and throws the illegal exception:
Parameter updateattendance is not found
How should I change my getAttendanceValue() function to suit my purpose?
EDIT:
The JSP part where I am fetching the values:
<label>Present</label><input type = "radio" name ='updateattendance <%=((Object[])search)[5]%>' value = "Present" />
<label>Absent</label><input type = "radio" name= 'updateattendance <%=((Object[])search)[5]%>' value = "Absent" />
IN the above code I have kept a check to see if it is pre marked. I have put the above code fragment in if-else block for pre marked attendance check
You're doing this:
Attendance newAttendanceInstance = new AttendanceImpl();
String checkAttMarkStatus = newAttendanceInstance.getAttStatus(); // most likely null or ""
System.out.println("checkAttMarkStatus: " + checkAttMarkStatus);
So I don't expect the correct status to be held by the object that you just created without any reference to previous state. My expectation is that checkAddMarkStatus is now "" (empty string) or null
Further you check for identity of strings, not equality (this is a huge difference in java:
if(checkAttMarkStatus != "Absent" || checkAttMarkStatus != "Half Day" ) {
You should rather use String.equal (and be aware of null values), but due to the issue described above, this will not help you without sorting out both issues. There might be more, but this is what I found on first sight.
Following the comments and your question update, I'm still missing to see the actual intent in the code. However, I'd advise to not use an exception like you do for a case that doesn't seem exceptional - rather use proper return values and check for these values - e.g. if someone never attended, have a value to signal this and react accordingly. If you throw an exception and don't catch it, you must expect things like you mention (e.g. half-executed methods)
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.