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();
}