springMVC中的跳转方式

springmvc中跳转封装了servlet的forward和redirect

    forward 一次请求 服务器内部跳转 跳转后地址栏不变  可以用request传递数据
    redirect 多次跳转  客户端跳转  跳转后地址栏  不可以用request传递数据

springmvc中的跳转

从controller -> jsp

    forward 默认是forward跳转  return "页面逻辑名"  -> return "index"
    redirect 使用redirect:关键字  return "redirect:页面视图全名" -> return "/index.jsp"
      注意:redirect 跳转不经过视图解析器  所以需要全名

从controller -> controller

    无论是跳转到同一个的controller或者不同的controller都可以直接使用forward:|redirect:
    return "forward:|redirect:/类上的@requestMapping路径/类中方法上的@requestMapping路径"


跳转示例

package com.codegzy.controller;

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

//页面之间的跳转

@Controller
@RequestMapping("/haha")
public class HaHaController {

    @RequestMapping("/test1")
    public String test1(){
        //forward直接跳转到index页面 地址栏不会改变
        System.out.println("test1");
        return "index";
    }

    @RequestMapping("/test2")
    public String test2(){
        //redirect跳转到index页面      地址栏会改变
        //使用redirect跳转不会经过视图解析器
        System.out.println("test2");
        return "redirect:/index.jsp";
    }

    @RequestMapping("/test3")
    public String test3(){
        //一个controller不同方法之间跳转直接使用forward或者redirect
        System.out.println("test3");
        return "forward:/haha/test1";
    }

    @RequestMapping("/test4")
    public String test4(){
        System.out.println("test4");
        return "redirect:/haha/test2";
    }

    @RequestMapping("/test5")
    public String test5(){
        //不同controller之间跳转也是直接使用forward或者redirect
        System.out.println("test5");
        return "forward:/hello";
    }

    @RequestMapping("/test6")
    public String test6(){
        //不同controller之间跳转也是直接使用forward或者redirect
        System.out.println("test6");
        return "redirect:/hello";
    }
}


posted @ 2021-09-02 18:00  code-G  阅读(438)  评论(0编辑  收藏  举报