I was trying to paging my product list into several pages. Each page contains 12 records. I used servlet to retrieve data from jsp file and JSTL to display data in JSP file. But my jsp file cant display anything. The main problem seems to be with "productList" not being available to the jsp
This is my servlet.
public class ProductServlet extends HttpServlet{
private static final long serialVersionUID=1L;
public ProductServlet(){
super();
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
int page=1;
int rowsPerPage=12;
if (request.getParameter("page") != null) {
page = Integer.parseInt(request.getParameter("page"));
}
ProductDAO pd = new ProductDAO();
List<Product> list = pd.getAllPaging((page - 1) * rowsPerPage, rowsPerPage);
int noOfRows = list.size();
int noOfPages = noOfRows / rowsPerPage;
request.setAttribute("productList", list);
request.setAttribute("noOfPages", noOfPages);
request.setAttribute("currentPage", page);
RequestDispatcher view = request.getRequestDispatcher("productlist.jsp");
view.forward(request, response);
}
}
This is my productlist.jsp file.
<table border="1" cellpadding="5" cellspacing="5">
<tr>
<th>Game ID</th>
<th>Game name</th>
<th>price</th>
<th>Realease date</th>
</tr>
<c:forEach var="product" items="${productList}">
<tr>
<td><c:out value="${product.gameid}"/></td>
<td><c:out value="${product.gamename}"/></td>
<td><c:out value="${product.price}"/></td>
<td><c:out value="${product.releasedate}"/></td>
</tr>
</c:forEach>
</table>
<%--For displaying Previous link except for the 1st page --%>
<c:if test="${currentPage != 1}">
<td>Previous</td>
</c:if>
<%--For displaying Page numbers.
The when condition does not display a link for the current page--%>
<table border="1" cellpadding="5" cellspacing="5">
<tr>
<c:forEach begin="1" end="${noOfPages}" var="i">
<c:choose>
<c:when test="${currentPage eq i}">
<td>${i}</td>
</c:when>
<c:otherwise>
<td>${i}</td>
</c:otherwise>
</c:choose>
</c:forEach>
</tr>
</table>
And finally, my web.xml
<servlet>
<servlet-name>ProductServlet</servlet-name>
<servlet-class>product.ProductServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ProductServlet</servlet-name>
<url-pattern>/productlist</url-pattern>
</servlet-mapping>
I debugged my method getAllPaging() and it works perfectly, I checked and rechecked my jsp with JSTL syntax. It's ok. So I think the problem belongs to my servlet but I cant figure out what it is. Thank you for your help.
Related
I have created a table in the jsp, for the table the data will be loaded from database and rendered into the jsp or web page to show the all appointments , in this particular scenario i want to delete the selected row from database .
The tried code is below but couldn't make it happen and no error is shown as well:
JSP:
<main>
<h1 style="margin-left:5rem; text-align: center; margin-top:4%;"> Scheduled Appointments </h1>
<div class="title-box">
<form method="POST">
<c:choose>
<c:when test="{empty list}">
<h1>No upcoming Appointments</h1>
</c:when>
<c:otherwise>
<table class="styled-table" style="margin-bottom: 15px; margin-top:15px;">
<thead>
<tr>
<th>Patient Name</th>
<th>Appointment Date</th>
<th>Delete</th>
</tr>
</thead>
<c:forEach items="${list}" var="record">
<c:if test="${record.ageInDays lt 1}">
<tbody>
<tr class="active-row">
<td>${record.name}</td>
<td>${record.date}</td>
<td><input type="" name="id" value="${record.appointmentId}"><i class="fas fa-trash-alt"></i></td>
</tr>
</tbody>
</c:if>
</c:forEach>
</table >
</form>
</c:otherwise>
</c:choose>
</div>
</main>
Servlet:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getServletPath().contains("/delete")){
/* deleting the appointment*/
int id= Integer.parseInt(request.getParameter("id"));
if(id>0){
StaffManager.getInstance().deleteAppointments(id);
List list = new ArrayList<>();//Creating a list to hold data
list = StaffManager.getInstance().getAppointments();//MVC method implementation for Searching patient
request.setAttribute("list", list);
request.getRequestDispatcher("/Appointments.jsp").forward(request, response);
}
}
}
The staff Manager:
public void deleteAppointments(int id) {
staff.deleteAppointments(id);
}
The Dao Class:
public void deleteAppointments(int id) {
try{
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hms", "root", "");
PreparedStatement st=conn.prepareStatement("DELETE FROM appointments WHERE AppointmentsID = ? ");
st.setInt(1, id);
st.executeUpdate();
}catch(SQLException e){
e.printStackTrace();
}
}
I'm still new into java web development , so please excuse for not always following the best practices here .
And would really appreciate help to make this work , thank you in advance.
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();
});
===============================update====================================
try{
// snip
while (rs.next()) {
BookListEntity entity = new BookListEntity();
entity.setId(rs.getInt("id"));
entity.setName(rs.getString("name"));
entity.setSubject(rs.getString("subject"));
entity.setInsertTime(rs.getString("insert_time"));
entity.setRentalCheck(rs.getInt("rental_check"));
BookList.add(entity);
}
} catch (Exception e) {
e.printStackTrace();
}
model.addAttribute("TestList",BookList);
this is first controller
-> get BookList to "TestList" and move to view(jsp)
<c:forEach var="listValue" items="${TestList}">
<form action="rentalandreturn.do" method="post">
<tr class="active">
<td><c:out value="${listValue.id}" /></td>
<td><c:out value="${listValue.name}" /></td>
<td><c:out value="${listValue.subject}" /></td>
<td><c:out value="${listValue.insertTime}" /></td>
<c:if test="${listValue.rentalCheck eq 1}">
<td>
<input type="submit" value="貸し出しする" />
</td>
</c:if>
<c:if test="${listValue.rentalCheck eq 0}">
<td><input type="submit" value="返納する" /></td>
</c:if>
</tr>
</form>
</c:forEach>
This is jsp(view) code
->and I want to use c:out value something do
#Controller
public class Rentalandreturn {
#RequestMapping(value = "rentalandreturn", method = RequestMethod.POST)
public String rentalandreturn(HttpServletRequest request, Model model) {
//How can i get c:out value?
String id = (String) request.getAttribute("value");
System.out.println(id);
return "BookList";
}
}
and this is second java code(Controller)
-> I want to get c:out value what I print view page.
is there any way to get c:out value in Controller(=java code)?
sorry about my English. if you don't understand my question. say to comment.
you can not read directly in controller class as it is in , better to write a javascript code to to read the data and from that on an action you can send to controller.
I have two objects Employee and Department Employee contains the dept_id. What i want to do is display the content of Employee in a table in jsp page. But instead of displaying dept_id i want to display dept_name from Department table. So far i have my controller method as:
public ModelAndView viewEmployee(HttpServletRequest request,
HttpServletResponse response) throws Exception {
List<Employee> employeeList = employeeService.getAllEmployee();
List<Department> departmentList = new ArrayList<Department>();
for (Employee e : employeeList) {
departmentList.add(departmentService.getDepartment(e.getDept_id()));
}
Map<String, Object> model = new HashMap<String, Object>();
model.put("employee", employeeList);
model.put("department", departmentList);
return new ModelAndView("viewEmployee", "model", model);
}
viewEmployee.jsp
<table border="1px" bordercolor="black" width=80% align="center">
<tr>
<td>Name</td>
<td>Gender</td>
<td>Salary</td>
<td>Department</td>
<td>Action</td>
</tr>
<c:forEach items="${model.employeeList}" var="element">
<tr>
<td><c:out value="${element.name}" /></td>
<td><c:out value="${element.gender}" /></td>
<td><c:out value="${element.salary}" /></td>
<td>display Department Name here </td>
<td><a
href="<c:url value="editEmployee.htm">
<c:param name="emp_id" value="${element.id}"/>
</c:url>
">Edit</a>
<a
href="<c:url value="deleteEmployee.htm">
<c:param name="emp_id" value="${element.id}"/>
</c:url>
">Delete</a>
</td>
</tr>
</c:forEach>
</table>
Any help? I am not being able to display the map content to the jsp page.
it should be <c:forEach items="${model.employee}" var="element">
Also department should be a property of Employee , so that you can use ${employee.department.name}
Does anyone has uses jsp debug helper page that can be dropped into any webapp or included from within another jsp page to view header, req and session attributes?
can you please share if possible ? It will be a great help for many
Drop pageDebugger.jsp in you webapp
Access the page directly or include from another jsp like, layout.jsp to show this details on every page
This page Lists following in a table
Request Parameters
Page scoped attributes and values
Request scoped attributes and values
Session scoped attributes and values
Application scoped attributes and values
Request headers
All Spring beans defined in the scope
Option to search for a resource on the classpath
Dependency on spring framework is optional remove it if you dont use
pageDebugger.jsp
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<style type="text/css">
td {
word-wrap: break-word;
}
</style>
</head>
<body>
<table width="100%" border="1" cellpadding="0" cellspacing="0"
style="table-layout: fixed;">
<colgroup>
<col width="500">
</colgroup>
<tr>
<th colspan="2">
<h3>attributes in $paramValues</h3>
</th>
</tr>
<c:forEach var="entry" items="${paramValues}">
<tr>
<td><c:out value="${entry.key}" /></td>
<td><c:forEach var="item" items="${entry.value}"
varStatus="status">
<pre><c:out value="${item}" /></pre>
<c:if test="${not status.last}">
<br />
</c:if>
</c:forEach></td>
</tr>
</c:forEach>
<tr>
<th colspan="2">
<h3>attributes in $requestScope</h3>
</th>
</tr>
<c:forEach var="entry" items="${requestScope}">
<tr>
<td><c:out value="${entry.key}" /></td>
<td><pre><c:out value="${entry.value}" /></pre></td>
</tr>
</c:forEach>
<tr>
<th colspan="2">
<h3>attributes in $sessionScope</h3>
</th>
</tr>
<c:forEach var="entry" items="${sessionScope}">
<tr>
<td><c:out value="${entry.key}" /></td>
<td><pre><c:out value="${entry.value}" /></pre></td>
</tr>
</c:forEach>
<tr>
<th colspan="2">
<h3>attributes in $pageScope</h3>
</th>
</tr>
<c:forEach var="entry" items="${pageScope}">
<tr>
<td><c:out value="${entry.key}" /></td>
<td><pre><c:out value="${entry.value}" /></pre></td>
</tr>
</c:forEach>
<tr>
<th colspan="2">
<h3>attributes in $headerValues</h3>
</th>
</tr>
<c:forEach var="entry" items="${headerValues}">
<tr>
<td><c:out value="${entry.key}" /></td>
<td><c:forEach var="item" items="${entry.value}"
varStatus="status">
<pre><c:out value="${item}" /></pre>
<c:if test="${not status.last}">
<br />
</c:if>
</c:forEach></td>
</tr>
</c:forEach>
<tr>
<th colspan="2">
<h3>attributes in $applicationScope</h3>
</th>
</tr>
<c:forEach var="entry" items="${applicationScope}">
<tr>
<td><c:out value="${entry.key}" /></td>
<td><pre><c:out value="${entry.value}" /></pre></td>
</tr>
</c:forEach>
<tr>
<th colspan="2">
<h3>System Properties</h3>
</th>
</tr>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
<%#page import="java.util.Map"%>
<%#page import="java.util.Set"%>
<%#page import="java.util.Properties"%>
<%#page import="java.util.Arrays"%>
<%
Properties p = System.getProperties();
Set<Map.Entry<Object, Object>> set = p.entrySet();
for (Map.Entry<Object, Object> e : set) {
%>
<tr>
<td><%=e.getKey()%></td>
<td><%="".equals(e.getValue()) ? " " : e.getValue()%></td>
<%
}
%>
</tr>
<tr>
<th colspan="2">
<h3>Spring Beans</h3>
</th>
</tr>
<%#page import="org.springframework.web.context.WebApplicationContext"%>
<%#page
import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%#page import="org.springframework.core.io.Resource"%>
<%
try {
WebApplicationContext springContext = WebApplicationContextUtils
.getWebApplicationContext(config.getServletContext());
if (springContext != null) {
String[] beanNames = springContext.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
String className = springContext.getType(beanName)
.getName();
%>
<tr>
<td><%=beanName%></td>
<td><%=className%></td>
</tr>
<%
}
%>
<tr>
<th colspan="2">
<h3>Spring Resources</h3>
</th>
</tr>
<tr>
<th colspan="2">
<form><input name="resources" size="50"/></form>
</th>
</tr>
<%
String resourceNames = request.getParameter("resources");
if (resourceNames != null) {
Resource[] resources = springContext
.getResources(resourceNames);
for (Resource r : resources) {
%>
<tr>
<td><%=r.getFilename()%></td>
<td><%=r.getURI()%></td>
</tr>
<%
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>
Additionally if you have option to modify web.xml, have a look at these that can also be used to monitor / profile active http session attributes
http://code.google.com/p/sessionmon/
http://messadmin.sourceforge.net/
At work I have used JDeveloper to run an application in debug mode from the IDE. You can insert breakpoints into your .jsp and view all the debugging info. Although, I am not a big fan of jdeveloper, it is a nice feature of the IDE.