1

I have a spring mvc controller, which accepts a post request and it needs to redirect to a URL (GET request).

@RequestMapping(value = "/sredirect", method = RequestMethod.POST)
public String processForm(HttpServletRequest request) {
    System.out.println("Ews redirect hit !!! ");
request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE,HttpStatus.MOVED_PERMANENTLY);
    
    return "redirect:https://www.google.com/";
}

And the class is annotated with @RestController. I am always getting 405, method not allowed for the redirect url. (i.e google.com).

As per docs (https://www.rfc-editor.org/rfc/rfc7238), it should allow the method to be changed . I am not sure what am I doing wrong? Can someone help

Community
  • 1
  • 1
TruckDriver
  • 1,383
  • 13
  • 28
  • It sounds like you're getting the 405 instead of your logging, correct? Are you doing an HTTP POST to your /sredirect? That's the only thing this controller will accept. – dbreaux Aug 27 '18 at 13:36
  • No , my logs are being printed correctly in console, . – TruckDriver Aug 27 '18 at 13:40
  • 1
    Ok, based on this, then, I'm thinking that RestControllers can't simply return "redirect:", like non-Rest Controllers can: https://stackoverflow.com/questions/29085295/spring-mvc-restcontroller-and-redirect (Not adding as an answer, because I don't actually know :-)) – dbreaux Aug 27 '18 at 16:00
  • @dbreaux You are correct, the solution mentioned in the link works for me. You can add this as answer, I will accept it. :) – TruckDriver Aug 28 '18 at 05:32

2 Answers2

1

It looks like Rest Controllers can't use the simple "redirect:" convention, like non-Rest Controllers can. See Spring MVC @RestController and redirect

dbreaux
  • 4,982
  • 1
  • 25
  • 64
0

Have you tried accepting GET in the request mapping?

method = { RequestMethod.POST, RequestMethod.GET }
Baskiney
  • 76
  • 3
  • Hmm Okay. Maybe change the function to return type void and call `request.sendRedirect("https://www.google.com");` instead of the return. – Baskiney Aug 27 '18 at 11:57