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

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>

Related

Hidden inputs in JSP returning as null in Java Servlet - why?

I'm trying to send a variable from my JSP to my Servlet using the post method. However, the value is continually returning null. I've put in prints and another type of hidden input to check for other errors, but it's just that the inputs are null in the servlet. Why is this?
JSP: (this code is within a table)
<c:set var="counter" value="0"/>
<tbody>
<form id="myForm" 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 id="myButton" class="btn-danger-stale" name="btn${counter}" value="val${counter}">Delete Schedule</button></td>
<c:set var="counter" value="${counter + 1}"/>
<c:out value="${counter }"/>
</tr>
</c:forEach>
<c:out value="${counter }"/>
<input type="hidden" name="hi" id="hi" value="hi"/>
<input type="hidden" name="numSchedules" id="numSchedules" value="${counter}"/>
</form>
</tbody>
</table>
<script type="text/javascript">
var form = document.getElementById("myForm");
document.getElementById("myButton").addEventListener("click", function () {
form.submit();
});
</script>
Servlet: ('test' variable is null; code crashes at 'count' declaration because parseInt can't parse a null value)
#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");
String test = request.getParameter("hi");
System.out.println(test);
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);
}
}
}
}
You can try debugging the code by making the form method=GET. This will help you to know the values that are going to Servlet. Then you can just check the URL to see if the data is there or not. Try this if you cannot see the data in the url that means that the form submit is not working properly.

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

How to get data from jsp page in struts1

I have below JSP page. Using this I can bind data and its working fine.
I am using logic:iterate for binding data from list.
What I am doing fetch the data from database and set it to list and using this list I can bind data into login iterate.
I am using below VO for bind data:
public class EDCPEmployeeRequestForm extends ActionForm {
private static final long serialVersionUID = 1L;
private String employeeCode ;
private String employeeName;
private String employeeAddress;
private String cardNo;
private String employeeEmailId;
private String employeeContactNo;
private String company;
private String strCompany;
private String employeeWorkCity;
private String employeeWorkLocation;
private String band;
private String status;
private EDCPNomineeDetailsForm[] nomineeDetailsList;
// getter and setter method....
.....
Now I want get the data from list which is use in the login:iterator. Why I need if any user login first time then empty list will generate and empty data all the field in which are used within login:iterate.
When user press the submit button in the the above form then below action class is execute :
public class EDCPEnrollmentAction extends Action {
Logger LOGGER = Logger.getLogger(this.getClass());
#Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession(false);
EDCPEmployeeRequestForm eDCPEmployeeRequestForm = (EDCPEmployeeRequestForm) form;
LOGGER.info("EDCPRequest Object : "+eDCPEmployeeRequestForm.toString());
}
}
Ouput when user press submit button :
EDCPEmployeeRequestForm [employeeCode=123456, employeeName=Test,
employeeAddress=null, cardNo=null, employeeEmailId=test#gmail.com,
employeeContactNo=124589652, company=null, strCompany=1001,
employeeWorkCity=1001, employeeWorkLocation=10011, band=2D,
status=null, nomineeDetailsList=null]
You can see that nomineeDetailsList=null its showing null.
But now problem is that I am getting the value for nomineeDetailsList field. Every time I am getting null when I am trying to get value from VO.
My HTML file is designed as below :
<html:form action="/eDCPEnrollment" onsubmit="return checkallfields()">
<logic:iterate id="nomineeData" name="eDCPEmployeeRequestForm" property="nomineeDetailsList" indexId="index" >
<table width="709" border="0" align="center" cellpadding="1" cellspacing="0">
<tr>
<td width="162" height=10></td>
<td width="162"></td>
<td width="162"></td>
<td width="163"></td>
<td width="50"></td>
</tr>
<tr>
<td align="right" class="text">Name :</td>
<td align="center"><html:text property="firstName" name="nomineeData"
maxlength="25" styleClass="textfield" indexed="true"></html:text></td>
<td align="center"><html:text property="middleName" name="nomineeData"
maxlength="25" styleClass="textfield" indexed="true"></html:text></td>
<td align="center"><html:text property="lastName" name="nomineeData"
maxlength="25" styleClass="textfield" indexed="true"></html:text></td>
<td></td>
</tr>
<tr><td><html:submit styleClass="button"></html:submit></td></tr>
</table>
</html:form>
I am stuck here. Please correct me if I missing something.

JSTL forEach not displaying anything

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

How to get value without accessing database?

I need your help. I'm currently doing a project on purchase. After the user click on Add to cart, the item will be added to the cart but not yet persist into database. Then later on, I will have the user to click checkout. PurchaseCart.jsp will do action and bring them to PurchaseCheckOut servlet. So, how can I get the data from previous ?
PurchaseCart.jsp
<body>
<%!List<Double> stockArray = new ArrayList<Double>() ;%>
<%!List<Object> list1 = new ArrayList<Object>();%>
<% Object o = request.getAttribute("purchased");
list1.add(o);
int size = list1.size();
double stockPrice = (Double)request.getAttribute("stockPriceReal");
if(stockArray.size() == 0)
{
stockArray.add(stockArray.size(),stockPrice);
}
else {
stockArray.add(stockArray.size(), stockPrice); } %>
<form action = "../PurchaseCheckOut">
<table border="1">
<thead>
<tr>
<th>No.</th>
<th>Purchase Details ID</th>
<th>Stock ID</th>
<th>Quantity</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<% for (int g = 0; g < size; g ++) { %>
<tr>
<% String toString = list1.get(g).toString();
String subString1 = toString.substring(0,7);
String subString2 = toString.substring(7,9);
String subString3 = toString.substring(9,14);
%>
<td><%= g +1 %></td>
<td><%= subString1 %></td>
<td><%= subString2 %></td>
<td><%= subString3 %></td>
<td><%= stockArray.get(g).toString() %></td>
</tr>
<% } %>
</tbody>
</table>
<input type = submit name="checkout" value="Check Out">
</form>
</body>
PurchaseCheckOut.java (I've done the persist part and redirect part but I have no idea how to get the value. ? is the value i'm passing in.)
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
PurchaseService ps = new PurchaseService(em);
utx.begin();
boolean success = ps.addPurchaedetails(?);
utx.commit();
HttpSession session = request.getSession();
session.setAttribute("success", success);
response.sendRedirect("MemberAccess/AddConfirm.jsp");
}
catch (Exception ex) {
Logger.getLogger(PurchaseCheckOut.class.getName()).log(Level.SEVERE, null, ex);
}
PurchaseService for addPurchasedetails
public boolean addPurchasedetails(Purchasedetails purcD) {
mgr.persist(purcD);
return true; }
Structure of the purchase works like this : PurchaseM.jsp(let user to choose) -> PurchaseCreate.java(pass all the value to cart) -> PurchaseCart.jsp (display the value(not yet persist))-> PurchaseCheckOut.java(persist) -> AddConfirm.jsp(display "You've done")
You can store the add to cart value in a Session object and refer anywhere you need to.

Categories

Resources