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.
Related
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.$()
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");
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>
Good day.
I have a JSP view, and a controller, which gives it a model to be populated with.
Here is my controller`s method for JSP.
#RequestMapping("/seller")
public ModelAndView seller() {
if(isUserInRole("SELLER_ROLE"))
{
List<SellerStatistics> entities = sellerService.getAllStatistics().getContent();
List<String> statuses = sellerService.getStatuses();
Map<String, Object> model = new HashMap<String, Object>();
model.put("gridRows", entities);
model.put("statuses", statuses);
return new ModelAndView("seller",model);
}
return new ModelAndView("login");
}
gridRows contains information which must be inserted into table in JSP. One of the columns in that table is "status". Status must be a drop down box to be able to change this row`s status.
Here is my JSP:
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# include file="header.jsp" %>
<div class="container">
<div class="row">
<div class="span12">
<h1>Sellers welcome</h1>
<div class="top-menu">
<span>Период</span><input type="text">
<span>Период</span><input type="text">
<span>Период</span><input type="text">
<span>Период</span><input type="text">
<span>Период</span><input type="text">
<input type="button">
</div>
<table class="table table-bordered table-hover table-condensed">
<thead>
<tr>
<th>id</th>
<th>Email</th>
<th>Телефон</th>
<th>Дата регистрации</th>
<th>Сайт откуда первый раз пришел</th>
<th>Первый поисковый запрос</th>
<th>Оплата</th>
<th>Счет/Реализация/Счет фактура</th>
<th>Журнал посещений</th>
<th>Журнал коммуникаций</th>
<th>Статус</th>
</tr>
</thead>
<c:forEach items="${gridRows}" var="cur">
<tr>
<td>${cur.id }</td>
<td>${cur.email }</td>
<td>${cur.phone}</td>
<td><fmt:formatDate pattern='dd.MM.yyyy HH:mm' value='${cur.registrationDate}'/></td>
<td>${cur.referer}</td>
<td>${cur.searchQuery}</td>
<%--Payments--%>
<td>
<c:forEach items="${cur.payments}" var="payment">
<fmt:formatDate pattern='dd.MM.yyyy' value='${payment.created}'/>
${payment.value} рублей
</c:forEach>
</td>
<td>${cur.aii}</td>
<td>${cur.visits} страниц<br>Подробно</td>
<td>
<c:forEach items="${cur.communicationLog}" var="communication">
${communication.time} ${communication.description}
</c:forEach>
</td>
<td>
<!--Status must be here-->
</td>
</tr>
</c:forEach>
</table>
</div>
</div>
</div>
How do i create drop down box in JSP, and how do i select the current value for each row?
Try this:
<select>
<c:forEach var="item" items="${statuses}">
<c:choose>
<c:when test="${cur.status == item}">
<option selected>${item}</option>
</c:when>
<c:otherwise>
<option>${item}</option>
</c:otherwise>
</c:choose>
</c:forEach>
</select>
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.