从Spring控制器发送重定向

12 浏览
0 Comments

从Spring控制器发送重定向

如果返回类型不是String的话,如何在Spring控制器中发送重定向到URL Handler方法。

@RequestMapping(value = "/save", method = RequestMethod.POST)
@ResponseBody
public JsonResponse save(@RequestBody FormBean formBean) {  
    if(condition true)
      ? Save(formBean)
      : "redirect:/anotherUrl";
}

所以返回类型JsonResponse实际上是一个Java类,我如何在这里发送重定向呢?

0
0 Comments

问题的原因是控制器方法需要返回一个ResponseEntity对象来处理重定向,但是没有正确设置重定向的状态码和头部信息。

解决方法是在控制器方法中返回一个ResponseEntity对象,并设置正确的状态码和头部信息来实现重定向功能。

以下是解决方案的代码示例:

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/example")
public class ExampleController {
    
    @GetMapping("/redirect")
    public ResponseEntity redirect() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Location", "http://www.example.com");
        return new ResponseEntity<>(headers, HttpStatus.FOUND);
    }
}

以上代码中的`redirect`方法返回了一个`ResponseEntity`对象,并设置了重定向的URL和状态码。通过设置`Location`头部信息为重定向的URL,并将状态码设置为`HttpStatus.FOUND`来实现重定向功能。

这样,在访问`/example/redirect`接口时,客户端会收到一个`302 Found`的响应,并包含一个`Location`头部信息,告诉客户端要重定向到`http://www.example.com`。

0