Why isn't my List<Object> displaying on my webpage? - java

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

Related

Populating Thymeleaf rows, with one of column referenced to another table(Database).Need another column of referenced Table to display

I am beginner with springboot. I came across a situation.Ok, let me give table structure before I explain.
Expenses
expensesId, categories,
Categories
categoryId, categoryname
Expenses table is referring to category table with categoryId.
I am able to populate datatable with expensesList that was sent from a controller to view successfully. But my problem is I get columnid in populated but I wish to populate that column with categoryname instead. I thought for possible solutions for some time and I come up with stupid Idea using If the condition in thymeleaf of mapping categoryId with categoryName but I don't wish to go for that part as I can have more categories growing in future and code is difficult to maintain.
I could really use some help on this.
Link to git project
expensespage link
expenses controller link
Please do provide links if a solution is already available which I missed during my google search on this issue.
Apologies for bad english for Title part as I cannot squeeze question further.
I just added category object containing Id and name to every expenses object in
Expenses Object List and passed to controller. Now I can directly use CategoryName in View with Thymeleaf as follows
<td th:text="${expense.categories.categoryname}"></td>>
What I changed in controller.
Before
#RequestMapping(value = "/expenses")
public String toExpensesPage(Model model) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = monitorService.getUserByUserName(authentication.getName()).get(0);
List<Categories> categoriesList = monitorService.getAllCategories();
model.addAttribute("expenses",new Expenses());
if(categoriesList != null) {
model.addAttribute("categories",categoriesList);
}
List<Expenses> expensesList = monitorService.getAllExpensesActive(user.getUserid());
model.addAttribute("expensesList",expensesList);
return "common/expensespage";
}
To.
#RequestMapping(value = "/expenses")
public String toExpensesPage(Model model) {
Map<Integer,String> categoryMap = new HashMap<Integer, String>();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = monitorService.getUserByUserName(authentication.getName()).get(0);
/* getting Category List This contains both categoryId and categoryname */
List<Categories> categoriesList = monitorService.getAllCategories();
/* Using hashmap to map id to name so we dont need to iterate categoryList or call to database with category Id..*/
for(int i = 0; i < categoriesList.size();i++){
categoryMap.put(categoriesList.get(i).getCategoryid(),
categoriesList.get(i).getCategoryname());
}
model.addAttribute("expenses",new Expenses());
if(categoriesList != null) {
model.addAttribute("categories",categoriesList);
}
List<Expenses> expensesList = monitorService.getAllExpensesActive(user.getUserid());
/*Assigning category object to expenses object*/
for(int i = 0; i < expensesList.size();i++){
Categories categories = new Categories();
categories.setCategoryid(expensesList.get(i).getCategories().getCategoryid());
categories.setCategoryname(categoryMap.get(expensesList.get(i).getCategories().getCategoryid()));
expensesList.get(i).setCategories(categories);
}
model.addAttribute("expensesList",expensesList);
return "common/expensespage";
}
Added Comment's inside code on how I did. Hope someone find it helpful.

Spring MVC displaying arraylist in JSP correctly

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

Getting value from dynamically created inputText box in forEach section

I am trying to do something very similar to this Getting value from dynamically created inputText and i have some difficulties that is why i will ask my question here, hope you can help me. I want to bind dynamically generated input box with Object. I have:
<c:forEach items="${filterTypeBean.listTextFilterTypes()}"
var="inputBoxes">
<h:outputText value="${inputBoxes.filterTypeName}"
style="width: 100px; white-space: normal; border: 3px" />
<h:inputText value="${requestBean.filterTypeValue}" />
</c:forEach>
In the request bean for filterTypeValue i have:
private String filterTypeValue;
public String getFilterTypeValue() {
return filterTypeValue;
}
public void setFilterTypeValue(String filterTypeValue) {
this.filterTypeValue = filterTypeValue;
}
My issues come from the fact that i have three entities - TRequest, TRequestFilter, TFilter. TRequestFilter is a mapping table, where i have TREQUEST, TFILTER and the value which i want to take and insert in DB from the inputbox latter.
filterTypeBean.listTextFilterTypes() i take from FilterTypeBean:
public List<TFilterType> listTextFilterTypes() {
EntityManager em = HibernateUtil.getEntityManager();
Query q = em.createQuery("select u from TFilterType u where u.filterType like 'T'");
List<TFilterType> resultList = q.getResultList();
return resultList;
}
I want to set the value of inputbox in RequestBean because first i insert a new Request in the DB, and after that i want to insert the filters for this new Request in TRequestFilter table (the reason i need TFilter and the inserted value for it).
Thanks a lot for the help!
I managed to make it working with mapping in my bean class:
private Map<TFilterType, Object> values = new HashMap<TFilterType, Object>();
public Map<TFilterType, Object> getValues() {
return values;
}
and iterator:
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
if (pairs.getValue() != null) {
System.out.println(pairs.getKey() + '='+ pairs.getValue());
}
it.remove(); // avoids a ConcurrentModificationException
}
in this way i have and Object and its value and i am able to insert a record in a new Entity in the database.

How to change list(select) data dynamically

I am adding product details.
So for that with it I have to add product attribute, product feature with it.
I am loading all data of attribute from mysql table.
I am using one mechanism that first user have to select attribute category from list (select control), when user select category then as per it data of other list (select control) changes.
main category image :
sub attribute category :
I have added data like this in JavaScript array :
var at_category_id = [];
var at_category_name = [];
<%
List<Integer> aIDList = (List<Integer>) request.getAttribute("aID");
List<String> aNAMEList = (List<String>) request.getAttribute("aNAME");
for (int i = 0; i < aIDList.size(); i++)
{
%>
at_category_id.push(<%= aIDList.get(i) %>);
at_category_name.push(<%= aNAMEList.get(i) %>);
<%
}
%>
var option_str = document.getElementById('list_main_category');
for (var i=0; i<at_category_id.length; i++)
{
option_str.options[option_str.length] = new Option(at_category_id[i],at_category_name[i]);
}
I have done same like this for attribute and add data to JavaScript array.
var at_id = [];
var at_name = [];
<%
List<Integer> acIDList = (List<Integer>) request.getAttribute("acID");
List<String> acNAMEList = (List<String>) request.getAttribute("acNAME");
for (int i = 0; i < aIDList.size(); i++)
{
%>
at_id.push(<%= acIDList.get(i) %>);
at_name.push(<%= acNAMEList.get(i) %>);
<%
}
%>
but now how to move forward I don't know.
I want to do something like that.
Means when user click on first list that is main category how second list will be changed ?
any suggestion please.
The usual way would be to put a javascript action on the value changing for the first combo box.
At that point you can either (easy way) submit the whole form and then send back the new page with the extra value added or (slightly more complex) do an AJAX call to fetch the data and populate the new dropdown.

Play Framework 2.0 form helper: from checkbox to List<String>

I have a model that contains a String and a list:
public String title;
public List<String> topics;
In index.scala.html I use a form to add new items:
#form(routes.Application.newPaper()) {
#inputText(paperForm("title"))
<input type="submit" value="Create">
}
with a simple String, this works nicely. But I would like to show checkboxes
#for(t <- topics) {
<input type='checkbox' name='topic' value=#t>#t <br>
}
and subsequently add all checked 'topics' to the List<String> topics; of my new item. How can I process the checkboxes within #form{ ... }?
I am using Play!Framework 2.1.0, below is the solution :
1. In the scala template, you must give all checkbox name like this:
#form(action = routes.Application.newPaper()) {
#inputText(paperForm("title"))
#******* Indexed chekbox name *********#
#for((t, index) <- topics.zipWithIndex) {
<input type="checkbox" name="topics[#index]" value="#t">#t <br>
}
<input type="submit" value="Create">
}
2. Then in your controller, as an action to handle form submit, you should doing something like this :
public static Result newPaper() {
// Bind submitted form value to your model, ex. Paper.java
Form<Paper> paperForm = Form.form(Paper.class).bindFromRequest();
Paper paper = paperForm.get();
Logger.info("Title entered = " + paper.title);
// Because in template we use indexed name, unchecked item are binded with null value
paper.topics.removeAll(Collections.singleton(null)); // remove value for unchecked topic
for (String t : paper.topics) {
Logger.info("The topic is " + t);
}
Logger.info("Total topic selected = " + paper.topics.size());
return redirect(routes.Application.index()); // redirect page
}
UPDATE
This is another idea to the solution. Your checkbox code on scala template is not modified.
#for(t <- topics) {
<input type='checkbox' name='topic' value=#t>#t <br>
}
So the controller should be like this :
public static Result newPaper() {
// Bind submitted form value to your model, ex. Paper.java
Form<Paper> paperForm = Form.form(Paper.class).bindFromRequest();
Paper paper = paperForm.get();
// get request value from submitted form
Map<String, String[]> map = request().body().asFormUrlEncoded();
String[] checkedVal = map.get("topic"); // get selected topics
// assign checked value to model
paper.topics = Arrays.asList(checkedVal);
// for debugging purpose
for (String t : paper.topics) {
Logger.info("The topic is " + t);
}
Logger.info("Total topic selected = " + paper.topics.size());
return redirect(routes.Application.index()); // redirect page
}
Hope this idea is more elegant.. :)
Note: I have tested on Play!Framework 2.1.1 too, and that is work for me.

Categories

Resources