kris14an kris14an - 4 months ago 23
Java Question

Spring @RequestParam with class

I use

Spring
and
Hiberate
to create simply web service. In Controller i have long list of args from form.

My Controller

@RequestMapping( value="/addAccount", method=RequestMethod.POST )
public String addAccoundPOST( @RequestParam( value = "username" ) String username,
@RequestParam( value = "password" ) String password,
@RequestParam( value = "email" ) String email,
@RequestParam( value = "name" ) String name,
@RequestParam( value = "surname" ) String surname,
@RequestParam( value = "birth_date" ) String birth_date,
@RequestParam( value = "place" ) String place,
@RequestParam( value = "province" ) String province,
@RequestParam( value = "motorcycle" ) String motorcycle,
@RequestParam( value = "tel" ) String tel )
{
User user = new User();

if( username != null && username.length() >= 4 )
user.setUsername( username );

if( password != null && password.length() >= 4 )
user.setPassword( password );

// and more, and more, and mode....

return "addAccount";
}


Part of User class:

@Entity
@Table( name = "users", catalog = "dbjadenazlot" )
public class User implements Serializable {
private int uid;

private String ...;
/* --------------------------------- GET ------------------------------ */

@Id
@GeneratedValue(strategy = IDENTITY)
@Column( name = "uid", unique = true, nullable = false )
public int getUID()
{ return uid;}

@Column( name = "name", length = 45 )
public String getName()
{ return name; }
// setters and rest code..
}


Is it possible to convert my arguments from POST request to class? If it's possible, what is required?

@RequestMapping( value="/addAccount", method=RequestMethod.POST )
public String addAccoundPOST( @RequestParam( value = "user") User user )
{

return "addAccount";
}


How can i write shorten code?

Answer

First of all, in your first example,

if( username != null && username.length() >= 4 )

checking for null is not necessary. Spring will return a 400 status code, if a @RequestParam cannot be resolved.

it is possible to convert my arguments from POST request to class? If it's possible, what is required?

Yes, create a class, possibly your User class, which has fields that share the same name as the request parameters. Make your handler method accept a parameter of that class.

public String addAccoundPOST( @ModelAttribute User user ) 

If you want to validate it, just add @Valid.

public String addAccoundPOST( @Valid @ModelAttribute User user ) 
Comments