springmvc重定向中文路径问题编码踩坑

springmvc的重定向功能,路径中有中文需要用到URLEncoder编码后在重定向路径,但是一直错误;

关键问题是URLEncoder.encode()方法编码路径不能有斜杠“/”,!!!!!!被坑了几个小时。

这里自定义了一个编码方法规避“/”斜杠的问题,例如:“/中文/路径“用这个方法编码之后在redirect重定向,路径才才会正常跳转!!

@GetMapping(value = "/to/{name}" )

public void redirect(@PathVariable("name") String name, HttpServletResponse response) throws IOException {

List<UIFile> uiFiles = uiFileRepository.findAllByName(name);

// 获取最新版本路径

String path = "";

Integer version = 0;

for (UIFile uiFile : uiFiles) {

if(uiFile.getVersion() > version){

version = uiFile.getVersion();

path = uiFile.getPath();

}

}

// 跳转

String encodePath = path + "/index.html";

String u = urlEncode(encodePath);

response.sendRedirect(u);

}

private String urlEncode(String path) throws UnsupportedEncodingException {

String[] pathArray = path.split("/");

StringBuilder stringBuilder = new StringBuilder();

for (String p : pathArray) {

if (p.isEmpty()) continue;

stringBuilder.append("/").append(URLEncoder.encode(p, "UTF-8"));

}

return stringBuilder.toString();

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值