【SpringMVC04】SpringMVC跳转

实现跳转即实现转发(forward)和重定向(redirect),SpringMVC中在返回值中加入forwardredirect即可实现。

在配置的视图解析器org.springframework.web.servlet.view.InternalResourceViewResolver的父类UrlBasedViewResolver中:

public class UrlBasedViewResolver extends AbstractCachingViewResolver implements Ordered {

	/**
	 * Prefix for special view names that specify a redirect URL (usually
	 * to a controller after a form has been submitted and processed).
	 * Such view names will not be resolved in the configured default
	 * way but rather be treated as special shortcut.
	 */
	public static final String REDIRECT_URL_PREFIX = "redirect:";

	/**
	 * Prefix for special view names that specify a forward URL (usually
	 * to a controller after a form has been submitted and processed).
	 * Such view names will not be resolved in the configured default
	 * way but rather be treated as special shortcut.
	 */
	public static final String FORWARD_URL_PREFIX = "forward:";

可以看到,当SpringMVC发现返回值中带有forwardredirect关键字时,便不再拼接前后缀,此时就需要写出完整的路径

1 转发

转发到JSP页面:

@Controller
@RequestMapping("/jump")
public class JumpController {
    @RequestMapping("/forward-page")
    public String forwardPageTest(){
        System.out.println("forwardPageTest");
        return "forward:/hello2.jsp";
    }
}
  • return "forward:/hello2.jsp";:可以简写为return "hello2";;

转发到其他方法:

@RequestMapping("/forward-method")
public String forwardMethodTest(){
    System.out.println("forwardMethodTest");
    return "forward:/jump/forward-page";
}
  • return "forward:/jump/forward-page";:是绝对路径写法,写成相对路径为:return "forward:forward-page";

    • 相对路径适合在一个类中进行转发;

    • 需要转发至其他类中的方法必须使用绝对路径;

测试:

2 重定向

重定向和转发类似,将转发的forward关键字替换为redirect关键字即可实现重定向,不过需要注意的是:重定向到页面不可以采用简写的方式,简写方式是转发;

Controller:

@RequestMapping("/redirect-page")
public String redirectPageTest(){
    System.out.println("redirectPageTest");
    return "redirect:/hello2.jsp";
}

@RequestMapping("/redirect-method")
public String redirectMethodTest(){
    System.out.println("redirectMethodTest");
    return "redirect:redirect-page";
}

 测试:

3 转发与重定向的选择

由于转发不会改变url路径,所以为了防止请求重复提交:

  • 增删改:重定向跳转;

  • 查询:转发跳转;

版权声明:
作者:jackqiang
链接:http://www.jackqiang.com/framework/springmvc/2090/springmvc_jump/
来源:JackQiang's
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>
文章目录
关闭
目 录