Spring-MVC 重定向404和数据丢失问题解决方案


1.转发正常,重定向404,表示不公开的资源
在这里插入图片描述

原因

重定向是对于客户端而言,而转发在服务器内部。重定向是想让客户端去访问指定的地址,而WEB-INF下的文件是受保护的,不可以被外部直接访问到,就会出现以上问题,报出404路径错误。

解决

将要访问的文件放置到WEB-INF外即可

2.重定向数据无法携带
controller层

// 使用Model携带参数会发生数据丢失问题 使用session(会话级别)
@RequestMapping("/redirect")
public String model03(Model model) {
    model.addAttribute("msg", "重定向跳转");
    // 重定向
    return "redirect:/index.jsp";
}

跳转页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>首页</title>
</head>
<body>
<h1>Spring-Controller的首页</h1>
<hr>
<h1>${msg}</h1>
</body>
</html>

在这里插入图片描述

将controller的代码修改如下,用servlet中session来携带数据

// 使用Model携带参数会发生数据丢失问题 使用session(会话级别)
    @RequestMapping("/redirect")
    public String model03(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        session.setAttribute("msg", "重定向跳转");
        // 重定向
        return "redirect:/index.jsp";
    }

再次运行,数据携带成功
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值