gpt4 book ai didi

java - 如何在 Spring Boot 中使用注释配置 View 解析器?

转载 作者:行者123 更新时间:2023-12-01 18:00:34 34 4
gpt4 key购买 nike

我已经在 DispatcherServlet xml 文件中配置了 View 解析器。但是如何在 Spring Boot 中使用注解配置 View 解析器呢?

最佳答案

来自Spring Boot documentation :

If you want to keep Spring Boot MVC features, and you just want to add additional MVC configuration (interceptors, formatters, view controllers etc.) you can add your own @Configuration class of type WebMvcConfigurerAdapter, but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter or ExceptionHandlerExceptionResolver you can declare a WebMvcRegistrationsAdapter instance providing such components.

If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.

你能做到:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

@Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/");
resolver.setSuffix(".html");
return resolver;
}
}

当然,根据您的实际配置调整前缀和后缀。

<小时/>

编辑以在请求 / 时处理到页面的重定向:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

@Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/");
resolver.setSuffix(".html");
return resolver;
}
// add a mapping for redirection to index when / requested
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/index");
}
}

关于java - 如何在 Spring Boot 中使用注释配置 View 解析器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41322059/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com