[英]Spring @RequestParam with class
I use Spring
and Hiberate
to create simply web service. 我使用Spring
和Hiberate
创建简单的Web服务。 In Controller i have long list of args from form. 在Controller中,我从表单中获取了大量的args。
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? 是否可以将我的参数从POST请求转换为类? 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? 我该如何编写较短的代码?
First of all, in your first example, 首先,在第一个示例中,
if( username != null && username.length() >= 4 )
checking for null
is not necessary. 不需要检查null
。 Spring will return a 400 status code, if a @RequestParam
cannot be resolved. 如果无法解析@ @RequestParam
,Spring将返回400状态代码。
it is possible to convert my arguments from POST request to class? 有可能将我的参数从POST请求转换为类吗? 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. 是的,创建一个类,可能是您的User
类,该类具有与请求参数共享相同名称的字段。 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
. 如果要验证它,只需添加@Valid
。
public String addAccoundPOST( @Valid @ModelAttribute User user )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.