forward和redirect请求方式

Posted ya-qiang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了forward和redirect请求方式相关的知识,希望对你有一定的参考价值。

之前一直对forward和redirect有点疑问,现在练习一下加深点记忆,理解理解,forward是一次请求,在一个request范围内,而redirect是二次请求

实例:

@Controller
public class ForwardController {
    @RequestMapping("/makeDataForward2.html")
    public String makeDataResponse(Model model,HttpServletRequest request) {
        //在model和request中保存属性
        model.addAttribute("modelData", "model data");
        //得到完整路径
        System.out.println("request.getRequestURL()"+request.getRequestURL());
        //得到除去ip地址的路径
        System.out.println("request.getRequestURI()"+request.getRequestURI());
        request.setAttribute("requestData", "reuqest data");
        //正常响应
        return "success";
    }
    
    //请求转发
    @RequestMapping("/makeDataForward.html")
    public String makeDateForward(Model model,HttpServletRequest request) {
        //在model和request中保存属性
        model.addAttribute("modelData", "model data");
        request.setAttribute("requestData", "reuqest data");
        //请求转发过去后值也传递过去了
        return "forward:toSuccessPage.html";
    }
    @RequestMapping("/makeDataRedirect.html")
    public String makeDataRedirect(Model model, HttpServletRequest request) {
        //在model和request中保存属性
        model.addAttribute("modelData", "model data");
        request.setAttribute("requestData", "reuqest data");
        //重定向
        return "redirect:toSuccessPage2.html";
    }
    
    @RequestMapping("/toSuccessPage.html")
    public String toSuccessPage() {
        return "success";
    }
    
    @RequestMapping("/toSuccessPage2.html")
    public String toSuccessPage2(@ModelAttribute("modelData") String modelData) {
        //@ModelAttribute("modelData")
        //可以获取重定向传递过来的页面的model值,这样在前端就可以获取了
        //如果没有这个参数,页面就获取不到值
        return "success";
    }
    @RequestMapping("/toSuccessPage3.html")
    //RedirectAttributes可以向url传递参数,包括中文
    public String toSuccessPage3(RedirectAttributes redirectAttributes) {
        redirectAttributes.addAttribute("param", "王");
        return "redirect:/WEB-INF/jsp/success.jsp?method=号";
    }
    
}

 

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    model中数据:${modelData}
    <br/>
    <br/>
    request中数据:${requestData }
    <br/>
</body>
</html>

 

以上是关于forward和redirect请求方式的主要内容,如果未能解决你的问题,请参考以下文章

Java Web forward和redirect的区别

Java常见面试题之Forward和Redirect的区别

forward 与 redirect 区别

直接请求转发(Forward)和间接请求转发(Redirect)两种区别?

3--springMVC中redirect重定向和forward转发的区别---一些简单的问题的解决

forward 与 redirect 的区别