4

I have read the Spring documentation and I was not able to find relevant information regarding the expected behavior of a Spring MVC controller method returning null (with a return type of String).

Can someone please provide a reply or direct me to relevant documentation? Or to put it another way, what would be the benefit of returning null from a Spring MVC controller method?

4
  • Which version of spring are you using?How is your controller setup done? Commented Nov 9, 2012 at 17:21
  • Your question has already been answered in this post : stackoverflow.com/questions/6875255/… Commented Nov 9, 2012 at 18:50
  • Jerome: you must have misread my question. The link you provide explains how the controller will resolve the view name. My question is : "what is the benefit of returning null from a controller method?" Commented Nov 9, 2012 at 21:08
  • Santosh: I use the current version of Spring i.e. 3.1 and I rely on Spring Roo's default configuration for the controller setup. Commented Nov 9, 2012 at 21:10

2 Answers 2

6

In Spring 2, when you returned null from a controller you were saying to the Spring dispatcher that you don't want it to search for a view.

You did this if you were handling the response yourself by writing the response content directly and then flushing the output stream (you were managing a file download for example).

If you didn't return null, Spring would have forwarded to a view who would try to write to the response also, messing up your already written data or resulting in an exception if the response was already commited.

Returning null was a way of saying back off to Spring's view resolver.

A lot of things changed in Spring 3 and now the same can be obtained by having an @RequestMapping annotated method that returns void.

If you have a return type of String but you return null I think that it uses the default RequestToViewNameTranslator for translating an incoming HttpServletRequest into a logical view name when the view name wasn't explicitly supplied.

Sign up to request clarification or add additional context in comments.

Comments

0

Return type String in spring mvc generally returns your view resolver, it can be your JSP, html or any other view page.

http://www.mkyong.com/spring3/spring-3-mvc-hello-world-example/

Suppose you want to return a normal String like "hi", you can use @ResponseBody annotation to do this.

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.