SpringMVC跳转视图的五种方法

本文详细介绍了在Spring MVC框架中实现页面跳转的五种方法:通过返回视图名称、利用方法名作为视图名、使用原生Servlet API、返回ModelAndView对象以及运用转发和重定向关键字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

跳转的五种方法

第一种:返回值跳转
注:返回值就是视图名称

@RequestMapping(path = "/testUser")
public String testUser(){
    System.out.println("跳转");
    return "success";
}

第二种:无返回值
注:方法名就是视图名

@RequestMapping(path = "/testVoid")
public void testVoid(){
    System.out.println("跳转");
}

第三种:原声Servlet
注:要写全路径

@RequestMapping(path = "/testRequest")
public void testRequest(HttpServletRequest request, HttpServletResponse response) throws Exception{
    System.out.println("跳转");
    //request.getRequestDispatcher("/users/success.jsp").forward(request,response);
    System.out.println(request.getContextPath());
    response.sendRedirect(request.getContextPath()+"/users/success.jsp");
}

第四种:返回ModelAndView
注:第一种和第二种的底层也是这个实现的

@RequestMapping(path = "/testModelAndView")
public ModelAndView testModelAndView(){
    ModelAndView mv = new ModelAndView();
    mv.addObject("user","用户");  //保存数据到request域中(注:key:value)
    System.out.println("跳转");
    mv.setViewName("success");//跳转页面
    return mv;
}

第五种:关键字跳转
注:关键字:forward转发 redirect重定向

@RequestMapping(path = "/testKeyword")
public String testKeyword(){
    return "forward:/users/success.jsp";//转发
    //return "redirect:/index.jsp";//重定向
}
Spring MVC提供了多种跳转页面的方法,其中常用的有以下几种: 1. 使用String类型返回值:在Controller的处理方法中,返回一个字符串类型的视图名,Spring MVC会根据这个视图名自动查找对应的视图,然后返回给浏览器。例如: ```java @RequestMapping("/index") public String index() { return "index"; // 视图名为index } ``` 2. 使用ModelAndView类型返回值:在Controller的处理方法中,返回一个ModelAndView类型的对象,该对象包含要跳转到的视图名以及要传递给视图的数据。Spring MVC会根据该对象中的视图名自动查找对应的视图,然后返回给浏览器。例如: ```java @RequestMapping("/index") public ModelAndView index() { ModelAndView mav = new ModelAndView("index"); // 视图名为index mav.addObject("message", "Hello, World!"); // 向视图中传递数据 return mav; } ``` 3. 使用重定向:在Controller的处理方法中,使用RedirectView或redirect:前缀来指定跳转到的URL。Spring MVC会将该URL返回给浏览器,然后浏览器会向该URL发起新的请求。例如: ```java @RequestMapping("/index") public String index() { return "redirect:/home"; // 使用重定向跳转到/home } 或者 @RequestMapping("/index") public RedirectView index() { RedirectView redirectView = new RedirectView(); redirectView.setUrl("/home"); // 使用RedirectView跳转到/home return redirectView; } ``` 4. 使用forward:在Controller的处理方法中,使用forward:前缀来指定跳转到的URL。Spring MVC会将该URL转发给浏览器,然后浏览器会向该URL发起新的请求。例如: ```java @RequestMapping("/index") public String index() { return "forward:/home"; // 使用forward跳转到/home } ``` 以上就是Spring MVC中常用的跳转页面的方法
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值