Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
744 views
in Technique[技术] by (71.8m points)

jsf 2 - Request parameter is null during postback

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
           

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...