Spring @RequestParam与class

时间:2014-03-16 18:41:07

标签: java spring hibernate

我使用SpringHiberate来创建简单的网络服务。在Controller中,我有很长的args表格。

我的控制器

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

用户类的一部分:

@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.. 
}

是否可以将我的参数从POST请求转换为类?如果可能,需要什么?

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

    return "addAccount";
}

我怎样才能缩短代码?

1 个答案:

答案 0 :(得分:3)

首先,在你的第一个例子中,

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

无需检查null。如果无法解析@RequestParam,Spring将返回400状态代码。

  

可以将我的参数从POST请求转换为类吗?如果可能,需要什么?

是的,创建一个类,可能是您的User类,其中的字段与请求参数的名称相同。使您的处理程序方法接受该类的参数。

public String addAccoundPOST( @ModelAttribute User user ) 

如果您想验证它,只需添加@Valid

public String addAccoundPOST( @Valid @ModelAttribute User user )