1

How do you write a controller method which can either return a View or HTTP response status code based on if its 200 then view else the response status code.

 @RequestMapping(value="/",method=RequestMethod.GET)
 public String showLanding()
 {
    return View.Landing;     
 } 

I want to handle in case of 401, 403, 500 etc. just status code should be returned instead of view.

Novice User
  • 3,552
  • 6
  • 31
  • 56

3 Answers3

0

To return the 403- Unauthorized status code,

@RequestMapping(value="/",method=RequestMethod.GET)
public String showLanding()
{
     return HttpStatus.UNAUTHORIZED;    
} 

See this:

  1. http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/http/HttpStatus.html?is-external=true
  2. How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?
Community
  • 1
  • 1
Pankaj Gadge
  • 2,748
  • 3
  • 18
  • 25
0

You could also check out the @ResponseStatus annotation as well as ResponseEntity (for more dynamic scenarios)

geoand
  • 60,071
  • 24
  • 172
  • 190
0

I'm far from suggesting that you should do flow control with Exceptions - but those HTTP statuses are errors and exceptions. So you might want to throw business exceptions from your controller methods and then handle those using @ExceptionHandlers.

You can also target a subset of Controllers and assist those with Exception handling using @ControllerAdvice.

Brian Clozel
  • 56,583
  • 15
  • 167
  • 176