springmvc跳转到响应页面(modelandview 中的view)

这篇博客详细介绍了在Spring MVC中,如何使用`ModelAndView`或直接返回字符串来实现页面跳转。通过`forward`和`redirect`前缀,解释了它们在视图解析过程中的不同行为。`forward`是请求转发,不会改变浏览器URL,而`redirect`是重定向,浏览器会发起新的请求。示例代码展示了如何配置和使用这两个功能。
摘要由CSDN通过智能技术生成

从控制器类向前端页面跳转时,指定传递的页面

modelandview 中的view

1.当返回的就是我要显示的页面名时,使用thymeleaf解析器(thymeleaf设置的视图解析器)解析出文件地址,转发方式跳转到该页面

2.当以forward为前缀时,创建internalsersourceview视图,此时不会直接被thymeleaf解析,而是将forward去掉,寻找控制器的value一样的方法,用thymeleaf解析该方法的返回值,并请求转发访问该页面

 @RequestMapping("/forward_thymeleaf")
    public String forwrad_thyleaf()
    {
        return "forward:/test_thymeleaf";
    }

会寻找有 @RequestMapping("/test_thymeleaf")的控制方法,用thymeleaf解析该方法的返回值,得出文件的路径,并请求转发跳转至该页面

2.当以redirect为前缀时,创建internalsersourceview视图,此时不会直接被thymeleaf解析,而是将redirect去掉,寻找控制器的value一样的方法,用thymeleaf解析该方法的返回值,并重定向访问该页面

 @RequestMapping("/forward_thymeleaf")
    public String forwrad_thyleaf()
    {
        return "redirect:/test_thymeleaf";
    }

会寻找有 @RequestMapping("/test_thymeleaf")的控制方法,用thymeleaf解析该方法的返回值,得出文件的路径,并请求重定向至该页面-

package org.hxut.rj1192.zyk;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ViewController {
    @RequestMapping("/test_thymeleaf")
    public String thyleaf()
    {
        return "test_restful";
    }
    @RequestMapping("/")
    public String thyleafsucess()
    {
        return "index";
    }
    @RequestMapping("/forward_thymeleaf")
    public String forwrad_thyleaf()
    {
        return "forward:/test_thymeleaf";
    }
    @RequestMapping("/redirect_thymeleaf")
    public String redirect_thyleaf()
    {
        return "redirect:/test_thymeleaf";
    }
}

 forward和redirect是不管返回值是model modelandview  都可以使用

    @RequestMapping(value = "/update2")
    public ModelAndView after_choose_change(Books books)
    {
        booksServiceimpl.updateBook(books);
        System.out.println("books 这是修改后的books"+books);
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("redirect:/books/allbooks");
        return modelAndView;
    }

4.当我由控制方法跳转到页面时,不需要传递数据,仅仅是告诉thymeleft我跳转的页面(仅有view)时,可以在spring.xml中(视图控制器的xml文件)中写这句,注意

<mvc:annotation-driven/>一定要写,否则其他@requestparam注解会全部失效
    <mvc:view-controller path="/" view-name="index"></mvc:view-controller>
<!--    开启mvc注解驱动-->
    <mvc:annotation-driven/>

 和下面是一样的效果

 @RequestMapping("/")
public String thyleafsucess()
{
   return "index";
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值