Spring MVC @RestController and redirect

后端 未结 6 1088
闹比i
闹比i 2020-11-29 22:19

I have a REST endpoint implemented with Spring MVC @RestController. Sometime, depends on input parameters in my controller I need to send http redirect on client.

I

6条回答
  •  春和景丽
    2020-11-29 22:30

    To avoid any direct dependency on HttpServletRequest or HttpServletResponse I suggest a "pure Spring" implementation returning a ResponseEntity like this:

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(URI.create(newUrl));
    return new ResponseEntity<>(headers, HttpStatus.MOVED_PERMANENTLY);
    

    If your method always returns a redirect, use ResponseEntity, otherwise whatever is returned normally as generic type.

提交回复
热议问题