JSTL forEach not displaying anything - java

i am trying to display a JSTL loop using list in a JSP code but it is not displying anything , neither it is giving any type of error nor any result
servlet code :
public void doGet(HttpServletRequest req , HttpServletResponse res) throws ServletException,IOException {
res.setContentType("text/html;charset=UTF-8");
PrintWriter pw = res.getWriter();
String n=req.getParameter("action");
HttpSession ses = req.getSession();
String userid = ses.getAttribute("uname").toString();
if(n.equalsIgnoreCase("viewcart")) {
ses.setAttribute("cartlist", o.showCart(userid));
rd=req.getRequestDispatcher("/Register/cart.jsp");
rd.forward(req, res);
}
}
java function (showCart)
List<product> cart=new ArrayList<product>();
try {
conn = obj.connect();
String sql="it is working i checked in DB";
cs=conn.createStatement();
rs=cs.executeQuery(sql);
while(rs.next()) {
product p=new product();
p.setPname(rs.getString(1));
p.setQuantity(rs.getString(2));
p.setPrice(rs.getString(3));
p.setDtime(rs.getString(4));
p.setImg(rs.getString(5));
cart.add(p);
}
JSP code :
<c:forEach items="${cartlist}" var="product">
<tr>
<td>jbefjkw<c:out value="${product.pname}" /></td>
<td><c:out value="${product.quantity}" /></td>
<td><c:out value="${product.price}" /></td>
<td><c:out value="${product.dtime}" /></td>
<td>Rs <c:out value="${product.price}" /></td>
</tr>
product class :
public class product {
private String quantity;
private String dtime;
etc ..
public void setPname(String pname) {
this.pname=pname;
}
public String getPname() {
return pname;
}
etc and etc ....
the query is working in DB i checked multiple times .... the issue is guess with the forEach , it is unable to fetch the variables and the loop is not even running once
thnks in advance

Related

Trouble running overridden doPost method in a java servlet [duplicate]

This question already has answers here:
How do I call a specific Java method on a click/submit event of a specific button in JSP?
(4 answers)
How do I pass current item to Java method by clicking a hyperlink or button in JSP page?
(1 answer)
Closed 3 years ago.
The code below is from the jsp file.
<table class="table table-striped table-hover table-responsive ezoo-datatable">
<thead>
<tr>
<th class="text-center">Schedule ID</th>
<th class="text-center">Feeding Time</th>
<th class="text-center">Recurrence</th>
<th class="text-center">Notes</th>
<th class="text-center">Food</th>
<th class="text-center">Animal ID</th>
<th></th>
</tr>
</thead>
<% int counter = 0; %>
<tbody>
<form action="feedingSchedules" method="post">
<c:forEach var="schedule" items="${feeding_schedules}">
<tr>
<td><c:out value="${schedule.schedule_ID}" /></td>
<td><c:out value="${schedule.feeding_time}" /></td>
<td><c:out value="${schedule.recurrence}" /></td>
<td><c:out value="${schedule.notes}" /></td>
<td><c:out value="${schedule.food}" /></td>
<td><c:out value="${schedule.animalID}" /></td>
<td><button class="btn-danger-stale" name="btn${counter}" value="val${counter}">Delete Schedule</button></td>
<% counter++; %>
</tr>
</c:forEach>
<input type="hidden" name="numSchedules" value="${counter}"/>
</form>
</tbody>
</table>
This code builds a table of data. I have a servlet to populate the table by fetching data from a database in a call to a dao method. I need to add buttons to the table to delete the row corresponding to the button. I have the buttons in place, but I'm not sure how to get them to perform the actual deletion.
#WebServlet(description = "This servlet is the main interface into the Feeding Schedules System", urlPatterns = { "/feedingSchedules" })
public class FeedingSchedulesServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Grab a list of Animals from the Database
FeedingScheduleDAO dao = DAOUtilities.getFeedingScheduleDao();
List<FeedingSchedule> schedules = dao.getAllSchedules();
// Populate the list into a variable that will be stored in the session
request.getSession().setAttribute("feeding_schedules", schedules);
request.getRequestDispatcher("feedingScheduleHome.jsp").forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
FeedingScheduleDAO dao = DAOUtilities.getFeedingScheduleDao();
List<FeedingSchedule> schedules = dao.getAllSchedules();
//Get Parameters
System.out.println("got here");
int count = Integer.parseInt(request.getParameter("numSchedules"));
for(int i = 0; i < count; i++) {
String btn = null;
btn = request.getParameter("btn" + i);
if(btn == ("val" + i)) {
System.out.println("got here");
// call delete method from DAO
try {
dao.deleteSchedule(schedules.get(i));
request.getSession().setAttribute("message", "Schedule successfully deleted");
request.getSession().setAttribute("messageClass", "alert-success");
response.sendRedirect("feedingSchedules");
} catch (Exception e) {
e.printStackTrace();
request.getSession().setAttribute("message", "There was a problem deleting the schedule at this time");
request.getSession().setAttribute("messageClass", "alert-danger");
request.getRequestDispatcher("feedingScheduleHome.jsp").forward(request, response);
}
}
}
}
}
The above code is the servlet. The print lines I put in the overridden doPost method do not show in the console when I click the buttons, so I do not believe the method is being called properly. Does anyone know what I'm doing wrong? I've spent a few hours staring at this and could use some fresh eyes.
Assign an id to your form e.g.
<form id="myForm" action="feedingSchedules" method="post">
And replace
<button class="btn-danger-stale" name="btn${counter}" value="val${counter}">Delete Schedule</button>
with
<button class="btn-danger-stale" name="btn${counter}" value="val${counter}" onclick="document.getElementById('myForm').submit();">Delete Schedule</button>
Alternatively,
Assign an id to your form as mentioned above and also to your button as mentioned below:
<button id="myButton" class="btn-danger-stale" name="btn${counter}" value="val${counter}">Delete Schedule</button>
and add the following javascript in your jsp file:
var form = document.getElementById("myForm");
document.getElementById("myButton").addEventListener("click", function () {
form.submit();
});

Expression language can't access getter methods

I have the following class users.java:
package org.XY;
public class user {
private String mail;
private String name;
private String org;
private String pw;
private String admin;
public user (String mail,String name,String org, String pw, String admin){
this.mail=mail;
this.name=name;
this.org=org;
this.pw = pw;
this.admin = admin;
}
public String getMail() {
return this.mail;
}
public String getName() {
return this.name;
}
public String getOrg() {
return this.org;
}
public String getPw() {
return this.pw;
}
public String getAdmin() {
return this.admin;
}
public String getUser() {
String u = this.mail + " | " + this.name + " | " + this.org + " | " + this.pw + " | Is admin:" + this.admin;
return u;
}
}
And the following jsp page:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page import="org.XY" %>
<%# page import="java.util.List" %>
<%#page isELIgnored="false"%>
<html>
<head>
<title>myservlet</title>
</head>
<body>
<%--<c:forEach items="${users}" var="user">
<tr>
<td><c:out value="${user.getMail()}" /></td>
<td><c:out value="${user.getName()}" /></td>
<td><c:out value="${user.getOrg()}" /></td>
<td><c:out value="${user.getPw()}" /></td>
<td><c:out value="${user.getAdmin()}" /></td>
</tr>
</c:forEach>--%>
<%
List<user> users = (List<user>) request.getAttribute("users");
for (user user : users) {
%>
${user.mail}
<%
}
%>
<%
for (user user : users) {
out.println("<li>" + user.getPw());
}
%>
...
I want to create a table which contains all the data from the users.
As you can see, I tried using the ${user.mail} method with el.
Both give me an javax.el.PropertyNotFoundException: No public static field named [mail] was found on class [org.isse.sopro.user] error and an java.lang.NoSuchFieldException: mail error.
I already tried renaming the getter methods but it did not solv the issue.
Could someone tell me what I am diong wrong?
Regards
Andi
UPDATE:
Obviously it wasn't about the program itself, it was about maven. After a complete reload from Intellij, maven reloaded the project and everything worked fine.
You can not use ${user.mail} because of did not implements Serializable
You need change user class implements Serializable
public class user implements Serializable{
}
And you can use ${user.mail} instead of ${user.getMail()}
<c:forEach items="${users}" var="user">
<tr>
<td><c:out value="${user.mail}" /></td>
</tr>
</c:forEach>
Try this
<%--<c:forEach items="${users}" var="user">
<tr>
<td><c:out value="${user.mail}" /></td>
<td><c:out value="${user.name}" /></td>
<td><c:out value="${user.org}" /></td>
<td><c:out value="${user.pw}" /></td>
<td><c:out value="${user.admin}" /></td>
</tr>
</c:forEach>--%>

Display ArrayList (EJB session + Servlet + JSP, no JDBC)

I've search on stack and on the internet and I haven't find the anwser at my problem.
I try to display an ArrayList from ejb to a jsp page by a servlet. I use mysql-connector-java-5.1.22-bin and not jdbc. I succeed in getting data from the database but the servlet is unable to send this ArrayList to the jsp page. Can you help? I've tried many checks and it seems like the problem is when I get the arraylist in servlet.. I probably badly call it..
Here my code :
accessBean :
public class accessBean implements accesCatalogueBeanRemote, accesCatalogueBeanLocal {
public List getLivresList() {
String flightQuery = "SELECT p FROM produit p";
Query q = em.createQuery(flightQuery);
List existing = q.getResultList();
return existing;
}
}
My servlet :
#WebServlet("/servlet")
public class servlet_produit extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
List list = null;
//Connexion JNDI (annuaire pour localiser l'EJB)
try{
final Hashtable jndiProperties = new Hashtable();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
final Context context = new InitialContext(jndiProperties);
final String appName = "BktEAR";
final String moduleName = "Commands";
final String beanName = "JNDI";
final String viewClassName = accesCatalogueBeanRemote.class.getName();
accesCatalogueBeanRemote remote = (accesCatalogueBeanRemote)
context.lookup("ejb:"+appName+"/"+moduleName+"/"+
beanName+"!"+viewClassName);
list = remote.getLivresList();
}
catch (Exception e) {
e.printStackTrace();
}
session.setAttribute("books", list);
response.sendRedirect("product.jsp");
}
}
And the place I call the servlet in my jsp page :
<c:forEach items="${books}" var="list">
<tr>
<td>ok : ${list.id}</td>
<td><c:out value="${list.name}" /></td>
<td><c:out value="${list.description}" /></td>
<td><fmt:formatNumber value="${list.price}" type="currency" /></td>
</tr>
</c:forEach>
Thanks by advance.
You are putting data into your session in this line
session.setAttribute("books", list);
So you should retrieve them in jsp from session. You can access session in jsp by using ${sessionScope.books}.
This will helps you:
<c:forEach items="${sessionScope.books}" var="list">
<tr>
<td>ok : ${list.id}</td>
<td><c:out value="${list.name}" /></td>
<td><c:out value="${list.description}" /></td>
<td><fmt:formatNumber value="${list.price}" type="currency" /></td>
</tr>
</c:forEach>

How to display String of Json in jsp table

I have searched every where, but can't find the help I need.
In my servlet I receive a String containing JSON data. These data are rows from a database and contains this:
[{"note_id":1,"title":"Homework","text":"Math ex. 15, 16, 17.","color":"Yellow","datetime":""}]
My problem is that I'm not able to show these data on a html table using jstl.
This is what I get:
(I'm getting stressed and can't figure out how to solve this).
Servlet code (post method):
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
.
.
.
String output = resp.getEntity(String.class);
System.out.println("* JSON string contains: * " + output); //prints the string with json data successfully
ObjectMapper objectMapper = new ObjectMapper();
TypeReference<ArrayList<Note>> mapType = new TypeReference<ArrayList<Note>>() {};
ArrayList<Note> jsonToList = objectMapper.readValue(output, mapType);
request.setAttribute("allNotesOfUser", jsonToList);
RequestDispatcher rd = request.getRequestDispatcher("/Notes.jsp");
rd.forward(request, response);
}
jsp code (just the table part):
<table class="table table-striped">
<thead>
<tr>
<th> Id </th>
<th> Title </th>
<th> Text </th>
<th> Color </th>
<th> Date/Time </th>
</tr>
</thead>
<tbody>
<c:forEach items="${allNotesOfUser}" var="pp">
<tr>
<td><${pp.note_id}</td>
<td><${pp.title}</td>
<td><${pp.text}</td>
<td><${pp.color}</td>
<td><${pp.datetime}</td>
</tr>
</c:forEach>
</tbody>
</table>
Note entity:
#XmlRootElement
public class Note {
private int note_id;
private String title;
private String text;
private String color;
private String datetime;
public Note(int note_id, String title, String text, String color, String datetime){
this.note_id = note_id;
this.title = title;
this.text = text;
this.color = color;
this.datetime = datetime;
}
public Note(){
super();
}
public int getNote_id() {
return note_id;
}
public void setNote_id(int note_id) {
this.note_id = note_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getDatetime() {
return datetime;
}
public void setDatetime(String datetime) {
this.datetime = datetime;
}
}
I don't know why, but I tried to insert <c:out value="" /> in my JSP code, so it looked like this:
<c:forEach items="${allNotesOfUser}" var="pp">
<tr>
<td><c:out value="${pp.note_id}" /></td>
<td><c:out value="${pp.title}" /></td>
<td><c:out value="${pp.text}" /></td>
<td><c:out value="${pp.color}" /></td>
<td><c:out value="${pp.datetime}" /></td>
</tr>
</c:forEach>
So now it's working:
Here is a link for some reference of the c:out
(Now i'll just continue and get stuck somewhere else T-T crying XD)
simple way you can send the Note entity to jsp page and print it. and you can also use JSON object bt bst way with JSON object you have to use java script. but you can also use com.google.gson.JSONObject for resolve this problem.

print complete rows in table which is passed from servlet

I have one jsp page and one servlet, In servlet i want to fetch some rows from a particular table and pass them to jsp .I am able to retrieve in servlet and trying to pass them in jsp it is not getting displayed please anyone help me out here...
public class TimeDetail extends HttpServlet {
#SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
HttpSession session = request.getSession(true);
String eid = (String) session.getAttribute("eid");
int count = 0;
Connection con = ConnectionManager.getConnection();
try {
Statement st = con.createStatement();
Statement st1 = con.createStatement();
String Query = "select date, intime, outtime, eid from fulltime where eid='" + eid + "'";
ArrayList Rows = new ArrayList();
ResultSet rs = st.executeQuery(Query);
List agentList = new ArrayList();
while (rs.next()) {
ArrayList row = new ArrayList();
for (int i = 1; i <= 4; i++) {
row.add(rs.getString(i));
}
String n1 = rs.getString("date");
String n2 = rs.getString("intime");
String n3 = rs.getString("outtime");
String n4 = rs.getString("eid");
session.setAttribute("n1", n1);
session.setAttribute("n2", n2);
session.setAttribute("n3", n3);
session.setAttribute("n4", n4);
// response.sendRedirect("TimeDetail.jsp");
Rows.add(row);
}
request.getSession().setAttribute("results", Rows);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/TimeDetail.jsp");
rd.forward(request, response);
} catch (Throwable theException) {
System.out.println(theException);
}
}
}
and here is jsp code
<tr><td>
<table width="600" height="300"align=center cellspacing=0 border="0"
<caption><h2>List of users</h2></caption>
<tr>
<th>date</th>
<th>intime</th>
<th>outtime</th>
<th>eid</th>
</tr>
<c:forEach var="user" items="${Rows.rows}">
<tr>
<td><c:out value="${user.date}" /></td>
<td><c:out value="${user.intime}" /></td>
<td><c:out value="${user.outtime}" /></td>
<td><c:out value="${user.eid}" /></td>
</tr>
</c:forEach>
</table>
</div>
</table><BR>
</fieldset>
</td></tr></table>
</td></tr>
</table>
</body>
</html>
Your for each loop should be like this ,
<c:forEach var="user" items="${results}">
<tr>
<td><c:out value="${user}" /></td>
<td><c:out value="${user}" /></td>
<td><c:out value="${user}" /></td>
<td><c:out value="${user}" /></td>
</tr>
</c:forEach>
And your servlet as ,
try {
Statement st = con.createStatement();
Statement st1 = con.createStatement();
String Query = "select date, intime, outtime, eid from fulltime where eid='" + eid + "'";
ArrayList row = new ArrayList();
ResultSet rs = st.executeQuery(Query);
while (rs.next()) {
row.add(rs.getString("date"));
row.add(rs.getString("intime"));
row.add(rs.getString("outtime"));
row.add(rs.getString("eid"));
}
}
request.getSession().setAttribute("results", row);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/TimeDetail.jsp");
rd.forward(request, response);
Hope this helps !!

Categories

Resources