结果跳转方式

结果跳转方式

一、 ModelAndView

1.设置ModelAndView对象,根据view名称,和视图解析器跳转到指定的页面。
页面:{视图解析器前缀}+viewName+{视图解析器后缀}

<!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>

2.编写的对应继承controller接口的类ContollerTest类

public class ControllerTest implements Controller {
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
       //返回一个模型视图对象
       ModelAndView mav = new ModelAndView();
       mav.addObject("msg","ControllerTest1");
       mav.setViewName("test");
       return mav;
  }
}

二、ServletAPI

通过设置ServletAPI , 不需要视图解析器

1、通过HttpServletResponse进行输出

//resp输出
    @RequestMapping("/test/t1")
    public void test1(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.getWriter().println("Hello,test By ServletAPI");
    }

2、通过HttpServletResponse实现重定向

//resp重定向
    @RequestMapping("/test/t2")
    public void test2(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.sendRedirect("/index.jsp");
    }

3、通过HttpServletResponse实现转发

//req转发
    @RequestMapping("/test/t3")
    public void test3(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        req.setAttribute("msg","/test/t3");
        req.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(req,resp);
    }

三、SpringMVC

1.通过SpringMVC来实现转发和重定向,无需视图解析器;

测试前,需要将视图解析器注释掉

@Controller
public class SpringMVCControl {
    //转发一:直接返回转发
    @RequestMapping("/result/t1")
    public String test1(){
        return "/index.jsp";
    }

    //转发二:forword关键字
    @RequestMapping("/result/t2")
    public String test2(){
        return "forward:/index.jsp";
    }

    //重定向:redirect关键字
    @RequestMapping("/result/t3")
    public String test3(){
        return "redirect:/index.jsp";
    }
}

2.通过SpringMVC来实现转发,需要视图解析器;
重定向不需要视图解析器,相当于另一个请求。

@Controller
public class SpringMVCControl2 {
    //转发
    @RequestMapping("/result2/t1")
    public String test1(){

        return "hello";
    }

    //重定向
    @RequestMapping("/result2/t2")
    public String test3(){

        return "redirect:/index.jsp";
        //return "redirect:know.do"; //know.do为另一个请求/
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值