0

I'm working on simple Spring-MVC application and I love new Spring REST features. I'd like to use the same method to process regular form and JSON data. It seems to be a little tricky, however. For example, method

public @ResponseBody String process(@RequestBody Bean bean);

will work for JSON request (Content-type: application/json), and

public @ResponseBody String process(Bean bean);

will match request with Content-type: application/x-www-form-urlencoded.

These methods are obviously will have almost the same content, so I'd prefer to avoid such duplication. With Jersey it's possible with @Consumes annotations, but I can't figure out how to do it with Spring.

2
  • What is the return type for those methods? I thought you needed to specify a "type" after the @ResponseBody annotation or at least void? Commented Feb 15, 2011 at 23:32
  • Oh, sorry missed return types. They are irrelevant, in fact. It seems, Spring matches request by arguments. Commented Feb 16, 2011 at 9:23

2 Answers 2

1

First, the above declaration won't compile, because you are having duplicate signature.

Btw, @Consumes wouldn't help, I think, because it only designates what content type the method can handle.

In spring you can specify the content-type with

@RequestMapping(headers="Content-Type=application/json")
Sign up to request clarification or add additional context in comments.

8 Comments

@Consumes is for Jersey, sorry for misunderstanding. Thanks for your remark about compilation, but these signatures are just for demonstration purposes. What I really need is not to have different methods for JSON and form data processing, which seems to be impossible with Spring MVS.
@rsvato and how is it possible in Jersey? I've shown the equivallent of Consumes - it's "headers". But how would it work in Jersey? You can specify that the method handles both content types (and so can you in spring), and then?
And then approriate MessageBodyReader implementation will decode request. So it's just a question of provider (in Jersey). You mean it's impossible to process several content types with one method?
@rsvato - I was asking how will you do it. I've done very little with jax-rs.
Ah, I see. Well, i'm annotating method with @Consumes({"application/json", "application/xml", "application/form"}) which means that this method may process all three types of requests.
|
0

Just add @RestController annotation for the controller class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.