基于springboot框架 和thymleaf模板引擎 理解Redirect和Forward请求转发方式在后台和前台数据的方式

后台控制用户登录的信息

@Controller
public class AdminController {

    @RequestMapping({"/index", "/"})
    public String index(){
        return "index";
    }

    @PostMapping("/login")
    public String login(@RequestParam("userName") String userName,
                        @RequestParam("password") String password,
                        HttpSession session,
                        HttpServletRequest request){
        System.out.println("用户名:" + userName);
        System.out.println("密码:" + password);

        request.getSession().setAttribute("userId", 1);

        session.setAttribute("msg", "session中的属性msg");
        request.setAttribute("ver", "request中的属性ver");

        return "redirect:/success";
    }

    @RequestMapping("/success")
    public String successPage(){
        return "success";
    }

}

index.html页面

        <form th:action="login"  method="post">
            用户名:<input type="text" name="userName"></br>
            密码:<input type="password" name="password"></br>
            <input type="submit" value="登录">
        </form>

        <h1 th:text="${session.msg}"></h1>

success.html页面

        <h1>登录成功</h1>
        <div th:text="${session.userId}"> </div>
        <div th:text="${session.msg}">hhhh</div>
        <div th:text="${#httpServletRequest.getAttribute('ver')}">hhhh</div>
        <div th:text="${#httpServletRequest.getAttribute('userName')}">hhhh</div>
        <div th:text="${#httpServletRequest.getAttribute('interceptor')}">hhhh</div>
@Component
public class AdminLoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器执行。。。");
        HttpSession session = request.getSession();

        if(session.getAttribute("userId") != null){
            request.setAttribute("interceptor", "拦截器已经检验!!!");
            return true;
        }
        request.getSession().setAttribute("msg", "请先登录!!");
        request.getRequestDispatcher(request.getContextPath() + "/index").forward(request, response);
        return false;
    }

}

整个浏览器的大致运行过程
在这里插入图片描述

当后台login方法中

return “redirect:/success”;

则代表重定向,
在request中保存的属性页面获取不到
如下如所示:
在这里插入图片描述

当后台login方法修改为

return “forward:/success”;

前端页面显示如下:
在这里插入图片描述
通过对比可以发现request中保存的属性值可以获取了。

如果大家仔细观察拦截器中的代码,会发现request对象中也存放了属性,而且两种方式都能够获取到“拦截器已经检验”的信息。
这个请求转发会出现我就不解释了,主要解释为什么重定向会出现这种状况。
主要是因为在login方法中request对象中保存的属性,在经过重定向后, 这个对象消失了,会产生一个新的request对象,所以login方法中的属性获取不到,客户端会重新发送请求,但是会被拦截器拦截, 之后拦截器里面的request对象并没有消失。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值