How to delete a selected row in jsp? - java

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.

Related

Why is it that my form does not redirect me to the route im passing?

Im doing a CRUD app with Java using Servlets and i have a jsp file as a list of many users where i have a button to edit my row. As i click on my button it should redirect me to ServletPacientes?Param=editar&dni=<%a.getDni()%>.
So this is my ListarPacientes.jsp: Where i have some scriplets and my html forms.
<body>
<% if (request.getSession().getAttribute("usuario") == null) {
request.getRequestDispatcher("Login.jsp").forward(request, response);
throw new UsuarioNoLoggeadoException();
}
Usuario user = (Usuario)request.getSession().getAttribute("usuario");
if (user.getTipo_usuario().getID() != 1) {
request.getRequestDispatcher("Home.jsp").forward(request, response);
throw new UsuarioSinPermisoException();
}
%>
<%
if (request.getParameter("buscarLista") == null) {
request.getRequestDispatcher("ServletPacientes?Param=list").forward(request, response);
}
List<Paciente> listaM = new ArrayList<Paciente>();
if (request.getAttribute("listaPac") != null) {
listaM = (List<Paciente>)request.getAttribute("listaPac");
}
%>
<jsp:include page="Menu.jsp"></jsp:include>
<div class="table-title">
<h3>Tabla Pacientes</h3>
</div>
<form method="post" action="ServletPacientes">
<div class="form-group">
<label>Buscar: </label>
<input type="text" class="form-control" name="txtBuscar">
</div>
<div class="col-12">
<input type="submit" class="btn btn-success" value="Buscar" name="btnBuscar">
</div>
<table class="table-fill">
<thead>
<tr>
<th class="text-left">Nombre</th>
<th class="text-left">Apellido</th>
<th class="text-left">DNI</th>
<th class="text-left">Sexo</th>
<th class="text-left">Direccion</th>
<th class="text-left">Fecha de Nacimiento</th>
<th class="text-left">Email</th>
<th class="text-left">Telefono</th>
<th class="text-left">Nacionalidad</th>
</tr>
</thead>
<tbody class="table-hover">
<tr>
<%
for (Paciente a : listaM) {
%>
<tr>
<form action="ServletPacientes" method="post">
<td><%=a.getNombre()%></td>
<td><%=a.getApellido()%></td>
<td><%=a.getDni()%> <input type="hidden" name="dniPaciente" value="<%=a.getDni()%>" ></td>
<td><%=a.getSexo()%></td>
<td><%=a.getDireccion()%></td>
<td><%=a.getFechaNac()%></td>
<td><%=a.getCorreo()%></td>
<td><%=a.getTelefono()%></td>
<td><%=a.getNacionalidad()%></td>
<td> <input type="submit" name="btnEliminar" value="Eliminar" class="btn btn-danger"></td>
</form>
<td> <input type="submit" name="btnEditar" value="Editar" class="btn btn-warning"></td>
</tr>
<%
}
%>
</tbody>
</table>
<br>
<div align="center">
</div>
</form>
</body>
As you can see i have de following tags
<td> <input type="submit" name="btnEditar" value="Editar" class="btn btn-warning"></td>
So in each row i have this button where i call my Controller (Servlet) with the parameter "editar" and i pass the method getDni() of my class Paciente.
And here is my code of my ServletPacientes:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("Param")!=null)
{
String opcion = request.getParameter("Param").toString();
switch (opcion) {
case "previoInsert":
{
break;
}
case "list":
{
request.setAttribute("listaPac", negPac.listarPacientes());
RequestDispatcher dispatcher = request.getRequestDispatcher("/ListarPacientes.jsp?buscarLista=1");
dispatcher.forward(request, response);
break;
}
case "editar":
{
Paciente p = new Paciente();
p = negPac.obtenerUno(request.getParameter("dniPaciente"));
System.out.println(p);
request.setAttribute("dniPac", p);
RequestDispatcher dispatcher = request.getRequestDispatcher("/EditarPaciente.jsp");
dispatcher.forward(request, response);
break;
}
default:
break;
}
}
}
The method above shows a switch where each case is a different parameter that im passing to my route. So when i click on my edit button instead of taking me to for example ServletPacientes?Param=editar&dni=20216447 it just redirects me to ServletsPacientes which is a blank page.
It looks like im never receiving the parameter editar neither the dni property. Becaus if i manually put on my url ServletPacientes?Param=editar&dni=20216447 it does takes me to the Edit view.
You essentially have the following structure:
<form method="post" action="ServletPacientes">
<a href="ServletPacientes?Param=editar&dni=<%=a.getDni()%>">
<input type="submit" value="Editar">
</a>
</form>
This means that when you click on this "Editar" button, a form submission will happen as a POST request. This request is supposed to be processed by a doPost method on the servlet side, and the URL would be /ServletPacientes. This is why you navigate to /ServletPacientes. The link in the wrapping <a> element will have no effect.
If you expect to navigate to something like ServletPacientes?Param=editar&dni=20216447, you'll have to make the nested input element a regular button, not a submit: <input type="button" value="Editar">.

Parameter not received inside controller

I try to send a parameter applicationNo wrapped inside my form tag.The data inside input generated via javascript snippet. I need to pass this data to my controller, but it always throw null pointer exception, I am not able to figure it out what is the problem.
So kindly suggest me the best way to achieve. I also attached required source code and snapshot.
I want to send the data highlighted in red area in below screenshot.
JSP CODE:
<form action="${baseURL}view_grp_conn_applications" id="grpCreationForm" method="post" commandName="command" >
<div class="col-sm-12">
<table id="addAppTable" class="table table-responsive table-bordered table-striped text-center" id="newField">
<thead>
<tr>
<th>#</th>
<th>Application No.</th>
<th>Name</th>
<th>Mobile No.</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<c:set var="i" value="0"></c:set>
<tr>
<td valign="center"><input name="workOrderPostSps[${i}]" id="workOrderPostSps[${i}]" type="checkbox" value="${wo.woPostIdEnc}" onclick="highlightrow(this);" /></td>
<td align="center"><b><input onkeypress="show_list('${i}');" id="appNo1${i}" name="applicationNo" class="form-control start" autocomplete="off" data-validate="required" required="true" placeholder="press key on keyboard"/></b></td>
<td align="left"><span id="appName1${i}"></span></td>
<td align="left"><span id="appContact${i}"></span></td>
<td align="left"><span id="email1${i}"></span></td>
</tbody>
</table>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-turquoise pull-right no-margin " name="saveBtn" id="saveBtn" value="Next >>" onclick="myfunction()">
</div>
</form>
JAVA CODE:
This method open the JSP from where I wish to send the applicationNo
#RequestMapping(value = "/create_group_connection")
public ModelAndView createConnection(Model model) {
ModelAndView mav = new ModelAndView("user/create_group_connection");
Application application = new Application();
mav.addObject("command", application);
return mav;
}
This method will open the jsp where i need to extract that applicationNo
#RequestMapping(value = "/view_grp_conn_applications", method = RequestMethod.POST)
public ModelAndView viewApplications(#ModelAttribute("command")Application application,HttpServletRequest request, HttpSession session) {
ModelAndView mav = new ModelAndView("user/grp_conn_applications");
try {
System.out.println("inside view group applications");
String[] applicationNo = request.getParameterValues("applicationNo");
System.out.println("inside " + applicationNo[0]);
// for (int i = 0; application.length > 0; i++) {
// System.out.println("application number is" + application[i]);
// }
} catch (Exception e) {
System.out.println("Exception occured");
e.printStackTrace();
}
return mav;
}
<td><b><input onkeypress="show_list('${i}');" id="appNo1${i}" name="applicationNo" class="form-control start" autocomplete="off" data-validate="required" required="true" placeholder="press key on keyboard"/></b></td>
you just use the below instead of above
<input type='hidden' id="applicationNo" name="applicationNo" /></b></td>
you just set the application number using Javascript through id of hidden field on any event like onBlur, onKeyPress,Your Controller code is Correct

No result when Pagination with Servlet and JSP

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.

How to pass data from table in JSP to Java controller?

Please help me to solve a problem!
I have table created in JSP and filled with data from my DB, and the problem is - I have not idea how to access that JSP data from my controller.
For example - I need to pass appropriate ID (just String) to my controller from JSP to execute Delete method.
My jsp:
<body>
<form action="/editCategory" method="POST">
<h3>Existing categories</h3>
<%
List<Category> categories = (List<Category>) request.getAttribute("model");
if (categories != null) {
%>
<table border="1">
<tr>
<th width="24">ID</th>
<th width="80">Name</th>
<%--<th></th>--%>
</tr>
<%
for (Category category : categories) {
%>
<tr>
<td><%= category.getId() %> <% request.setAttribute("id", category.getId());%>
</td>
<td><%= category.getName() %>
</td>
<td>
<input type="submit" name="delete" value="Delete"/>
</td>
</tr>
<%
}
%>
</table>
<%
} else {
%>
<b>Categories list is empty :(</b>
<%
}
%>
</form>
</body>
My controller methods:
public Model getModel(HttpServletRequest req, HttpServletResponse resp) throws DBException
{
if (req.getParameter("submit")!=null){
addCategory(req);
}
if (req.getParameter("delete")!=null){
deleteCategory(req);
}
categories = categoryDAO.getCategories();
return new Model("/editCategory.jsp", categories);
}
private void deleteCategory(HttpServletRequest req) {
System.out.println(req.getAttribute("id") + " printed");
}
For now I want just to see that correct ID is taken!
Please help!
you could do it this way:
<%
for (Category category : categories) {
%>
<tr>
<td><%= category.getId() %>
<input type="hidden" name="allIds" value="<%= category.getId() %>" /></td>
<td><%= category.getName() %>
</td>
<td>
<input type="submit" name="delete" value="Delete"/>
</td>
</tr>
<%
}
%>
as the type says hidden is not visible.
after that read the values in your servlet with:
String[] lAllIds = request.getParameterValues("allIds");

Getting list of strings from servlet to jsp

I have a JSP page in which I have two tags. In first I am trying get input such as Car Maker name such as Tata, Hyundai, Toyota, Audi etc. When user selects any option in first , it should display car models from that maker such as Innova,Land Cruiser etc. So when user selects any option in first tag, I am calling a servlet which gets all the models from database in a list and setting the list as attribute of session and forwarding the request back to JSP. But in jsp when I try to fetch the list it is giving NULL POINTER EXCEPTION. How to solve it?
The code is as below:
DbReviewCar.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn= null;
PreparedStatement pstmt= null;
ResultSet rs;
String sql= null;
String maker= request.getParameter("make");
List modellist= new ArrayList();
/*if(maker==null)
{
modellist.add("ferrari");
modellist.add("hummer");
request.getSession().setAttribute("value", modellist);
request.getRequestDispatcher("CarReview.jsp").forward(request,response);
}
else
{*/
try {
Class.forName("com.mysql.jdbc.Driver");
conn= DriverManager.getConnection("jdbc:mysql://localhost/cardetails", "root", "Welcome123");
sql= "select model from cars where make=?;";
pstmt= conn.prepareStatement(sql);
pstmt.setString(1, maker);
rs= pstmt.executeQuery();
while(rs.next())
{
String mod= rs.getString(1);
modellist.add(mod);
System.out.println(mod+">>>>>>>>>>>>>>>>>>.");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
request.getSession().setAttribute("value", modellist);
request.getRequestDispatcher("CarReview.jsp").forward(request,response);
}
CarReview.jsp
Here is my JSP file
<form action="DbReviewCar" method="get" name="myform">
<table>
<tr>
<td>
<tr>
<td>Make:</td>
<td><select name="make" onchange="this.form.submit()"><option>select</option>
<option>Maruti</option>
<option>Ford</option>
<option>Honda</option>
<option>Skoda</option>
<option>Tata</option>
<option>Audi</option>
<option>Toyota</option></select><br></br></td>
</tr>
<%
List list = new ArrayList();
list.addAll((List) (request.getSession().getAttribute("value")));
%>
<tr>
<td>Model:</td>
<td><select name="model">
<%
for (int i = 0; i < list.size(); i++) {
%>
<option value=<%=list.get(i)%>><%=list.get(i)%></option>
<%
}
%>
</select><br></br></td>
</tr>
<tr>
<td>Rating For Style:</td>
<td><input type="text" name="style"><br></br></td>
</tr>
<tr>
<td>Rating for comfort:</td>
<td><input type="text" name="comfort"><br></br></td>
</tr>
<tr>
<td>Rating for Performance:</td>
<td><input type="text" name="performance"><br></br></td>
</tr>
<tr>
<td>Rating for FuelEconomy:</td>
<td><input type="text" name="economy"><br></br></td>
</tr>
<tr>
<td>Review:</td>
<td><textarea cols="18" rows="3"></textarea><br></br></td>
</tr>
<tr>
<td><Button>Save</Button></td>
<td><input type="reset" name="cancel" value="Cancel" /></td>
</tr>
</table>
</form>
When jsp loading for the first time the "value" atribute is not set.
Try to check null for value:
request.getSession().getAttribute("value")

Categories

Resources