一、重定向

方式一:使用 "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";//跳转到指定页面
    }
}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐