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?

balteo
  • 23,602
  • 63
  • 219
  • 412
  • Which version of spring are you using?How is your controller setup done? – Santosh Gokak Nov 09 '12 at 17:21
  • Your question has already been answered in this post : http://stackoverflow.com/questions/6875255/what-does-it-mean-when-spring-mvc-controller-returns-null-view-name – Jerome Dalbert Nov 09 '12 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?" – balteo Nov 09 '12 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. – balteo Nov 09 '12 at 21:10

2 Answers2

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.

Bogdan
  • 23,890
  • 3
  • 69
  • 61
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.

Harini
  • 105
  • 3
  • 13