【问题标题】:WebMvcConfigurer not working in spring boot?WebMvcConfigurer 在 Spring Boot 中不起作用?
【发布时间】:2019-11-25 06:08:51
【问题描述】:

我改变了我完美工作的控制器类,它只是为了解决视图解析的目的:

@Controller
public class MyController {

@GetMapping("/signup")
public String signupPage() {
    return "signup";
}

@GetMapping("/login")
public String loginPage() {
    return "login";
}

@GetMapping("/dashboard")
public String dashboardPage() {
    return "dashboard";
}

@GetMapping("/logout")
public String logoutPage() {
    return "redirect:/";
}
}

到一个扩展 WebMvcConfigurer 的类,它具有所有视图解析器,如下所示:

@Configuration
@EnableWebMvc
public class ViewConfig implements WebMvcConfigurer {

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/signup").setViewName("signup");
    registry.addViewController("/login").setViewName("login");
    registry.addViewController("/dashboard").setViewName("dashboard");
    registry.addViewController("/logout").setViewName("redirect:/");
}

这感觉更加简洁和干净。

但是,每当我尝试加载这些页面中的任何一个时,都会出现 405 Method Not Allowed 错误。为什么会这样? spring boot 不支持 WebMvcConfigurer 吗?

【问题讨论】:

    标签: spring-boot spring-mvc


    【解决方案1】:

    这个在Spring Boot Documentation中有提到,在spring mvc部分下可以使用WebMvcConfigurer,但是不需要做@EnableWebMvc

    所以你应该删除@EnableWebMvc 注释!

    @Configuration
    // @EnableWebMvc Remove this!
    public class ViewConfig implements WebMvcConfigurer {
    
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/signup").setViewName("signup");
        registry.addViewController("/login").setViewName("login");
        registry.addViewController("/dashboard").setViewName("dashboard");
        registry.addViewController("/logout").setViewName("redirect:/");
    }
    

    【讨论】:

    • 那么什么时候应该使用@EnableWebMvc注解呢?
    • @YeetCoder 使用此配置,您只需重定向到索引页面。你不注销。
    • @JeetRoy EnableWebMvc 不需要 Spring Boot stackoverflow.com/questions/51008382/…
    猜你喜欢
    • 2021-11-08
    • 2018-09-24
    • 2020-10-31
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 2017-08-26
    相关资源
    最近更新 更多