2

I have a view that display a list of users, from this view I can go to another view of "details" of any selected user. In the details view I need to select some values from 2 select list and then in the backed bean take these values, and add them to an user to finally store (update) the user in the database. These are my methods in the "user Bean".

With this method I get the user id from the "list of users view" and retrieve the user from the database to display its info on the details view.

public void getParam(){

    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();

    //Obtener parametros del request
    Map<String, String> parameterMap = (Map<String, String>) externalContext.getRequestParameterMap();
    Long param = Long.valueOf(parameterMap.get("id_usuario"));
    System.out.println(param);
    this.setU(controlador.getUser(param));


}

With this method I set the values from the select list to an object and then I add this object to the user, finally I save it on the database.

public void setPrivilegio(){

    System.out.println("hola");
    Privilegio pri=new Privilegio();
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();

    //Obtener parametros del request
    Map parameterMap = externalContext.getRequestParameterMap();
    Agrupacion agrupacion= (Agrupacion)parameterMap.get("agrup");
    System.out.println(agrupacion.getNombre());
    Rol rol = (Rol)parameterMap.get("rols");
    System.out.println(rol.getNombre());
    System.out.println(""+rol.getNombre()+" "+agrupacion.getNombre());
    pri.setRol(rol);
    pri.setAgrupacion(agrupacion);
    pri.setActive(true);
    this.getU().addPrivilegio(pri);

    controlador.saveUsuario(this.getU());


}

This is my view:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html"
                xmlns:f="http://java.sun.com/jsf/core">
    <div class="container">
        <h:panelGroup id="Usuarios">
            <h:form id="FormUsuarios">
                <h2>Detalles Usuario</h2>

                <h:dataTable id="users" value="#{usuario.u}"  styleClass="table table-striped table-bordered" headerClass="sorting_asc"
                             rowClasses="odd,even">
                    <h:column>
                        <f:facet name="header">#</f:facet>
                        #{usuario.u.id}
                    </h:column>
                    <h:column>
                        <f:facet name="header">Identificador</f:facet>
                        <h:inputText id="identificador" value="#{usuario.u.identificador}" />
                    </h:column>
                    <h:column>
                        <f:facet name="header">Nombre</f:facet>
                        <h:inputText id="nombres" value=" #{usuario.u.nombres}"/>   <h:inputText id="apellidoP" value=" #{usuario.u.apellidoPaterno}"/> <h:inputText id="apellidoM" value=" #{usuario.u.apellidoMaterno}"/>
                    </h:column>
                    <h:column>
                        <f:facet name="header">Active</f:facet>
                        <h:selectBooleanCheckbox id="check" value="#{usuario.u.active}"></h:selectBooleanCheckbox>
                    </h:column>

                </h:dataTable>

                <h3>Asignar Privilegios</h3>

                <h:selectOneMenu id="agrup" value="#{usuario.selected}" converter="omnifaces.SelectItemsConverter">
                    <f:selectItems value="#{agrupacion.agrupacion}" var="entity" itemLabel="#{entity.nombre}" itemValue="#{entity.id}"/>
                </h:selectOneMenu>

                <h:selectOneMenu id="rols" value="#{rol.selected}" converter="omnifaces.SelectItemsConverter">
                    <f:selectItems value="#{rol.roles}" var="rol" itemLabel="#{rol.nombre}" itemValue="#{rol.id}"/>
                </h:selectOneMenu>

                <h:commandButton  value="Asignar"  styleClass="btn-primary" actionListener="#{usuario.setPrivilegio}">
                </h:commandButton>


                <h3>Privilegios Asignados:</h3>

                <h:dataTable id="privilegios" value="#{usuario.u.privilegios}" var="p" styleClass="table table-striped table-bordered" headerClass="sorting_asc"
                             rowClasses="odd,even">
                    <h:column>
                        <f:facet name="header">#</f:facet>
                        #{p.id}
                    </h:column>
                    <h:column>
                        <f:facet name="header">Roles</f:facet>
                        #{p.rol.nombre}
                    </h:column>
                    <h:column>
                        <f:facet name="header">Grupos</f:facet>
                        #{p.agrupacion.nombre}
                    </h:column>
                    <h:column>
                        <f:facet name="header">Active</f:facet>
                        <h:selectBooleanCheckbox id="checkbox" value="#{p.active}"></h:selectBooleanCheckbox>
                    </h:column>

                </h:dataTable>






            </h:form>
            <script type="text/javascript" src="js/paging-bootstrap.js"></script>
            <script type="text/javascript" src="js/contenidoc.datatable.init.js"></script>
        </h:panelGroup>
    </div>
</ui:composition>

When I click on my commandbutton called "Asignar" that calls the method setPrivilegio(), I get this error:

java.lang.NumberFormatException: null
    at java.lang.Long.parseLong(Long.java:404)
    at java.lang.Long.valueOf(Long.java:540)
    at cl.uchile.sti.bean.UsuarioBean.getParam(UsuarioBean.java:114)

The tables in the view shows all the info, but when I want to call the method that add the selected items to the user and save it on the database (setPrivilegio) I get this error.

How is this caused and how can I solve it?

This is my full "user bean":

@ManagedBean(name = "usuario")
@ViewScoped
public class UsuarioBean {
    private usuarioController controlador;
    private Usuario u=new Usuario();
    private Privilegio Selected=new Privilegio();
    private Boolean active;
    private long id_user;

    @PostConstruct
    public void init() {


        controlador=new usuarioController();

    }


    public long getId_user() {
        return id_user;
    }

    public void setId_user(long id_user) {
        this.id_user = id_user;
    }

    public Privilegio getSelected() {
        return Selected;
    }

    public void setSelected(Privilegio selected) {
        Selected = selected;
    }

    public Boolean getActive() {

        return active;
    }

    public void setActive(Boolean active) {

        this.active = active;
    }

    public Usuario getU() {
        getParam();
        return u;
    }

    public void setU(Usuario u) {
        this.u = u;
    }

    private List<Usuario> usuario;



    public List<Usuario> getUsuario() {
        usuario=UsuarioDAO.getAll();
        return usuario;
    }

    public Usuario getById(long id_usuario){

       return u;
    }

    public void setUsuario(List<Usuario> usuario) {
        this.usuario = usuario;
    }


    public void saveUsuario(Usuario u){
        controlador.saveUsuario(u);
    }

    public void getParam(){

        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExternalContext externalContext = facesContext.getExternalContext();

        //Obtener parametros del request
        Map<String, String> parameterMap = (Map<String, String>) externalContext.getRequestParameterMap();
        Long param = Long.valueOf(parameterMap.get("id_usuario"));
        System.out.println(param);
        this.setU(controlador.getUser(param));


    }

    public void setPrivilegio(){

        System.out.println("hola");
        Privilegio pri=new Privilegio();
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExternalContext externalContext = facesContext.getExternalContext();

        //Obtener parametros del request
        Map parameterMap = externalContext.getRequestParameterMap();
        Agrupacion agrupacion= (Agrupacion)parameterMap.get("agrup");
        System.out.println(agrupacion.getNombre());
        Rol rol = (Rol)parameterMap.get("rols");
        System.out.println(rol.getNombre());
        System.out.println(""+rol.getNombre()+" "+agrupacion.getNombre());
        pri.setRol(rol);
        pri.setAgrupacion(agrupacion);
        pri.setActive(true);
        this.getU().addPrivilegio(pri);

        controlador.saveUsuario(this.getU());


    }









}

this is the first view (list of users, from which i go to user details)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html"
                xmlns:f="http://java.sun.com/jsf/core">
    <div class="container">
        <h:panelGroup id="Usuarios">
            <h:form id="FormUsuarios">
                <h2>Listado de Usuarios</h2>
                <h:graphicImage url="http://a.dryicons.com/images/icon_sets/simplistica/png/128x128/add.png" width="30" height="30"/>

                <h:dataTable id="users" value="#{usuario.usuario}" var="o" styleClass="table table-striped table-bordered" headerClass="sorting_asc"
                             rowClasses="odd,even">
                    <h:column>
                        <f:facet name="header">#</f:facet>
                        #{o.id}
                    </h:column>
                    <h:column>
                        <f:facet name="header">Identificador</f:facet>
                        #{o.identificador}
                    </h:column>
                    <h:column>
                        <f:facet name="header">Nombre</f:facet>
                        #{o.nombres}  #{o.apellidoMaterno} #{o.apellidoPaterno}
                    </h:column>
                    <h:column>
                        <f:facet name="header">Active</f:facet>
                        <h:selectBooleanCheckbox id="check" value="#{o.active}"></h:selectBooleanCheckbox>
                    </h:column>
                    <h:column>
                        <f:facet name="header">Detalles</f:facet>


                        <h:outputLink  value="contenido/detalleUsuario.xhtml">
                            Detalle
                            <f:param name="id_usuario" value="#{o.id}"  />
                        </h:outputLink>
                    </h:column>
                </h:dataTable>
            </h:form>
            <script type="text/javascript" src="js/paging-bootstrap.js"></script>
            <script type="text/javascript" src="js/contenidoc.datatable.init.js"></script>
        </h:panelGroup>
    </div>
</ui:composition>
user2018726
  • 638
  • 2
  • 12
  • 23
  • Where does your parameter `id_usuario` came from? I can't see it anywhere on xhtml page. It is obvious that it is null. – partlov Jan 28 '13 at 18:31
  • it comes from the other view (list of users view): i take it in the backed bean and it works because i can see the "details" of the selected user, but it fails when the method "setPrivilegio()" is called. – user2018726 Jan 28 '13 at 19:07
  • Do not do business logic in getters. http://stackoverflow.com/questions/2090033/why-jsf-calls-getters-multiple-times/2090062#2090062 – BalusC Jan 28 '13 at 20:08

2 Answers2

3

Bad getter!

    public Usuario getU() {
    getParam();
    return u;
    }

The getter above is a very bad idea. You've said it yourself that the variable makes it into the usuario backing bean(this I doubt). It is just plain wrong to perform business logic inside a getter because of inconsistencies (like you're experiencing) and the fact that the getter is called multiple times during a request. There are more elegant and cleaner ways to pass and initialise parameters between JSF pages.

private Usuario u=new Usuario(); is also a bad idea. Why is this necessary when you have

      this.setU(controlador.getUser(param));

All that should happen inside your @PostConstructor

    @PostConstruct
    public void init() {


    controlador=new usuarioController();
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();

    //Obtener parametros del request
    Map<String, String> parameterMap = (Map<String, String>) externalContext.getRequestParameterMap();
    Long param = Long.valueOf(parameterMap.get("id_usuario"));
    System.out.println(param);
    this.setU(controlador.getUser(param));

    }

The getter should just be plain

public Usuario getU() {
    return u;
}
Community
  • 1
  • 1
kolossus
  • 20,559
  • 3
  • 52
  • 104
  • thanks for your answer.. i did that at first, but when i put that code inside of the init() i get this error: SEVERE: Error Rendering View[/main.xhtml] com.sun.faces.mgbean.ManagedBeanCreationException: An error occurred performing resource injection on managed bean usuario at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:229) – user2018726 Jan 28 '13 at 20:16
  • in this line: Long param = Long.valueOf(parameterMap.get("id_usuario")); but it says : An error occurred performing resource injection on managed bean usuario at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:229) – user2018726 Jan 28 '13 at 20:27
  • @user2018726 `param` is a reserved keyword, used for injecting request params(that method of injection is not available to you because of the scope of your backing bean). Change your variable name – kolossus Jan 28 '13 at 20:29
  • i changed the name and i got the same error :( in "root cause" says this: java.lang.NumberFormatException: null java.lang.Long.parseLong(Long.java:404) java.lang.Long.valueOf(Long.java:540) cl.uchile.sti.bean.UsuarioBean.init(UsuarioBean.java:50) – user2018726 Jan 28 '13 at 20:34
  • now i added the code of the first view from which i go to "details" passing the parameter "id_user". – user2018726 Jan 28 '13 at 20:42
  • @user2018726 That parameter never made it into the bean. Please use the parameter transmission method detailed in the second link to pass the parameter from the first to the second view. We can take this to chat if you need guidance – kolossus Jan 28 '13 at 22:39
  • @user2018726 nah, there's [chat here](http://chat.stackoverflow.com/users/1530938/kolossus) – kolossus Jan 29 '13 at 15:02
0

The cause of this error is that parameterMap.get("id_usuario") is null. You should investigate how you pass this parameter from the UI to the backing bean.

Bogdan
  • 934
  • 7
  • 13