SpringBoot 重定向请求路径跳转问题(一)

目录

1.刷新时候表单重复提交

2.重定向处理

3.addViewController()方法做路径映射

4.返回路径的思考


1.刷新时候表单重复提交

通过postman工具提交post请求,返回dashboard页面,(图中1注释所示)按F5刷新时候浏览器提示确认重新提交表单,因为发送的是同一个请求,这时候做了一个简单的重定向处理。

@Controller
public class CrudController {
    @PostMapping("/user/login")
    public String login(@RequestParam("username")String userName, @RequestParam("password")String password, Model model){
        HashMap map = new HashMap<>(10);
           if (!StringUtils.isEmpty(userName)&&"123456".equals(password)){
                  //1 刷新时候存在表单重复提交问题
//                  return "dashboard";
                 //2 通过重定向的方式(需要配置路径映射相应视图)
                return "redirect:dashboard";

           }else {
               model.addAttribute("msg","密码错误");
               return "login";
           }
    }
}

2.重定向处理

修改返回值为return "redirect:dashboard" ,通过postman工具提交post请求,返回404.请求路径为/user/dashboard,原因是因为我们没有做路径到视图的一个映射,之前是thymeleaf做的映射,找到了temlates下的dashboard.html。现在我们的请求路径是/user/dashboard,thymeleaf没有做这个路径的映射,因此需要我们自己添加映射的方法。

{
    "timestamp": "2020-04-11T07:30:41.742+0000",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/user/dashboard"
}

3.addViewController()方法做路径映射

两种方式

1.直接把/user/dashboard,映射到templates下的dashborad.html,这个过程中thymelaf帮我们完成了解析映射。

2.通过*/dashboard通配符的方式做映射。

此时通过postman工具提交请求,页面成功访问。

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("login");
        registry.addViewController("*/dashboard").setViewName("dashboard");
        registry.addViewController("user/dashboard").setViewName("dashboard");
    }
}

4.返回路径的思考

到这里重复表单的处理暂时完成了(这时候重复刷新不会提示重复表单,但是也可以通过路径直接访问,最好是使用拦截器拦截请求)。此时我产生了一个问题,为什么返回的路径是/user/dashborad,或者user/login/dashboard ,亦或/dashborad,这个/user是从哪里来的,猜测是从请求当中拿到的。带着这个疑问和思考我修改了请求,把/user/login改成/test/login,提交请求。

{
    "timestamp": "2020-04-11T07:52:41.444+0000",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/test/dashboard"
}

 此时返回路径变为/test/dashborad,修改路径为/login,返回/dashboard,此时可以看出当请求为二层时候,会取第一层的路径拼接重定向的路径,请求为一层时候,直接是/dashboard重定向的路径。那么有三层或者以上的时候呢?

{
    "timestamp": "2020-04-11T07:54:24.144+0000",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/dashboard"
}

当请求分别为/user/test/login时候和/user/test/go/login时候,说明N层的请求会取得前面N-1层的路径加上重定向的路径。

{
    "timestamp": "2020-04-11T07:59:08.299+0000",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/user/test/dashboard"
}
{
    "timestamp": "2020-04-11T08:00:30.793+0000",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/user/test/go/dashboard"
}

 

你可能感兴趣的:(spring,boot)