SpringMVC中结果的跳转跳转方式

本文深入探讨了SpringMVC框架下ModelAndView的使用方式,讲解了如何通过设置ModelAndView对象来实现页面跳转。同时,对比了重定向与转发的区别,包括它们在URL变化上的不同表现,并提供了具体的代码示例。

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

ModelAndView
设置ModelAndView对象,根据view的名称,和视图解析器跳到指定的页面
页面:视图解析器前缀(prefix)+viewName+视图解析器后缀(suffix)
controller部分

public class ControllerTest3 implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg","hello controllertest4");
        mv.setViewName("test");
        return mv;
    }
}

xml部分

<bean id="/hello" class="com.superman.controller.ControllerTest3"/>

ServletAPI
1.HttpServletResponse进行输出
2.HttpServletResponse实现重定向
3.HttpServletResponse实现转发

@Controller
public class ResultGo {

    @RequestMapping("/go/1")
    public void Go1(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.getWriter().println("这是result的go1");
    }

    @RequestMapping("/go/2")
    public void Go2(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //重定向
        response.sendRedirect("/index.jsp");
    }


    @RequestMapping("/go/2")
    public void Go3(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //转发
        request.setAttribute("msg","/go/2");
        request.getRequestDispatcher("WEB-INF/test.jsp").forward(request,response);
    }
}

重定向和转发最大却别就是:重定向的url会发生改变,转发的url不会改变
重定向:redirect 转发:forward

@Controller
public class ReturnTest {

    @RequestMapping("/aaa/1")
    public String test1(){
        //转发
        return "/WEB-INF/jsp/test.jsp";
    }

    @RequestMapping("/aaa/2")
    public String test2(){
        //转发
        return "forward:/WEB-INF/jsp/test.jsp";
    }

    @RequestMapping("/aaa/3")
    public String test3(){
        //重定向
        return "redirect:/WEB-INF/jsp/test.jsp";
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值