一、本质
1、本质还是两种跳转,即 请求转发和重定向,衍生出四种,分别是:
- 请求转发到页面
- 请求转发到action
- 重定向到页面
- 重定向到action
二、准备页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="js/jquery-3.3.1.js"></script>
</head>
<body>
<a href="${pageContext.request.contextPath}/one.action">1、请求转发到页面</a><br/>
<a href="${pageContext.request.contextPath}/two.action">2、请求转发到action</a><br/>
<a href="${pageContext.request.contextPath}/three.action">3、重定向到页面</a><br/>
<a href="${pageContext.request.contextPath}/four.action">4、重定向到action</a><br/>
<a href="${pageContext.request.contextPath}/five.action">5、跳任意页面</a><br/>
</body>
</html>
三、四种跳转方式
1、请求转发到页面
@RequestMapping("/one")
public String one(){
System.out.println("这是请求转发页面跳转.........");
//默认是请求转发,使用视图解析器拼接前缀后缀进行页面跳转
return "main";
}
2、请求转发到action
@RequestMapping("/two")
public String two(){
System.out.println("这是请求转发action跳转.........");
// /admin/ /other.action .jsp
//forward: 这组字符串可以屏蔽前缀和后缀的拼接.实现请求转发跳转
return "forward:/other.action"; //默认是请求转发,使用视图解析器拼接前缀后缀进行页面跳转
}
@RequestMapping("/other")
public String other(){
System.out.println("进入到OtherController........");
return "main";
}
3、重定向到页面
@RequestMapping("/three")
public String three(){
System.out.println("这是重定向页面.......");
//redirect: 这组字符串可以屏蔽前缀和后缀的拼接.实现重定向跳转
return "redirect:/admin/main.jsp";
}
4、重定向到action
@RequestMapping("/four")
public String four(){
System.out.println("这是重定向action.......");
//redirect: 这组字符串可以屏蔽前缀和后缀的拼接.实现重定向跳转
return "redirect:/other.action";
}
5、额外补充:跳转任意目录下的页面
@RequestMapping("/five")
public String five(){
System.out.println("这是随便跳.......");
return "forward:/fore/login.jsp";
}
四、简单源码分析视图解析器InternalResourceViewResolver
InternalResourceViewResolver类 继承UrlBasedViewResolver
UrlBasedViewResolver类中,包含了前缀、后缀以及重定向和转发的属性
public class UrlBasedViewResolver extends AbstractCachingViewResolver implements Ordered {
public static final String REDIRECT_URL_PREFIX = "redirect:";
public static final String FORWARD_URL_PREFIX = "forward:";
@Nullable
private Class<?> viewClass;
private String prefix = "";
private String suffix = "";
当action重定向或者转发到某个页面地址时,会默认根据配置文件加上前缀和后缀,就像这样
<!--添加视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/admin/"/>
<property name="suffix" value=".jsp"/>
</bean>
如果不想加上该前缀和后缀,此时可以使用视图解析器的静态常量值
redirect和forward,这两个字符串可以屏蔽前缀和后缀的拼接.实现页面的转发和重定向跳转
return "forward:/fore/login.jsp";
或者
return "redirect:/admin/main.jsp";