-1

I'm using Spring, Hibernate and JSF for a web application. In my case I have a Table User having many columns, one of those is idRole. idRole is a foreign key from table Role which containes Id of the role and the role name. What I want to know is how to make the role name shown in my place of the ID, and make that field a List showing only possible roles (which are all the columns of the Roles table)

Here is my ManagedBean :

package managedController;

import org.primefaces.event.RowEditEvent;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import spring.model.Customer;
import spring.service.CustomerService;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@ManagedBean(name="customerMB")
@RequestScoped
public class CustomerManagedBean implements Serializable {

    private static final long serialVersionUID = 1L;
    private static final String SUCCESS = "success";
    private static final String ERROR   = "error";

    @ManagedProperty(value="#{CustomerService}")
    CustomerService customerService;

    List<Customer> customerList;

    private int id;
    private String name;
    private String surname;

    public String addCustomer() {
        try {
            Customer customer = new Customer();
            customer.setId(getId());
            customer.setName(getName());
            customer.setSurname(getSurname());
            getCustomerService().addCustomer(customer);
            reset();
            return SUCCESS;
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return ERROR;
    }

    public String updateCustomer(Customer customer) {
        try {
            getCustomerService().updateCustomer(customer);
            return SUCCESS;
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return ERROR;
    }

    public String deleteCustomer(Customer customer) {
        try {
            getCustomerService().deleteCustomer(customer);
            customerList = null;
            getCustomerList();
            return SUCCESS;
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return ERROR;
    }

    public void onEdit(RowEditEvent event) {
        FacesMessage msg = new FacesMessage("Item Edited");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        updateCustomer((Customer)event.getObject());
    }

    public void onCancel(RowEditEvent event) {
        FacesMessage msg = new FacesMessage("Item Cancelled");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    public void reset() {
        this.setId(0);
        this.setName("");
        this.setSurname("");
    }

    public List<Customer> getCustomerList() {
        if(customerList == null){
            customerList = new ArrayList<Customer>();
            customerList.addAll(getCustomerService().getCustomers());
        }
        return customerList;
    }

    public CustomerService getCustomerService() {
        return customerService;
    }

    public void setCustomerService(CustomerService customerService) {
        this.customerService = customerService;
    }

    public void setCustomerList(List<Customer> customerList) {
        this.customerList = customerList;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

}

and here is the file where I show them (Users or Customers let's say) :

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:p="http://primefaces.org/ui"
      xmlns:sec="http://www.springframework.org/security/tags">

<h:head>
    <title>Welcome</title>

</h:head>

<h:body>

    <!-- View element level Spring Security : only can view for who has the role 'ROLE_ADMIN' -->
    <sec:authorize access="hasAnyRole('ROLE_ADMIN')">
        <h:form id="form2">
            <table>
                <tr>
                    <td><h:outputLabel for="id" value="Id : "/></td>
                    <td><p:inputText id="id" value="#{customerMB.id}">
                        <f:converter converterId="javax.faces.Integer"/>
                        <p:ajax event="blur" update="idMsg"/>
                    </p:inputText>
                        <p:message id="idMsg" for="id" display="icon"/>
                    </td>
                </tr>
                <tr>
                    <td><h:outputLabel for="name" value="Name : "/></td>
                    <td><p:inputText id="name" value="#{customerMB.name}">
                        <f:validateLength minimum="1"/>
                        <p:ajax event="blur" update="nameMsg"/>
                    </p:inputText>
                        <p:message id="nameMsg" for="name" display="icon"/>
                    </td>
                </tr>
                <tr>
                    <td><h:outputLabel for="surname" value="Surname : "/></td>
                    <td><p:inputText id="surname" value="#{customerMB.surname}">
                        <f:validateLength minimum="1"/>
                        <p:ajax event="blur" update="surnameMsg"/>
                    </p:inputText>
                        <p:message id="surnameMsg" for="surname" display="icon"/>
                    </td>
                </tr>
                <tr>
                    <td><p:commandButton id="addUser" value="Add" action="#{customerMB.addCustomer}" ajax="false"/></td>
                    <td><p:commandButton id="reset" value="Reset" action="#{customerMB.reset}" ajax="false"/></td>
                </tr>
            </table>
        </h:form>
    </sec:authorize>

    <br/>

    <h:form id="form1">
        <p:growl id="messages" showDetail="true"/>
        <p:dataTable id="customers" var="customer" value="#{customerMB.customerList}" style="width: 10%" editable="true">
            <p:ajax event="rowEdit" listener="#{customerMB.onEdit}" update=":form1:messages"/>
            <p:ajax event="rowEditCancel" listener="#{customerMB.onCancel}" update=":form1:messages"/>
            <p:column headerText="ID">
                <h:outputText value="#{customer.id}"/>
            </p:column>
            <p:column headerText="Name">
                <f:facet name="header">
                    <h:outputText value="Name"/>
                </f:facet>
                <p:cellEditor>
                    <f:facet name="output">
                        <h:outputText value="#{customer.name}"/>
                    </f:facet>
                    <f:facet name="input">
                        <p:inputText value="#{customer.name}" label="name"/>
                    </f:facet>
                </p:cellEditor>
            </p:column>
            <p:column headerText="Surname">
                <p:cellEditor>
                    <f:facet name="output">
                        <h:outputText value="#{customer.surname}"/>
                    </f:facet>
                    <f:facet name="input">
                        <p:inputText value="#{customer.surname}" label="surname"/>
                    </f:facet>
                </p:cellEditor>
            </p:column>
            <sec:authorize access="hasAnyRole('ROLE_ADMIN')">
                <p:column>
                    <f:facet name="header">Delete</f:facet>
                    <h:commandLink value="Delete" action="#{customerMB.deleteCustomer(customer)}"/>
                </p:column>
                <p:column style="width:20%">
                    <f:facet name="header">Update</f:facet>
                    <p:rowEditor/>
                </p:column>
            </sec:authorize>
        </p:dataTable>
        <br/>
        <p:commandButton value="Logout" id="logout" action="#{loginBean.logout}"/>
    </h:form>
</h:body>

</html>

Thank you

Chaibi Alaa
  • 1,216
  • 4
  • 22
  • 45
  • Where are your entities ? There is no user and no role just consumers in a list in your code. So you want a selectOneMenu with all the roles possible ? – Ced Aug 26 '15 at 01:46

1 Answers1

1
@ManagedBean(name="customerMB")
@RequestScoped
...
@ManagedProperty(value="#{CustomerService}")
CustomerService customerService;

It's advised to switch those to :

@Named
@RequestScoped
...
@Inject or @EJB
SomeService ss;
//for a managed property just use Inject without parameters.

Your code will still work. But take the javax.enterprise.context.RequestScoped package for request scoped.

Since you didn't post any entity whatsoever and probably copy pasted the tutorial, I'll post smtg generic to give you a general idea of how to go with it:

@Named
@RequestScoped
public class Mybean {

   private List<User> userLists; // +getters and setters
   @EJB
   private SomeService ss;

   //make the call to the Db in a PostConstruct annotated method, NOT in the constructor. So the injections are done.
   @PostConstruct
   public void init(){
      userLists = ss.getUsers();
   }
}

What I want to know is how to make the role name shown in my place of the ID

Huh ? I guess you want this :

<h:dataTable value="#{mybean.userLists}" var="user">
    <h:column>
      #{user.role.name} 
    </h:column>
</h:dataTable>

In your entities you must have a relationship between the two. Probably @ManyToOne

and make that field a List showing only possible roles (which are all the columns of the Roles table)

Same idea, get your list from db in the init method:

roleList = aService.getRoles();

Then You want to display those in a list ? I guess you meant a selectOneMenu. Follow the link the tutorial is well explained.

Community
  • 1
  • 1
Ced
  • 12,657
  • 11
  • 62
  • 124