开发者

How to bind request params in spring 3.0?

I'm building a controller which takes a request from a third party service. This service have request 5 params which I need to bind to a Message class.

Say, I in request, I'm getting

?a=x&b=y&c=z&d=w&e=k&f=t

The Message class is

public class Message{
 String a;
 String b;
 String c;
 String d;
 String e;
 String f;
 public Message(String a, String b, String c, String d, String e, String f){
     this.a=a;this.b=b;this.c=c;this.d=d;this.e=e;this.f=f;
 }
 ....// along with getters and setters
}

One option is to use @RequestParam in the method controller, but then I would have to p开发者_C百科ass all the parameters and then instantiate the Message object manually. I don't want to do that because the parameter count is too large.

Can this be done using init binder/web data binder? and how?


You don't need to do anything special to make this work, just declare a Message parameter to your controller method:

@RequestMapping
public String handleRequest(Message message) {
   ...
}

Spring will bind each parameter to a property on Message, where it can find one. If Message has getters and setters (and a default constructor), it will just work. If you want to use a non-default constructor, or direct field injection, you'll have to do more config work.


I think you just need to pass the Message object as a parameter for the controller's handler method, and the binding happens automatically. Your request param string would need to be like this though: ?a=x&b=y&c=z&d=w&e=&f= because if you have ?param=a&param=b&param=c then your message object would need to be:

class Message {
    List<String> param; // ends up holding strings "a","b","c",...
}

Which is not what you want (as far as I can see).


You can do that without any special work, just list the object you need, then Spring will cleanly bind your request parameters to your class instance.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜