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

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");

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">.

Displaying linked text in a groovy template GSP

I have a code that should display data on the page of the model
<% if (patients) { %>
<% patients.each { %>
<tr>
<td>${ ui.format(it.status) }</td>
<td align="center">
<% def linkClaim="patientView.page?patientId=' + ${patientId}+ '&claimUuid=" + ${it.uuid} %>
<button onclick="location.href='${linkClaim}'" type="button">Details</button>
</td>
</tr>
<% } %>
Data from the model:
patients
patientId
Error:
groovy.lang.MissingMethodException: No signature of method: SimpleTemplateScript171.$()

How to get list in jsp

AI have this code:
fileOne.java:
...
em.persist(new Item("A1","B1","C1","A.jpg","abc"));
em.persist(new Item("A2","B2","C2","B.jpg","abc"));
em.persist(new Item("A3","B3","C3","C.jpg","abc"));
...
fileTwo.jsp:
#SuppressWarnings("unchecked")
List<Item> myList = (List<Item>)request.getAttribute("Item");
%>
<span style="font-size: 150%; color: black; text-decoration: underline;">List:</span>
<table id="Table" style="display:block;">
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
<% if(myList != null){
int counter = 0;
for (Item Citem: myList ) { %>
<tr>
<td id="viewA<%=counter%>" ><%= Citem.getA()%></td>
<td id="viewB<%=counter%>" ><%= Citem.getB()%></td>
<td id="viewC<%=counter%>" ><%= Citem.getC()%></td>
<td id="viewImage<%=counter%>"><img alt="itemimg" src="ItemsImage<%= Citem.getImageUrl() %>" width="52" height="52"></td>
</tr>
<% counter++;
}
}
else{
%> Empty;
<%}
%>
</table>
...
And I want to view the List<Item> in a table on my HTML page.
and I get only "Empty" in the page (and the header "List").
what am I doing wrong?
I think you should try it
JAVA code
List<Map> em = null;
em.add( new HashMap<String, String>(){{
put("A","A1");
put("B","B1");
put("C","C1");
put("url","url1 here");
put("msg","message1 here");
}});
em.add( new HashMap<String, String>(){{
put("A","A2");
put("B","B2");
put("C","C2");
put("url","url2 here");
put("msg","message2 here");
}});
em.add( new HashMap<String, String>(){{
put("A","A3");
put("B","B3");
put("C","C3");
put("url","url3 here");
put("msg","message3 here");
}});
jsp code
<table>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
<c:forEach items="${Item}" var="subItem" varStatus="theCount">
<tr>
<td id="viewA<c:out value="${theCount.count}" />" ><c:out value="${subItem.A}" /></td>
<td id="viewB<c:out value="${theCount.count}" />" ><c:out value="${subItem.B}" /></td>
<td id="viewC<c:out value="${theCount.count}" />" ><c:out value="${subItem.C}" /></td>
<td id="viewImage<c:out value="${theCount.count}" />"><img alt="itemimg" src="<c:out value="${subItem.url}" />" width="52" height="52"></td>
</tr>
</c:forEach>
</table>
try it even you don't need to check for null if its null then it returns blanck table not throw any exception.
and add following taglib in jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
If you are using the entity manager, you will have to write a finder method that returns a list. For an ex
Query query = em.createQuery("FROM Item item WHERE item.name = ?");
query.setParameter(1, "abc");
List<Item> items = query.getResultList();
and set the items to the request.
request.setAttribute("Items", items);
em.persist will just persist the object.

Spring Mvc submit/delete checked (selected) records from table

I'm trying to submit selected items from a table and moake some modifications on them but I couldn't get it work.
MyObject.java
public class MyObject{
boolean checkControl = true; //default true
private String name;
private String code;
//getters & setters
}
MyObjectForm.java
public class MyObjectForm {
private List<MyObject> myList;
public List<MyObject> getMyList() {
return myList;
}
public void setMyList(List<MyObject> myList) {
this.myList= myList;
}
}
list-myObjects.jsp
<form:form action="submitList" method="post" modelAttribute="myObjectForm">
<table>
<tbody>
<c:forEach items="${myObjectForm.myList}" var="row" varStatus="status">
<tr>
<td>
<spring:bind path="myList[${status.index}].checkControl">
<input type="checkbox" value="<c:out value="${status.value}"/>" name="isChecked" <c:if test="${row.checkControl}"> checked="checked" </c:if> />
</spring:bind>
</td>
<td>${row.name}</td>
<td>${row.code}</td>
</tr>
</c:forEach>
</tbody>
</table>
<button type="submit">Submit</button>
</form:form>
And the controller
#RequestMapping(value = "/submitList", method = RequestMethod.POST)
public String save(#ModelAttribute("myObjectForm") MyObjectForm myObjectForm, Model model) {
List<MyObject> selectedtList = myObjectForm.getMyList(); //returns null
if (selectedtList == null) {
System.out.println("no objects selected");
}
else {
//Make some computation
}
model.addAttribute("resultArray", selectedtList);
return "display-items";
}
Some users asked me to explain this in more detail by email. So I decided to submit it here, Hope this helps.
I'm using spring annotations, to do the job. here is what I did to process selected checkboxes,
I have a java entity class which includes a boolean value for the checkbox, for example a Person class
// Person.java
class Person {
private Long id;
private String name;
private boolean check;
//here goes getters and setters
}
than I have a form object in java, which contains a list of Person
//PersonForm.java
class PersonForm {
private List<Person> personList;
//getters and setters here
}
in my case, there are two jsp pages, the first one lists items, with checkboxes, and the second one lists selected items.
the first jsp file is list.jsp
//list.jsp
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="datatables" uri="http://github.com/dandelion/datatables"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
....
<body>
<form:form action="sent-list" method="post" modelAttribute="personForm">
<table id="item-list" class="table table-striped table-bordered">
<thead class="dataTableHeader">
<tr>
<th width="10%" style="text-align:center">
CheckBox
</th>
<th>id</th>
<th>name</th>
</tr>
</thead>
<tbody>
<c:forEach items="${personForm.personList}" var="listItem" varStatus="status">
<tr>
<td style="text-align:center">
<form:checkbox path="listItem[${status.index}].check"/>
</td>
<td>${listItem.id} <form:hidden path="listItem[${status.index}].id"/></td>
<td>${listItem.name} <form:hidden path="listItem[${status.index}].name"/></td>
</tr>
</c:forEach>
</tbody>
</table>
<button class="btn btn-large btn-success pull-right" type="submit">POST</button>
</form:form>
</body>
</html>
the second jsp file is as follows
//sent-list.jsp
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="datatables" uri="http://github.com/dandelion/datatables"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
.....
<body>
<form:form action="#" method="post" modelAttribute="personForm">
<table id="item-list" class="table table-striped table-bordered">
<thead class="dataTableHeader">
<tr>
<th>id</th>
<th>name</th>
</tr>
</thead>
<tbody>
<c:forEach items="${resultList}" var="personItem" varStatus="status">
<tr>
<td>${personItem.id}</td>
<td>${personItem.name}</td>
</tr>
</c:forEach>
</tbody>
</table>
</form:form>
</body>
</html>
and finally there is a controller, which makes the computation
//PersonController.java
#Controller
class PersonController {
#RequestMapping(value = "/sent-list", method = RequestMethod.POST)
public String save(#ModelAttribute("personForm") PersonForm personForm, Model model){
for(Person personItem : personForm.getPersonList){
//make some computation here
}
}
}
I hope this helps.
Sounds like a binding issue. Have you tried using Spring's <form:checkbox> tag rather than <spring:bind>? It will automatically generate the checkbox attributes as well as adding a hidden field that Spring uses to determine whether the checkbox is 'on' or 'off'.
<form:form action="submitList" method="post" modelAttribute="myObjectForm">
<table>
<tbody>
<c:forEach items="${myObjectForm.myList}" var="row" varStatus="status">
<tr>
<td>
<form:checkbox path="myList[${status.index}].checkControl"/>
</td>
<td>${row.name}</td>
<td>${row.code}</td>
</tr>
</c:forEach>
</tbody>
</table>
<button type="submit">Submit</button>
</form:form>

JAVA String error in JSP

Im getting a curious error with an ArrayList, below is the code (note that this code was copied from an online servlet example, I am a JAVA novice).
the JSP:
<%#page import="p.SecondExample"%>
<%# page language="java" import="java.util.*;"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Servlet Application</TITLE>
<script language="javascript">
function editRecord(id){
window.location.href="editServlet/"+id;
}
function deleteRecord(id){
window.location.href="deleteUser/"+id;
}
</script>
</HEAD>
<BODY>
<br>
<table align="center">
</table>
<br>
<table width="600px" align="center" style="background-color:#EDF6EA;border:1px solid #000000;">
<tr><td colspan=9 align="center" height="10px"></td></tr>
<tr><td colspan=9 align="center"><!-- Add New User--></td></tr>
<tr><td colspan=9 align="center" height="10px"></td></tr>
<tr style="background-color:#7BA88B;font-weight:bold;">
<td>Sector Segment</td><td>Color</td>
</tr>
<%
String bgcolor="";
int count=0;
List viewList = new ArrayList();
Iterator viewItr;
SecondExample se = new SecondExample();
se.doPost(request, response);
if(request.getAttribute("userList")!=null && request.getAttribute("userList")!="")
{
List userList = (ArrayList)request.getAttribute("userList");
Iterator itr = userList.iterator();
System.out.println(userList);
while(itr.hasNext())
{
if(count%2==0)
{
bgcolor = "#C8E2D1";
}
else
{
bgcolor = "#EAF8EF";
}
viewList = (ArrayList)itr.next();
int id = Integer.parseInt(viewList.get(0).toString());
viewItr = viewList.iterator();
%>
<tr style="background-color:<%=bgcolor%>;">
<%
while(viewItr.hasNext())
{
%>
<td><%=viewItr.next()%></td>
<%
}
count++;
%>
<td><input type="button" name="edit" value="Edit" style="background-color:#49743D;font-weight:bold;color:#ffffff;" onclick="editRecord(<%=id%>);" ></td>
<td><input type="button" name="delete" style="background-color:#ff0000;font-weight:bold;;color:#ffffff;" value="Delete" onclick="deleteRecord(<%=id%>);"></td>
</tr>
<%
}
}
if(count==0)
{
%>
<tr><td colspan="9" align="center"> </td></tr>
<tr><td colspan="9" align="center">No Record Avaliable</td></tr>
<%
}
%>
<tr><td colspan=9 align="center" height="2px"></td></tr>
</table>
</BODY>
</HTML>
in debug, the error appears to occur with:
viewList = (ArrayList)itr.next();
int id = Integer.parseInt(viewList.get(0).toString());
viewItr = viewList.iterator();
where my error appears as:
org.apache.jasper.JasperException: java.lang.ClassCastException: java.lang.String cannot be cast to java.util.ArrayList
I'm not quite sure why or how to make next a string. Any help is greatly appreciated.
Yep, itr.next() returns a String, which cannot be cast into an ArrayList.
String value = (String) itr.next();
int id = Integer.parseInt(value);
The following few lines of code in which you're iterating over your viewArray can be removed now, too.

Categories

Resources