在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进行更复杂的操作。