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

栏目: Java · 发布时间: 5年前

内容简介:在之前的项目中,我们在Controller中设置ModelAndView对象来进行结果的跳转。其实除了这一种方式以外,我们还有其他的方式可以跳转结果。虽然之前已经用过了,但为了巩固一下,我们还是简单提一提吧。根据View的名称和视图解析器跳转到指定的页面。

在之前的项目中,我们在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> ,没错,就是这个拦截了我们的请求。

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


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms Unlocked

Algorithms Unlocked

Thomas H. Cormen / The MIT Press / 2013-3-1 / USD 25.00

Have you ever wondered how your GPS can find the fastest way to your destination, selecting one route from seemingly countless possibilities in mere seconds? How your credit card account number is pro......一起来看看 《Algorithms Unlocked》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器