SpringBoot请求转发与重定向
在Spring Boot中,你可以使用RedirectAttributes
来重定向请求并保留参数,使用HttpServletRequest
和HttpServletResponse
或者RestController
的@RequestMapping
注解来实现请求的转发。
重定向示例:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
public class RedirectController {
@GetMapping("/redirect")
public String redirectWithAttributes(RedirectAttributes redirectAttributes) {
redirectAttributes.addAttribute("param", "value");
return "redirect:/target";
}
}
请求转发示例:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class ForwardController {
@GetMapping("/forward")
public void forwardRequest(HttpServletRequest request, HttpServletResponse response) {
request.getRequestDispatcher("/WEB-INF/views/page.jsp").forward(request, response);
}
}
或者使用@RestController
注解进行转发:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RestForwardController {
@GetMapping("/rest/forward")
public String forwardRequest() {
return "Forward to another endpoint";
}
}
在@RestController
中,你可以通过返回字符串指定视图名称或者使用HttpEntity
进行更复杂的操作。
评论已关闭