7.重定向与转发

7.重定向与转发

7.1SpringMVC结果跳转方式

页面 : 视图解析器前缀 + viewName + 视图解析器后缀

例如 : /WEB-INF/jsp/ + hello + .jsp

7.2 重定向与转发

1.使用request与response

@Controller
public class TestController{
    //模板URL ,会直接通过 / 的形式绑定a与b
    @GetMapping("test/{a}/{b}")
    public String test(HttpServletRequest request,HttpServletResponse response,@PathVariable int a,@PathVariable String b, Model model) throws IOException {
        //封装数据
        String res = a+b;
        model.addAttribute("msg",res);
        response.sendRedirect("/jsp/hello.jsp");  //通过response转发
        return "hello";
    }
}

2.通过视图解析器

@Controller
public class TestController{
    //模板URL ,会直接通过 / 的形式绑定a与b
    @GetMapping("test/{a}/{b}")
    public String test(@PathVariable int a,@PathVariable String b, Model model) {
        //封装数据
        String res = a+b;
        model.addAttribute("msg",res);
        return "hello";  //直接通过视图解析器转发
    }
}

3.SpringMVC方式,无需视图解析器(把配置文件中的视图解析器注释掉)

  1. 使用全限定名(默认转发)

    @Controller
    public class TestController{
        //模板URL ,会直接通过 / 的形式绑定a与b
        @GetMapping("test/{a}/{b}")
        public String test(@PathVariable int a,@PathVariable String b, Model model) throws IOException {
            //封装数据
            String res = a+b;
            model.addAttribute("msg",res);
            return "/WEB-INF/jsp/hello.jsp"; //直接返回全限定名,DispatcherServlet仍然可以找到资源
        }
    }
    //全限定名默认是转发方式
    
  2. 使用forward、redirect 显示表明

    @Controller
    public class TestController{
        //模板URL ,会直接通过 / 的形式绑定a与b
        @GetMapping("test")
        public String test(Model model) throws IOException {
            //封装数据
            model.addAttribute("msg","hello");
            return "redirect:/index.jsp";  //redirect:重定向
        }
    }
    

4.使用视图解析器时显示表明转发或重定向

默认转发

@Controller
public class TestController{
    //模板URL ,会直接通过 / 的形式绑定a与b
    @GetMapping("test")
    public String test(Model model) throws IOException {
        //封装数据
        model.addAttribute("msg","hello");
        return "redirect:index.jsp"; //指明重定向
    }
}

注意

只要使用了forwardredirect ,就不会走视图解析器 ,因此写中间的名字是不会被找到的,只能写全限定名

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值