06-重定向和转发

本文介绍了如何在Spring MVC中实现视图的转发和重定向,无论是无需视图解析器的情况还是使用视图解析器的情况。通过示例代码展示了`forward:`和`redirect:`在Controller方法返回值中的使用,解释了它们的区别和实际效果。

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

重定向和转发

通过springmvc来实现转发和重定向—无需视图解析器

测试前,需要将视图解析器注释掉

<!--    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">-->
<!--    <property name="prefix" value="/WEB-INF/jsp/"/>-->
<!--    <property name="suffix" value=".jsp" />-->
<!--</bean>-->

默认的就是转发

转发

@Controller
public class ModelTest1 {
    @RequestMapping("/m1/t1")
    public String test(Model model){
    model.addAttribute("msg","ModelTest1");
        
//    return "/WEB-INF/jsp/test.jsp";  //转发 
        
      return "forward:/WEB-INF/jsp/test.jsp";  //转发

    }
}

重定向

不需要视图解析器,本质就是重新请求一个新地方嘛,所以注意路径问题.
可以重定向到另外一个请求实现﹒

@Controller
public class ModelTest1 {
    @RequestMapping("/m1/t1")
    public String test(Model model){
    model.addAttribute("msg","ModelTest1");
        
    return "redirect:/index.jsp";   //重定向
        
    }
}

通过springmvc来实现转发和重定向—有视图解析器

转发

@Controller
public class ModelTest1 {
    @RequestMapping("/m1/t1")
    public String test(Model model){
    model.addAttribute("msg","ModelTest1");        
        
      return "/test";  //转发

    }
}

重定向

@Controller
public class ModelTest1 {
    @RequestMapping("/m1/t1")
    public String test(Model model){
    model.addAttribute("msg","ModelTest1");        
        
      return "/redirect:/index.jsp";  //重定向
	// return "/redirect:hello.do";  //hello.do为另一个请求
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值