SpringBoot应用程序中,要去掉重定向之后的浏览器参数,可以通过如下的几种方式来实现。
重定向到一个不带参数的URL
直接重定向到一个不带参数的URL中,这是最简单也是最有效的方式,可以在重定向的时候将参数放在Session中,或者是利用其他存储机制来进行存储,然后再重定向之后的页面中再从存储中去获取到对应的参数并且在重定向页面上进行使用,如下所示。
@Controller
public class MyController {
@GetMapping("/redirectWithParams")
public String redirectWithParams(RedirectAttributes attributes) {
attributes.addFlashAttribute("param1", "value1");
return "redirect:/targetPage";
}
@GetMapping("/targetPage")
public String targetPage(@ModelAttribute("param1") String param1) {
// 使用 param1
return "targetPage";
}
}
使用JavaScript修改URL
除了上面的这种实现方式之外,我们还可以在需要重定向的页面上使用JavaScript来对浏览器中的URL进行判断,然后去掉在URL中不需要的参数再进行跳转操作,如下所示。
<!DOCTYPE html>
<html>
<head>
<title>Target Page</title>
<script type="text/javascript">
window.onload = function() {
var url = window.location.href;
var cleanUrl = url.substring(0, url.indexOf('?'));
window.history.replaceState({}, document.title, cleanUrl);
}
</script>
</head>
<body>
<h1>Target Page</h1>
</body>
</html>
使用Spring Boot的Flash Attributes
既然使用的是SpringBoot框架,那么我们也可以尝试通过SpringBoot中提供的Flash Attributes操作来进行参数携带,这个操作允许在重定向之后保存参数,并且这个参数不会出现在URL中,如下所示。
@Controller
public class MyController {
@GetMapping("/start")
public String start(RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("message", "This is a flash message!");
return "redirect:/end";
}
@GetMapping("/end")
public String end(Model model) {
String message = (String) model.getAttribute("message");
System.out.println(message); // This will print: This is a flash message!
return "endPage";
}
}
总结
以上这些方法都可以有效的去掉重定向之后的浏览器参数,在实际使用过程中还需要开发者选择合适的方式来在自己的应用中使用。