SpringMVC框架学习笔记(4)——结果跳转方式

本文介绍了在SpringMVC框架中如何使用ModelAndView对象、ServletAPI及SpringMVC内置方法来实现视图的渲染、重定向和转发。通过具体代码示例展示了不同场景下视图操作的具体实现方式。

1.设置ModelAndView对象。根据View和视图解析器跳转到指定页面(视图解析器前缀+viewname+视图解析器后缀)

@Override
public ModelAndView handleRequest(HttpServletRequest req,
        HttpServletResponse resp) throws Exception {
    ModelAndView mv = new ModelAndView();
    mv.setViewName("hello");
    mv.addObject("msg", "first spring mvc app");
    return mv;
}

2.通过ServletAPI对象来实现,不需要配置视图解析器

通过HttpServletRequest输出

resp.getWriter().print("Use httpServletAPI");

通过HttpServletRequest实现重定向

@RequestMapping(value = "/hi.do")
public void hello(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.sendRedirect("hello.jsp");
}

通过HttpServletRequest实现转发

@RequestMapping(value = "/hi.do")
public void hello(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    req.setAttribute("msg", "testRequestDispatcher");
    req.getRequestDispatcher("hello.jsp").forward(req, resp);
}

3.通过springMVC来实现重定向和转发

转发

@RequestMapping("/hi2")
public String hello2() {
    //转发1
    //return "index";
    //转发2
    return "forward:index.jsp";
}

重定向

@RequestMapping("/hi3.do")
public String hello3(ModelMap map) {
    map.addAttribute("msg", "helloworld");
    return "redirect:index.jsp";
}

 

转载于:https://www.cnblogs.com/huangjian2/p/6650037.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值