SpringMVC入门学习---结果跳转方式

本文详细介绍了在SpringMVC框架中实现结果跳转的多种方式,包括使用ModelAndView对象、ServletAPI对象、转发和重定向等方法,并探讨了视图解析器在不同场景下的应用。

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

在之前的项目中,我们在Controller中设置ModelAndView对象来进行结果的跳转。其实除了这一种方式以外,我们还有其他的方式可以跳转结果。

1.设置ModelAndView对象。

虽然之前已经用过了,但为了巩固一下,我们还是简单提一提吧。

根据View的名称和视图解析器跳转到指定的页面。

@RequestMapping("/hello")
public ModelAndView hello(HttpServletRequest req, HttpServletResponse res) {
	ModelAndView mv=new ModelAndView();
	mv.addObject("msg","hello annotation");
	mv.setViewName("hello");
	return mv;
}
复制代码
2.通过ServletAPI对象实现

用ServletAPI来实现跳转的话,我们就不需要视图解析器了。

a)用HttpServletResponse来进行输出
@RequestMapping("/hello")
public void hello(HttpServletRequest req, HttpServletResponse resp) throws IOException {
	resp.getWriter().println("use httpservlet api");
}
复制代码
b)用HttpServletResponse实现重定向
@RequestMapping("/hello")
public void hello(HttpServletRequest req, HttpServletResponse resp) throws IOException {
	resp.sendRedirect("index.jsp");
}
复制代码

我们要注意的是在maven项目中index.jsp文件是在webapp文件夹中,而Web项目中是在WebRoot文件夹中。

c)通过HttpServletRequest实现转发
@RequestMapping("/hello")
public void hello(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
	req.setAttribute("msg", "use req send message");
	req.getRequestDispatcher("index.jsp").forward(req, resp);
}
复制代码
3.通过springmvc实现转发和重定向---不使用视图解析器

实现转发

//第一种转发方式
@RequestMapping("/hello1")
public String hello() {
	return "index.jsp";
}

//第二种转发方式
@RequestMapping("/hello1")
public String hello() {
	return "forward:index.jsp";
}
复制代码

实现重定向

@RequestMapping("/hello1")
public String hello() {
	return "redirect:index.jsp";
}
复制代码
4.通过springmvc实现转发和重定向---使用视图解析器

实现转发

@RequestMapping("/hello2")
public String hello2() {
	return "hello";
}
复制代码

实现重定向

@RequestMapping("/hello2")
public String hello2() {
	//return "hello";
	return "redirect:hello.do";
}
复制代码

注:重定向"redirect:index.jsp"不需要视图解析器

我们看到的是我们重定向到的是一个hello.do,而不是用重定向的方式去跳转到hello.jsp文件。也就是说我们重定向到的是一个index.jsp文件。

重定向是不会用到视图解析器的。所以用springmvc实现重定向,不管你有没有视图解析器都是没有意义的,因为根本就没有用过。

接下来,就是一个我遇到的小问题,如果我们return一个这个"redirect:hello",也就是不加.do,我们可不可以跳转到index.jsp文件呢?答案是不行。不知道大家记不记得我们在web.xml文件里面配置映射加了一个<url-pattern>*.do</url-pattern>,没错,就是这个拦截了我们的请求。

那么我们关于结果跳转方式的介绍就完成了。

转载于:https://juejin.im/post/5cd581ab6fb9a031ea19e5db

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值