Springboot - 错误页面重定向 - 根据错误码重定向到指定页面

本文介绍了如何在Springboot应用中配置错误页面重定向,通过在public/error目录下放置不同错误码对应的HTML页面,如404.html和500.html,并在templates文件夹下创建通用的error.html,实现根据错误码展示定制化错误页面。
摘要由CSDN通过智能技术生成

Springboot - 错误页面重定向 - 根据错误码重定向到指定页面


  1. 在resources目录下建立文件夹public
  2. 在public目录下建立文件夹error
  3. 在error文件夹下放置404.html,500.html等各种错误页面
  4. 在resources下的templates文件夹下,创建error.html页面

    error.html
    http状态有很多,当遇到一个你没有定义的错误时,会跳转到error.html
    
Spring Boot中,如果你想要在某个特定场景下(比如登录成功、用户注册等)重定向到首页,你可以利用`RedirectView`或者`RedirectToStaticResourceLocation`来实现页面跳转。这里是一个简单的例子: ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; @RestController public class LoginController { @GetMapping("/login") public String loginForm() { return "login"; // 返回登录表单模板 } @PostMapping("/login") public ModelAndView handleLogin(@RequestParam String username, @RequestParam String password) { // 这里假设登录验证通过 if (isValidLogin(username, password)) { // 使用RedirectView重定向 return new ModelAndView("redirect:/"); // 或者使用RedirectToStaticResourceLocation重定向到主页资源 // return new ModelAndView(new RedirectToStaticResourceLocation("/", "index.html")); } else { return new ModelAndView("login", "error", "用户名或密码错误"); } } private boolean isValidLogin(String username, String password) { // 登录逻辑... return true; // 暂时返回true,实际应用中需要验证 } } ``` 在这个例子中,当登录验证通过时,会发送一个HTTP 302状态码(临时重定向)到"/"路径,即重定向到前端的根目录。如果验证失败,可以在视图模型中包含错误信息并保持在同一页面
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

简简单单OnlineZuozuo

感谢哥哥姐姐的打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值