I have searched several examples, still have not get. I am passing an List of GOOD object from controller into jsp pages. trying to loop over the list object, but its showing only one element repeatedly. should I use beans? If yes, could you provide more specific example for my case.
<c:if test="${not empty listGood}">
<c:forEach var="ob" varStatus="status" items="${listGood}">
<tr>
<td><c:out value="${ob.name}"/></td>
<td><c:out value="${ob.measure}"/></td>
<td><c:out value="${ob.quantity}"/></td>
<td><c:out value="${ob.price}"/></td>
</tr>
</c:forEach>
</c:if>
Update
Here is the controller:
#RequestMapping(value={"/supply"}, method=RequestMethod.POST)
public String consumptFormulate(Locale locale, Model model, #ModelAttribute ConsumptionForm cmd, HttpServletRequest request){
String[] s_str =cmd.getFromDate().split("/");
String normal_s = s_str[2]+"-"+s_str[0]+"-"+s_str[1];
String[] f_str = cmd.getToDate().split("/");
String normal_f = f_str[2]+"-"+f_str[0]+"-"+f_str[1];
List<Good> list = service.getGoods(normal_s,normal_f,cmd.getSocGoods(),cmd.getTradeObj());
List<ListGoodsForm> listg = new ArrayList<ListGoodsForm>();
org.jfree.data.xy.XYSeries series = new org.jfree.data.xy.XYSeries("За месяц:");
if(!list.isEmpty()){
lg=list;
ListGoodsForm listo = new ListGoodsForm();
java.util.Calendar ca = java.util.Calendar.getInstance();
for(Good g: list){
listo.setName(g.getName());
listo.setMeasure(g.getMeasure());
listo.setPrice(g.getPrice());
listo.setQuantity(g.getQuantity());
listg.add(listo);
java.util.Date date = g.getDates();
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("MMMM");
ca.setTime(date);
int in = ca.get(java.util.Calendar.MONTH);
String month = format.format(date);
}
}
request.setAttribute("listGood",listg);
//model.addAttribute("listGood", listg);
model.addAttribute("GOODS", prepareDataList());
// model.add
model.addAttribute("COMPANY",sservice.getSupplierName());
model.addAttribute("consumptionForm", cmd);
return "supply";
}
My guess is that your controller is doing the following:
Good g = new Good();
List<Good> goods = new ArrayList<Good>();
for (int i = 0; i < 4; i++) {
g.setName("a");
...
goods.add(g);
}
This means that you're modifying the same Good object 4 tilmes, and adding it 4 times to the list. In the end, your have 4 times the same object, containing the state you set into it in the last iteration.
Instead, do this:
List<Good> goods = new ArrayList<Good>();
for (int i = 0; i < 4; i++) {
Good g = new Good();
g.setName("a");
...
goods.add(g);
}
EDIT : and your edited question just confirmed my guess:
ListGoodsForm listo = new ListGoodsForm();
this line should be inside the for loop, and not outside.
use this code to pass list
request.setAttribute("listGood",listg);
Related
I'm trying to display the contents of a List<> of objects that are linked to the currently logged in user on a jsp page. The object is successfully created and stored in the database with a user_id of the user who created it, and with a simple system.out.print debugger I can see its added to the List.
But when I try to display this on the NewFile.jsp webpage its as if the the List is empty. There is no error, instead the page is just blank as if there is no List to iterate through.
Skill method in UserController
#RequestMapping(value = "/skill", method = RequestMethod.POST)
public String skill(#ModelAttribute("skillForm") Skill skillForm, BindingResult bindingResult, Model model, Principal principal) {
skillValidator.validate(skillForm, bindingResult);
if (bindingResult.hasErrors()) {
return "skill";
}
// Adds skill object to database and adding it to Users skill list
String name = principal.getName();
skillService.save(skillForm, name);
User currentUser = userService.findByUsername(principal.getName());
currentUser.addSkill(skillForm);
// Debug here shows that the list contains correct data and the list size
System.out.println(skillForm.getSkillName());
System.out.println(skillForm.getCategory());
System.out.println(currentUser.getSkills().size());
// Attempting to pass the list to NewFile.jsp to be displayed
List<Skill> savedSkills = currentUser.getSkills();
for(int i = 0; i < savedSkills.size(); i++) {
model.addAttribute("skills", savedSkills);
/*model.addAttribute("currentUser", currentUser);*/
}
return "NewFile";
}
NewFile.jsp
<table>
<c:forEach var="o" items="${savedSkills}" >
<tr>
<td>Skill Name:<c:out value = "${o.skillName}"/></td>
<td>Category:<c:out value = "${o.category}"/> </td>
</tr>
</c:forEach>
</table>
There are some mistakes. First you don't need a loop.
List<Skill> savedSkills = currentUser.getSkills();
model.addAttribute("skills", savedSkills);
Second, your EL has the wrong argument name, just like the others had stated.
<c:forEach var="o" items="${skills}" >
You need to specify what skill to be added , you are adding the List as an attribute but you need to the object that's inside it
for(int i = 0; i < savedSkills.size(); i++) {
model.addAttribute("skills", savedSkills[i]);
/*model.addAttribute("currentUser", currentUser);*/
}
Try by adding the code model.addAttribute("savedSkills", savedSkills); before the return statement. You haven't add the model attribute named with "savedSkills".
I have an legacy structure I need to use to render a matrix (or grid) using thymeleaf in a Springboot project.
I have several models to represent it with additional info.
public class CeldaGrid {
private int valor;
//Removed additional fields
//Constructor
//Getters/Setter
public class MiGrid {
//Represent each column of the matrix
private Collection<CeldaGrid> celdaGridList;
//Constructor
//Getter/Setter
public class ContenedorGrid {
//Represent the matrix
private Collection<MiGrid> gridList = new ArrayList<MiGrid>();
//Constructor
//Getter/Setter
This is how I initialze, in this case is 3x3 matrix (it could be different size):
Collection<MiGrid> gridList = new ArrayList<MiGrid>();
// Row 1
MiGrid miGrid = new MiGrid();
Collection<CeldaGrid> celdaGridList = new ArrayList<CeldaGrid>();
CeldaGrid celdaGrid = new CeldaGrid();
celdaGrid.setValor(1);
celdaGridList.add(celdaGrid);
celdaGrid = new CeldaGrid();
celdaGrid.setValor(2);
celdaGridList.add(celdaGrid);
celdaGrid = new CeldaGrid();
celdaGrid.setValor(3);
celdaGridList.add(celdaGrid);
miGrid.setCeldaGridList(celdaGridList);
gridList.add(miGrid);
// Row 2
miGrid = new MiGrid();
celdaGridList = new ArrayList<CeldaGrid>();
celdaGrid = new CeldaGrid();
celdaGrid.setValor(4);
celdaGridList.add(celdaGrid);
celdaGrid = new CeldaGrid();
celdaGrid.setValor(5);
celdaGridList.add(celdaGrid);
celdaGrid = new CeldaGrid();
celdaGrid.setValor(6);
celdaGridList.add(celdaGrid);
miGrid.setCeldaGridList(celdaGridList);
gridList.add(miGrid);
ContenedorGrid contenedorGrid = new ContenedorGrid();
contenedorGrid.setGridList(gridList);
model.addAttribute("contenedorgrid", contenedorGrid);
and finally the page:
<form action="#" th:action="#{/}" th:object="${contenedorgrid}" method="post">
<table>
<tbody>
<tr th:each="eachCelda,indexList : *{gridList}">
<td th:each="celda,indexCelda: ${eachCelda.celdaGridList}">
<input type="text" th:id="${celda.valor}"
th:field="*{celdaGridList[__${indexCelda.index}__].valor}"/>
</td>
</tr>
</tbody>
</table>
</form>
This is the list with values:
[MiGrid [celdaGridList=[CeldaGrid [valor=1], CeldaGrid [valor=2], CeldaGrid [valor=3]]], MiGrid [celdaGridList=[CeldaGrid [valor=4], CeldaGrid [valor=5], CeldaGrid [valor=6]]]]
And this is the error:
org.springframework.beans.NotReadablePropertyException: Invalid
property 'celdaGridList[0]' of bean class
[org.cabildo.gestatur.model.grid.ContenedorGrid]: Bean property
'celdaGridList[0]' is not readable or has an invalid getter method:
Does the return type of the getter match the parameter type of the
setter?
Code:
https://www.dropbox.com/sh/ppyf3f0l6p3v2ig/AABjXsS_6Mu2nmKd-XBRTclua?dl=0
UPDATE 1:
Changed code from Collection to List, exactly the same error.
Any suggestion?
Thanks
You should change type of field celdaGridList to List<CeldaGrid> inside MiGrid class.
Collection isn't ordered and it has no method get(int index) so value from specific index can not be fetched. But you are trying to do so with the line th:field="*{celdaGridList[__${indexCelda.index}__].valor}
, what results in exception.
Update
I've looked closer at your page.
You've declared an object th:object="${contenedorgrid}" which is of type ContenedorGrid. Then you've used an asterix selector th:field="*{celdaGridList[__${indexCelda.index}__].valor}" on this object what is equivalent to th:field="${contenedorgrid.celdaGridList[__${indexCelda.index}__].valor}" what is obviously wrong because it misses gridList.
Please update th:field attribute within your <input> with the following code:
th:field="*{gridList[__${indexList.index}__].celdaGridList[__${indexCelda.index}__].valor}"
i have a problem whith the displaying of an arraylist in jsp. it displays everything in one line for each person making repetition .
i have a table with columns (phone number,fax,phone2,email)
here is my dao function:
#Override
public ArrayList<String> moyenCom(Authentication auth) {
String login=auth.getName();
List list;
List listres = null;
ArrayList<String> array1=new ArrayList<String>();
//ArrayList<ArrayList<String>> array=new ArrayList<ArrayList<String>>();
SessionFactory factory=new Configuration().configure().buildSessionFactory();
Session session=factory.openSession();
session.beginTransaction();
//Your operation
String sql1="select r.id_responsable from WEBCARE.PERSONNE p,WEBCARE.RESPONSABLE r,WBB_CLU.ABONNE_COMPTE ac,WBB_CLU.COMPTE_CLU c where p.id=r.id_responsable and r.id_abonne=ac.id_abonne and c.id_compte=ac.id_compte and c.login=:x";
SQLQuery query1 = session.createSQLQuery(sql1);
query1.setParameter("x",login);
query1.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
session.getTransaction().commit();
list=query1.list();
for(int i=0;i<list.size();i++){
String res =list.get(i).toString();
String[] parts = res.split("=");
String part2 = parts[1];
System.out.println("id du responsable est"+res);
System.out.println("id du responsable spliteeee est "+part2);
session.beginTransaction();
String sql="select mc.information from WEBCARE.MOYEN_COMMUNICATION mc,WEBCARE.PERSONNE p where p.id=mc.id_categorie and mc.id_categorie=:part2 and mc.categorie=1";
SQLQuery query = session.createSQLQuery(sql);
query.setParameter("part2",part2);
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
session.getTransaction().commit();
listres=query.list();
for(int i1=0;i1<listres.size();i1++){
String resu =listres.get(i1).toString();
System.out.println("info "+resu);
array1.add(resu);
}
}
System.out.println(array1);
return array1;
}
my controller :
#RequestMapping("/fichets")
public String fichets(Model model,Authentication auth){
Authentication authen = SecurityContextHolder.getContext().getAuthentication();
String name = authen.getName(); //get logged in username
model.addAttribute("moycoms",metier.moyenCom(auth));
return "InfoAbonneTS";
}
and my jsp page :
<c:forEach items="${resps}" var="resp">
<tr>
<td id="date">${resp.nom} ${resp.prenom}</td>
<td>${resp.poste}</td>
<td>${resp.password}</td>
<c:forEach items="${moycoms}" var="moycom">
<td>${moycom}</td>
</c:forEach>
</tr>
</tbody>
</c:forEach>
The function returns the field information witch contains all the 4 informations that should be displayed each in every column.
arraylist returned is :
{information=01234567890}, {information=01999999999}, {information=0199999333}, {information=resp1#gmail.com}, {information=00 }, {information=0622355114}, {information=0588888888}, {information=respons3#gmail.com}, {information=00 }, {information=0111111111}, {information=0666666666}, {information=responsable4#gmail.com}
so the first four information should be displayed each in every column ,the second four same thing...in this example i have 3 persons.
i can't display this correctly any help?
resps is for displaying the first 3 columns
Looking at the data it looks like a List of Map. Try this code
<c:forEach items="${moycoms}" var="moycom" varStatus="stat">
<c:if test="${stat.index%4==0 && stat.index!=0}">
<tr>
</c:if>
<td>${moycom['information']}</td>
<c:if test="${stat.index%4==0 && stat.index!=0}">
</tr>
</c:if>
</c:forEach>
stat variable is used to find the current index. We are adding the <tr> based on the index so that its done for every fourth index. If resp contains some identifier which could be used for finding the correct user then use <c:if> for matching. Please provide additional information
you are adding only "moycoms" attribute to the model object
but you jstl starts from
<c:forEach items="${resps}" var="resp">
you are not adding any "resps" param in your model object
Hi I am trying to implement Add To Cart Mechanism in my web Application.
So that's why temporary i have created 3 JSP pages that implement such mechanism. But it is not working properly.
I have also created session uniquely for to identify specific user session but it is not actually implemented in all page.
Following Is My Code :
test.jsp
<%
Random rkey = new Random();
int randomkey = Math.abs(rkey.nextInt());
String sdata = "keyur"+randomkey;
DateFormat dateFormat = new SimpleDateFormat("HHmmss");
Calendar cal = Calendar.getInstance();
String sess = "keyur"+randomkey+dateFormat.format(cal.getTime());
session.setAttribute("KEYUR", sess);
%>
<% response.sendRedirect("test1.jsp"); %>
test1.jsp
Hello <%= session.getAttribute("KEYUR")%>
<%
String a="shirt",b="jeans";
int a1 = 10,b1=20;
Double a2=100.00,b2=200.00;
%>
<br><br>
A : Add To Cart<br><br>
A1 : Add To Cart
test2.jsp
Hello <%= session.getAttribute("KEYUR")%><br><br><br><br>
Your Cart :
<%
List<String> pname = new ArrayList<String>();
List<Integer> pqty = new ArrayList<Integer>();
List<Double> ppr = new ArrayList<Double>();
%>
<%
pname.add(request.getParameter("item"));
pqty.add(Integer.parseInt(request.getParameter("qty")));
ppr.add(Double.parseDouble(request.getParameter("price")));
Double total=0.00;
%>
<br><br>
<%
for(int i = 0;i < pname.size();i++)
{
String name = pname.get(i);
Integer qty1 = pqty.get(i);
Double pr1 = ppr.get(i);
%>
Name : <%= name %><br>
Qty : <%= qty1 %><br>
Price : <%= pr1 %><br><br>
Total : <%= total += qty1*pr1 %>
<%
}
%>
Right now i have taken static data, if it will work then I'll try it with dynamic data.
Anyone tell me why only one item display in cart.
Suppose user click on Add To Cart then it redirect to test2.jsp and again back to test1.jsp then click on second add to cart then cart should be appended not overwrite.
But currently it is overwriting.
Any Suggestion Please...
test2.jsp
List<String> pname = new ArrayList<String>(); //size is 0
...
pname.add(request.getParameter("item")); //size is 1
That's why you get just one item.
By the way, make your self a favour, don't use JSP scriptlets; use JSTL or write your own tags (look for Java Custom tags)
This procudure looking very Bad codding for store a cart items...
But still you can store as many you want in List
In your page when every time a Test2.jsp called the new keywprd initilize a new cart lists..
thats why previous value get losts....
instead of this code
<%
List<String> pname = new ArrayList<String>()
List<Integer> pqty = new ArrayList<Integer>();
List<Double> ppr = new ArrayList<Double>();
%>
use deceleration block for decleration
<%!
List<String> pname = new ArrayList<String>();
List<Integer> pqty = new ArrayList<Integer>();
List<Double> ppr = new ArrayList<Double>();
%>
after that you can store as many you want ....But there will be possible some duplicate values...to remove duplicate you can use Set at the place of List
I think you have got your query's answer.....
The reason why only one item is displayed is because you are inserting only one item in Lists pname, pqty, ppr.
Use a for loop in-order to insert. So that it contains multiple orders or items..
Hope it will help.
I am new to JSP and servlet for 1 month, and there are many things that I am still unsure off.. Inside a JSP, I have a dropdownlist(the values inside are grab from database) and it would be dynamically created on the number that the user keyed in. Example, the user key in 3, this digit would store in session, and 3 dropdownlist would be generated.
I am able to do this, however I am unable to grab the value of all the 3 dropdownlist in a servlet. and instead of getting 3 diff values, the output repeat the value of the first dropdownlist. Example "john,john,john" instead of "john, ken, andy".
JSP code:
<form action="Adding" method="post">
<%
session = request.getSession();
ProjectGroup projGrp1 = (ProjectGroup)session.getAttribute("PROJECTNAME");
//getMaxMember is the int that user keyed in
int staff =projGrp1.getMaxMember();
for(int i = 0; i < staff; i++) {
%>
<select name="list1" >
<%#page import="sit.bean.*,sit.data.*"%>
<%
GroupTaskManager mgr3 = new GroupTaskManager();
GroupTask[] at3 = mgr3.getCheckBox();
for(int g = 0; g < at3.length; g++) {
%>
<option><%=at3[g].getStaffName()%></option>
<%
}
%>
</select>
<%
}
%>
<input type="submit" name="submit">
</form>
In servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
ProjectGroup projGrp = (ProjectGroup)session.getAttribute("PROJECTNAME");
int member = projGrp.getMaxMember();
String total = null;
for(int i=0; i< member; i++)
{
String names = request.getParameter("list1");
total += names + " , ";
}
PrintWriter pw = response.getWriter();
pw.write("<HTML><BODY>");
pw.write(total);
pw.write("</HTML></BODY>");
pw.close();
}
Can i set the downdownlist name like "list<%i%>", to set different id to each downdownlist? therefore i can retrieve each of them seperately???
In servlet you are getting same parameter every time which is list1 in loop.
and also in JSP creating dropdownlist with same name attribute,
that's why you are getting john,john,john instead of john, ken, andy.
Yes you can use list<%i%> to set different id as well as name
change your select with below in JSP
<select name="list<%=i%>" >
and for loop in servlet with below
for(int i=0; i< member; i++)
{
String names = request.getParameter("list1"+i);
total += names + " , ";
}