springboot 重定向、转发

小灰灰 2024-02-05 12:58 159阅读 0赞

一、重定向

方式一:使用 “redirect” 关键字

注意:类的注解不能使用@RestController,要用@Controller。(因为@RestController内含@ResponseBody,解析返回的是json串。不是跳转页面)

  1. @Controller
  2. @RequestMapping(value="/product/list/{pid}" , method = RequestMethod.GET)
  3. public String test(@PathVariable String pid) {
  4. return "redirect:/ali/hello.html";
  5. }

方式二:使用servlet 的API

注意:类的注解不受@RestController和@Controller影响,可随意使用。

  1. @RequestMapping(value="/product/list/{pid}" , method = RequestMethod.GET)
  2. public void test(@PathVariable String pid, HttpServletResponse response) throws IOException {
  3. response.sendRedirect("/ali/hello.html");
  4. }

二、转发

方式一:使用 “forward” 关键字

注意:类的注解不能使用@RestController 要用@Controller

  1. @Controller
  2. @RequestMapping(value="/product/list/{pid}" , method = RequestMethod.GET)
  3. public String test(@PathVariable String pid) {
  4. return "forword:/ali/hello.html";
  5. }

方式二:使用servlet 的API

注意:类的注解不受@RestController和@Controller影响,可随意使用。

  1. @RequestMapping(value="/product/list/{pid}" , method = RequestMethod.GET)
  2. public void test(@PathVariable String pid, HttpServletRequest request, HttpServletResponse response) throws Exception {
  3. request.getRequestDispatcher("/ali/hello.html").forward(request,response);
  4. }

三、跳转到当前项目下的指定页面

无配置:访问的是templates目录下的页面。

经过配置:可访问public、static等目录下的页面。

  1. @Controller
  2. public class UserController {
  3. @RequestMapping("/product/list")
  4. public String showName(String pid,Model model){
  5. model.addAttribute("pid",pid);
  6. return "index";//跳转到指定页面
  7. }
  8. }

发表评论

表情:
评论列表 (有 0 条评论,159人围观)

还没有评论,来说两句吧...

相关阅读

    相关 转发定向

    1.转发         当客户端发送一个请求到服务器后,Web服务器调用内部的方法在容器内部完成请求处理和转发动作。可以共享request范围内的数据,客户端的URL地址不

    相关 转发定向

    区别 先来说说两者区别: 1. 转发是服务器行为,重定向是客户端行为 2. 转发是一次请求,重定向至少是两次请求 3. 转发浏览器url的地址栏不变,重定向url