Why iterate last data from ArrayList<>? - spring-mvc

I get data from database perfectly and pass to the Thymeleaf(Template), but the problem is near mdl.addAttribute("number" ,request.getNumber()) in controller to detect last value from foreach loop iteration and send by model
Here down my code:
Dto
public interface ProfileDto {
public Integer getU_id();
public Integer getP_id();
public String getEmail();
public String getUsername();
public String getPassword();
public String getContact();
public String getDate();
public String getProfile();
public String getWebsite();
public String getBio();
public String getGender();
public String getPost();
}
Entity
#Entity
#Table(name = "request_master")
public class Request {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int req_id;
private int sender_id;
private int receiver_id;
private String status;
private String date;
#Transient
private int number;
// getter setter
}
Repository
public interface profileRepo extends JpaRepository<Request, Integer> {
#Query(nativeQuery = true, value = "SELECT * FROM registration_master rm INNER JOIN profile_master pm ON rm.u_id = pm.user_id WHERE rm.u_id != ?")
List<ProfileDto> findByIdUser(Integer Id);
public interface requestRepo extends JpaRepository<Request, Integer> {
#Query(nativeQuery = true, value="SELECT * FROM request_master WHERE sender_id = ? and receiver_id = ?")
List<Request> getSuggetionButton(Integer Sender_id, Integer Receiver_id);
}
Service
#Service
public class ServiceImpl implements Service {
#Autowired
private profileRepo profileRepo;
#Autowired
private requestRepo requestRepo;
#Override
public List<ProfileDto> getSuggestedList(Integer Id) {
return this.profileRepo.findByIdUser(Id);
}
#Override
public List<Request> getSuggestionButton(Integer Sender_id, Integer Receiver_id) {
return this.requestRepo.getSuggetionButton(Sender_id, Receiver_id);
}
}
Controller
#Controller
public class Controller {
#Autowired
private Service service;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Model mdl, Request request) {
int SessionId = Integer.parseInt(session.getAttribute("uid").toString());
List<ProfileDto> Suggestion_list = service.getSuggestedList(SessionId);
for(ProfileDto Suggestion_id : Suggestion_list)
{
List<Request> Friend_request = this.service.getSuggestionButton(SessionId, Suggestion_id.getU_id());
if(Friend_request.size() > 0)
{
request.setNumber(Friend_request.size());
}
else
{
request.setNumber(0);
}
}
mdl.addAttribute("number" ,request.getNumber());
mdl.addAttribute("suggestionList", Suggestion_list);
return "post";
}
}
Thymeleaf
<div class="follow-user-list" th:each="suggetionFriend : ${suggestionList}">
<div class="follow-user clearfix" th:id="'follow-user'+${suggetionFriend.u_id}">
<img th:src="${suggetionFriend.profile}" alt="" class="profile-photo-sm pull-left" />
<div class="name clearfix">
<h5>
</h5>
<div class='follow-unfollow-btn' th:id="'follow-unfollow-button'+${suggetionFriend.u_id}">
<div th:text="${number}">
</div>
</div>
</div>
</div>
</div>
in below image 1 is for condition matched and find data and 0 is for condition not matched and not find data
In My output i can get only last iterate data in both user
Output:
Expected output:
I think problem is to pass data from controller to thymeleaf
If you have good idea to transfer value from Controller to Template tell me please

You should maintain request for each profile/user instead of having single request, what I mean by that is you should have number of request for each profileId/userId, you can maintain a map of profileId/userId and number of request for that profile/user, and use that map in your template, try to modify your code as below
Controller
#Controller
public class Controller {
#Autowired
private Service service;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Model mdl, Request request) {
Map<Integer, Integer> profileToNoOfRequestMap = new HashMap<>();
int SessionId = Integer.parseInt(session.getAttribute("uid").toString());
List<ProfileDto> Suggestion_list = service.getSuggestedList(SessionId);
for(ProfileDto Suggestion_id : Suggestion_list)
{
List<Request> Friend_request = this.service.getSuggestionButton(SessionId, Suggestion_id.getU_id());
profileToNoOfRequestMap.put(Suggestion_id.getU_id(), Friend_request.size());
}
mdl.addAttribute("profileToNoOfRequestMap", profileToNoOfRequestMap);
mdl.addAttribute("suggestionList", Suggestion_list);
return "post";
}
}
Thymeleaf
<div class="follow-user-list" th:each="suggetionFriend : ${suggestionList}">
<div class="follow-user clearfix" th:id="'follow-user'+${suggetionFriend.u_id}">
<img th:src="${suggetionFriend.profile}" alt="" class="profile-photo-sm pull-left" />
<div class="name clearfix">
<h5>
</h5>
<div class='follow-unfollow-btn' th:id="'follow-unfollow-button'+${suggetionFriend.u_id}">
<div th:text="${profileToNoOfRequestMap.get(suggetionFriend.u_id)}">
</div>
</div>
</div>
</div>
</div>

Related

How to use OneToMany Association in more than one table

I am trying to join three tables with my model class.Here is my model classes.
Users.java
#Entity
#Table(name = "users")
public class Users implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
public String username;
public String password;
public Integer privid;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "pid")
private Set<Privillages> priviJoin;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "actid")
private Set<Actions> actionJoin;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name = "privid")
public Integer getPrivid() {
return privid;
}
public void setPrivid(Integer privid) {
this.privid = privid;
}
public Set<Privillages> getPriviJoin() {
return priviJoin;
}
public void setPriviJoin(Set<Privillages> priviJoin) {
this.priviJoin = priviJoin;
}
public Set<Actions> getActionJoin() {
return actionJoin;
}
public void setActionJoin(Set<Actions> actionJoin) {
this.actionJoin = actionJoin;
}
public Users() {
}
}
And Privillages.java,
#Entity
#Table(name = "privillages")
public class Privillages implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Integer id;
#Column(name = "pname")
public String pname;
#ManyToOne(optional = false)
#JoinColumn(name = "pid", referencedColumnName = "privid")
public Users pid;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Users getPid() {
return pid;
}
public void setPid(Users pid) {
this.pid = pid;
}
public Privillages(){
}
}
And Actions.java
#Entity
#Table(name = "actions")
public class Actions implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Integer id;
#Column(name = "actname")
public String actname;
#ManyToOne(optional = false)
#JoinColumn(name = "actid", referencedColumnName = "privid")
public Users actid;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getActname() {
return actname;
}
public void setActname(String actname) {
this.actname = actname;
}
public Users getActid() {
return actid;
}
public void setActid(Users actid) {
this.actid = actid;
}
public Actions(){
}
}
My repository containing following code,
#Query(value = "SELECT u.*,p.*,a.* FROM users u "
+ "INNER JOIN privillages p ON u.privid = p.pid "
+ "INNER JOIN actions a ON u.privid = a.actid",
nativeQuery=true)
Set<Users> findByUsername();
My controller action is,
#RequestMapping(value = "/joinResult", method = RequestMethod.GET)
public ModelAndView joinResultShow(Model model)
{
model.addAttribute("joinData",userRepo.findByUsername());
ModelAndView viewObj = new ModelAndView("fleethome");
return viewObj;
}
And my view fleethome is like,
<table>
<th> Username </th>
<th> Privillage </th>
<th> Action </th>
<tr th:each="message : ${joinData}">
<td th:text="${message.username}"></td>
<td><span th:each="privi : ${message.priviJoin}"
th:text="${privi.pname}"></span></td>
<td><span th:each="action : ${message.actionJoin}"
th:text="${action.actname}"></span></td>
</tr>
</table>
I am trying to join Privillages and Actions with my main model Users. Users-Privillages have one to many. And also Users - Actions also have one to many. When I joined Users with Privillages it working good. I successfully joined two table.
Now I also need to join Actions class with Users. I am trying to displaying one column from each Model classes. When I implemented the procedure that I follow previously for joining Users-Privillages is not working here, when I added one more table.
I am getting the error like,
There was an unexpected error (type=Internal Server Error, status=500).
Exception evaluating SpringEL expression: "message.pname" (fleethome:65)
How can I join the additional one table with my previous join?
You probably can't do that without model entity changes.
If i got you right, you want to get your entity class with multiple related collections initialized from db. But this can't work as is in your case because MultipleBagFetchException: cannot simultaneously fetch multiple bags. It is basically the same problem of multiple collections with fetch = FetchType.EAGER. Easy fix would be to change Collection<Privillages> to Set<Privillages> or same for Actions if you can.
More info
As for Exception evaluating SpringEL expression: "message.pid.username" the actual reason is that you are trying to work with joinData as if it is some database table record, but instead you should work with it like you would with java classes. Because you already got Set<User> joinData from hibernate. Can try something like
<tr th:each="message : ${joinData}">
<td th:text="${message.username}"></td>
<td><span th:each="privi : ${message.priviJoin}"
th:text="${privi.pname}"></span></td>
<td><span th:each="action : ${message.actionJoin}"
th:text="${action.actname}"></span></td>
</tr>
If you want same output like in the image you provided, you can try:
<div th:remove="tag" th:each="message : ${joinData}">
<div th:remove="tag" th:each="privi : ${message.priviJoin}">
<div th:remove="tag" th:each="action : ${message.actionJoin}">
<tr>
<td th:text="${message.username}"></td>
<td th:text="${privi.pname}"></td>
<td th:text="${action.actname}"></td>
</tr>
</div>
</div>
</div>

Checkbox with Thymeleaf and custom List Object in Spring MVC (Boot)

I am using Thymeleaf with Spring Boot and MVC. What I have is a form in which certain checkboxes are being populated with an object(q1) added into the model from the controller
What I want to know is that how can I bind the selected checkboxes with my resulting object(surveyData) into a list of (complex) objects using Thymeleaf properly.
Edit
Also this is the first time I'm working on this combination of Spring Boot, Spring MVC, Spring JPA and entirely the first time I have used Thymeleaf. I'm not exactly sure where the problem may be. I did try debugging a lot but was unable to figure out where the problem is exactly. I tried various different combinations to get this working and got various different outcomes(mostly exceptions of course). It would be difficult for me to post all of them here so if you can suggest something I would love to try it out and post its result.
What I have till now: (The th:field for checkbox is obviously not working)
Code:
HTML Snippet:
<form action="#" th:action="#{/controlleraction}" method="post" th:object="${surveyData}">
<table class="table table-striped jambo_table bulk_action" id="table-resp">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr th:each="act,iter : ${q1}">
<td>
<input type="checkbox" class="check" th:value="${act.optionId}" th:field="*{keyResponsibilities.optionId.optionId}" />
</td>
</tbody>
</table>
</form>
SurveyData.java
#Entity
#Table(name = "survey_data")
public class SurveyData implements Serializable{
#Id
#Column(name = "some_id")
private Long someId;
#ElementCollection
#CollectionTable(name = "key_responsibilities", joinColumns = #JoinColumn(name = "data_id"))
private List<KeyResponsibilities> keyResponsibilities = new ArrayList<>();
public List<KeyResponsibilities> getKeyResponsibilities() {
return keyResponsibilities;
}
public void setKeyResponsibilities(List<KeyResponsibilities> keyResponsibilities) {
this.keyResponsibilities = keyResponsibilities;
}
}
KeyResponsibilities.java
#Embeddable
public class KeyResponsibilities {
#OneToOne
#JoinColumn(name = "option_id")
private OptionsMaster optionId;
#Column(name = "other")
private String other;
public OptionsMaster getOptionId() {
return optionId;
}
public void setOptionId(OptionsMaster optionId) {
this.optionId = optionId;
}
public String getOther() {
return other;
}
public void setOther(String other) {
this.other = other;
}
}
OptionsMaster.java
#Entity
#Table(name = "options_master")
public class OptionsMaster implements Comparable<OptionsMaster> {
private int optionId;
private String text;
#Id
#Column(name = "option_id")
public int getOptionId() {
return optionId;
}
public void setOptionId(int optionId) {
this.optionId = optionId;
}
#Basic
#Column(name = "text", length = -1)
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
#Override
public int compareTo(OptionsMaster o) {
return Integer.compare(this.getOptionId(),o.getOptionId());
}
}

Multiple select in thymeleaf + hibernate + spring boot

Hello guys I'm using thymeleaf 3 with spring boot and spring data jpa. But here is the problem. When I try to save I get this error from Hibernate:
Hibernate: insert into consulta (medico_id) values (?)
Hibernate: insert into consulta_pacientes (consulta_id, pacientes_id) values (?, ?)
2016-12-12 16:06:53.963 WARN 11912 --- [nio-9393-exec-9] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1364, SQLState: HY000
2016-12-12 16:06:53.963 ERROR 11912 --- [nio-9393-exec-9] o.h.engine.jdbc.spi.SqlExceptionHelper : Field 'pct_id' doesn't have a default value
2016-12-12 16:06:53.965 INFO 11912 --- [nio-9393-exec-9] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
2016-12-12 16:06:53.976 ERROR 11912 --- [nio-9393-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path
[] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not execute statement; nested exception is org.hibe
rnate.exception.GenericJDBCException: could not execute statement] with root cause
java.sql.SQLException: Field 'pct_id' doesn't have a default value
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:963) ~[mysql-connector-java-5.1.39.jar:5.1.39]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3966) ~[mysql-connector-java-5.1.39.jar:5.1.39]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3902) ~[mysql-connector-java-5.1.39.jar:5.1.39]
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2526) ~[mysql-connector-java-5.1.39.jar:5.1.39]
I already tried to use converter but didn't workout properly. Tried to look in this posts* ...but didn't solve either.
*1 http://forum.thymeleaf.org/th-selected-not-working-on-lt-select-gt-lt-option-gt-td4029201.html
*2
thymeleaf multiple selected on edit
Any tips? I'm kind of lost right now.
cadastro.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
...
<form action="#" th:action="#{salvar}" th:object="${consulta}" method="POST">
<div class="form-inline">
<label for="select-medico-consulta" class="form-group">Medico</label>
<select th:field="*{medico.id}" id="select-medico-consulta" >
<div>
<option th:each="medicoEntry : ${medicos}"
th:value="${medicoEntry.id}"
th:text="${medicoEntry.nome}"></option>
</div>
</select>
<div class="form-group">
<label id="paciente-label" for="select-paciente" > Paciente</label>
<select th:field="*{pacientes}" id="select-paciente" size="5" multiple="multiple" >
<div>
<option th:each="pacienteEntry : ${listaPacientes}"
th:field="*{pacientes}"
th:value="${pacienteEntry.id}"
th:text="${pacienteEntry.nome}"></option>
</div>
</select>
</div>
</div>
<div class="form-group">
<label for="comment">Consulta</label>
<textarea class="form-control" rows="5" id="comment"></textarea>
</div>
<button type="submit" class="btn btn-default">Salvar</button>
</form>
</div>
...
consultaController.java
package
and imports...
#Controller
#RequestMapping("/medclin")
public class ConsultaController {
#Autowired
private ConsultaDao consultadao;
#Autowired
private MedicoDao medicoDao;
#Autowired
private PacienteDao pacienteDao;
#RequestMapping("/consulta")
public ModelAndView Consulta() {
ModelAndView modelAndView = new ModelAndView("consulta/consulta");
ArrayList<Medico> medicos = (ArrayList<Medico>) medicoDao.findAll();
ArrayList<Paciente> pacientes = (ArrayList<Paciente>) pacienteDao.findAll();
modelAndView.addObject("medicos", medicos);
modelAndView.addObject("listaPacientes", pacientes);
modelAndView.addObject("consulta", new Consulta());
return modelAndView;
}
#RequestMapping(value = "/salvar", method = RequestMethod.POST)
public String salvar(#ModelAttribute Consulta consulta) {
consultadao.save(consulta);
return "redirect:medclin/home";
}
}
consultaDao.java
package br.com.medclin.boot.daos;
import java.io.Serializable;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import br.com.medclin.boot.models.Consulta;
#Repository
public interface ConsultaDao extends CrudRepository<Consulta , Integer>
{
}
EDIT:
as asked by #bphilipnyc
Paciente.java
#Entity
public class Paciente {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String nome;
private Calendar dataNascimento;
private String endereco;
#NotNull
private String cpf;
#ManyToOne
private Plano planoDeSaude;
public Paciente(String nome, Calendar dataNascimento, String endereco, String cpf, Plano plano) {
super();
this.nome = nome;
this.dataNascimento = dataNascimento;
this.endereco = endereco;
this.cpf = cpf;
this.planoDeSaude = plano;
}
public Paciente(String nome, Calendar dataNascimento, String endereco, String cpf) {
super();
this.nome = nome;
this.dataNascimento = dataNascimento;
this.endereco = endereco;
this.cpf = cpf;
}
public Paciente(String pctCpf) {
this.cpf = pctCpf;
}
public Paciente() {
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Calendar getDataNascimento() {
return this.dataNascimento;
}
public void setDataNascimento(Calendar dataNascimento) {
this.dataNascimento = dataNascimento;
}
public String getEndereco() {
return this.endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getCpf() {
return this.cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Plano getPlanoDeSaude() {
return planoDeSaude;
}
public void setPlanoDeSaude(Plano planoDeSaude) {
this.planoDeSaude = planoDeSaude;
}
public boolean equals(Paciente pct) {
if (this.id == pct.id)
return true;
else
return false;
}
#Override
public int hashCode() {
return super.hashCode();
}
#Override
public String toString() {
return "Paciente [id=" + id + ", nome=" + nome + ", dataNascimento=" + dataNascimento + ", endereco=" + endereco
+ ", cpf=" + cpf + ", planoDeSaude=" + planoDeSaude + "]";
}
}
The problem was solved. It seems that if you change your hibernate mapping, you must recreate the database. I did that and the problem was solved.

Spring HashMap Form

I am creating an application with Spring Roo for generate documents. First of all the user create a document:
public class Document {
#NotNull
private String titleDocument;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "relatedDocumentToThisDateField")
private Set<DateField> dateFields = new HashSet<DateField>();
#OneToMany(cascade = CascadeType.ALL, mappedBy = "relatedDocumentToThisRadioButton")
private Set<RadioButtonField> radioButtonFields = new HashSet<RadioButtonField>();
#OneToMany(cascade = CascadeType.ALL, mappedBy = "relatedDocumentToThisStringField")
private Set<StringField> stringFields = new HashSet<StringField>();
}
There are 3 types of fields, for simplify, this is StringField (the others are almost the same):
public class StringField extends Field {
#NotNull
private String valueString;
#NotNull
private Boolean isEditable;
#ManyToOne
private Document relatedDocumentToThisStringField;
#NotNull
private String nameStringField;
}
When the document with fields is created, another user has to fill it. Since I dont know how much fields the document will have I need to create a HashMap Form (I am following this tutorial)
My HashMap is:
public class DynamicForm {
private Map<String, String> dynamicMap=new HashMap<String, String>();
public Map<String, String> getDynamicMap() {
return dynamicMap;
}
public void setDynamicMap(Map<String, String> dynamicMap) {
this.dynamicMap = dynamicMap;
}
}
In my FillDocumentController I have:
#RequestMapping(value = "/{id}", params = "form", produces = "text/html")
public String updateForm(#PathVariable("id") Long id, Model uiModel) {
...
// Create DynamicForm Map
DynamicForm dynamicForm = new DynamicForm();
for (Field field : allFields) {
// Is StringField?
if (field.getClass().equals(StringField.class) == true) {
StringField stringField = (StringField) field;
if( stringField.getIsEditable() == true ) {
dynamicForm.getDynamicMap().put(stringField.getNameStringField(), stringField.getValueString() );
}
}
}
uiModel.addAttribute("dynamicForm", dynamicForm);
return "filldocuments/update";
}
This is the view:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<div
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:field="urn:jsptagdir:/WEB-INF/tags/form/fields"
xmlns:form="http://www.springframework.org/tags/form"
xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0">
<jsp:directive.page contentType="text/html;charset=UTF-8" />
<jsp:output omit-xml-declaration="yes" />
<form:form action="/DocumentGenerator/filldocuments/add" modelAttribute="dynamicForm" method="post">
<c:forEach items="${dynamicForm.dynamicMap}" var="element">
<input name="element['${element.key}']" value="${element.value}"/>
</c:forEach>
<input type="submit" value="Save" />
</form:form>
</div>
And this is the method that catch the modelAttribute:
#RequestMapping(value="/add", method = RequestMethod.POST, produces = "text/html")
public String update(#ModelAttribute(value="dynamicForm") DynamicForm dynamicForm, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
for( String key : dynamicForm.getDynamicMap().keySet() ) {
System.out.println("key="+key);
}
return "redirect:/filldocuments";
}
My problem is that dynamicForm is empty. There is another DynamicForm inside of uiModel and is empty too (I was in debug mode). Where is the data that the user fill?? I dont know what is wrong!!
My fault, the view has to be like that:
<c:forEach items="${dynamicForm.dynamicMap}" var="dynamicMap">
<input name="dynamicMap['${dynamicMap.key}']" value="${dynamicMap.value}"/>
</c:forEach>
So the error was use the variable element

JSF Managed Bean Method for actionListener does not have property?

I know this question is out there a lot, but after reading most of the answers and suggestions I believe I may have strayed from the proper path. Currently the error I am getting is the Following
/categorias.xhtml: The class 'Vista.CategoriaBean' does not have the property 'getcategoriaIDFromCat'.
Stack Trace
javax.el.ELException: /categorias.xhtml: The class 'Vista.CategoriaBean' does not have the property 'getcategoriaIDFromCat'.
I am checking back with JEE as I have not used it in over a year but do not recall how to resolve this error.
I am using JSF 2.2 and have a page given the following:
<ui:repeat value="#{categoriaBean.lista}" var="test">
<article class="row">
<div class="col col-md-12">
<img src="images/Category/#{test.categorianame}.jpg"
alt="#{test.categorianame}" class="img-thumbnail img-responsive img_left"/>
<h4>
<h:outputText value="#{test.categorianame}"/>
</h4>
<p>
<h:outputText value="#{test.categoriadesc}"/>
</p>
<h:form>
<p>
<h:commandButton action="negociosByCat.xhtml" immediate="true"
actionListener="#{categoriaBean.getcategoriaIDFromCat}"
class="btn btn-primary" role="button"
value="Ver #{test.categorianame}"/>
</p>
</h:form>
</div>
</article>
</ui:repeat>
And where the Managed bean is (sorry for the whole class being pasted by I suspect the issue is here):
#ManagedBean
#SessionScoped
public class CategoriaBean implements Serializable{
#EJB
private NegiciosBLLocal negociosBL;
#EJB
private CategoriaBLLocal categoriaBL;
int categoriaID;
Categoria categoria;
List <Categoria> listaCategoria;
List <Negocios> listaNegocios;
public Categoria getCategoria() {
return categoria;
}
public void setCategoria(Categoria categoria) {
this.categoria = categoria;
}
public NegiciosBLLocal getNegociosBL() {
return negociosBL;
}
public void setNegociosBL(NegiciosBLLocal negociosBL) {
this.negociosBL = negociosBL;
}
public CategoriaBLLocal getCategoriaBL() {
return categoriaBL;
}
public void setCategoriaBL(CategoriaBLLocal categoriaBL) {
this.categoriaBL = categoriaBL;
}
public int getCategoriaID() {
return categoriaID;
}
public void setCategoriaID(int categoriaID) {
this.categoriaID = categoriaID;
}
public List<Categoria> getListaCategoria() {
return listaCategoria;
}
public void setListaCategoria(List<Categoria> listaCategoria) {
this.listaCategoria = listaCategoria;
}
public List<Negocios> getListaNegocios() {
return listaNegocios;
}
public void setListaNegocios(List<Negocios> listaNegocios) {
this.listaNegocios = listaNegocios;
}
public CategoriaBean() {categoria=new Categoria();}
public List<Categoria> getLista(){
listaCategoria = categoriaBL.getCategorias();
return listaCategoria;
}
public void getcategoriaIDFromCat (ActionEvent evento){
categoria = listaCategoria.get(Integer.parseInt(evento.getComponent().getClientId().split(":")[1]));
categoriaID=categoria.getCategoriaID();
}
public List<Negocios> getNegociosByCategory(){
listaNegocios = negociosBL.getNegociosByCat(categoriaID);
return listaNegocios;
}
}
When I run this in Glassfish 3.1.2.2 (build 5), can anybody assist?

Resources