How to receive an object from a form in Struts2?

0

How can I receive an object from a form in an action, in order to avoid the getter and setter to receive field to field?

Example in Spring MVC

@RequestMapping(value = "/registro", method = { RequestMethod.POST })
    public String crearUsuario(@ModelAttribute Usuario user,HttpServletRequest req) {
        ModelMap  model = new ModelMap();
        registrarUsuario.crearUsuario(user);
        req.getSession().setAttribute("idUsuario",user.getIdUsuario());
        req.getSession().setAttribute("usuario",user.getNomUsuario());

        return "redirect:/home";
    }

In this case I am receiving a user object, as would be its equivalent in an action of struts2? Thank you very much.

    
asked by Gonzalo Zago 08.08.2017 в 18:40
source

1 answer

0

In your struts Action create only one getter and setter for your object, for example User:

Usuario getUsuario(){
  return this.usario;
}

void setUsuario(Usuario usuario){
 this.usuario = usuario;
}

In the jsp, within your form, you can use struts2 tags to access the User's attributes:

<s:form ...>
    <s:textfield name="usuario.nombre" label=...>
    <s:textfiled name="usuario.apellido" label=...>
<s:form/>

And the User class is the one that has the getters and setters for each attribute:

public class Usuario {
  private String nombre;
  private String apellido;

  String getNombre(){return nombre;}
  String getApellido(){return apellido;}
  void setNombre(String nombre){this.nombre = nombre;}
  void setApellido(String apellido){this.apellido = apellido;}
}
    
answered by 30.10.2017 в 19:12