微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SpringMVC入门学习六----SpringMVC中的转发与重定向

1、转发与重定向

在SpringMVC中,如果当处理器对请求处理完毕后,在不是返回JSON数据的情况下,一般都会跳转到其它的页面,此时有两种跳转方式:请求转发与重定向。在SpringMVC中分别对应forward和redirect这两个关键字。

关键字 描述 SpringMVC实现 原生servlet实现
forward 表示转发 forward:"目标页面"(例如forward:"/WEB_INF/success.jsp") request.getRequestdispatcher("xx.jsp").forward()
redirect 表示重定向 redirect:"目标页面" | redirect:"目标请求" response.sendRedirect("xxx.jsp")

2、SpringMVC转发指令

@RequestMapping("/forward")
public String forward() {
    return "forward:/target.jsp";
}

表示方法执行完成后转发到/target.jsp

3、SpringMVC重定向指令

@RequestMapping("/redirect")
public String redirect() {
    return "redirect:/target.jsp";
}

表示方法执行完成后重定向到/target.jsp。这里重定向中使用的路径和我们以前的写法不同,没有以Web应用名称开头,这是因为SpringMVC会替我们加上

@RequestMapping("/redirect")
public String redirect() {
    return "redirect:/find";
}

表示方法执行完成后重定向到/find请求。

4、使用原生对象完成转发

@RequestMapping("/forward")
public void forward2(HttpServletRequest request, HttpServletResponse response) throws servletexception, IOException {
    request.getRequestdispatcher("/target.jsp").forward(request, response);
}

注意:使用原生request对象执行转发后,handler方法的返回值就必须是void,意思是我们自己指定了响应方式,不需要SpringMVC再进行处理了。一个请求只能有一个响应,不能在handler方法里面给一个,然后SpringMVC框架再给一个

5、使用原生对象完成重定向

@RequestMapping("/redirect")
public void redirect2(HttpServletRequest request, HttpServletResponse response) throws servletexception, IOException {
    response.sendRedirect(request.getcontextpath()+"/target.jsp");
}

使用原生response对象执行重定向后,handler方法的返回值同样需要设置为void,原因同上。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐