springboot 重定向、转发

一、重定向

方式一:使用 "redirect" 关键字

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

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

方式二:使用servlet 的API

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

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

二、转发

方式一:使用 "forward" 关键字

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

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

方式二:使用servlet 的API

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

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

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

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

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

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

猜你喜欢

转载自blog.csdn.net/u011149152/article/details/134854427