开发工具:IntelliJ IDEA 2021.3.3 (Community Edition)
项目结构:
?前端使用了AdminLTE框架
Marven 依赖:spring-webmvc及thymeleaf-spring5
基于注解的方式替代web.xml配置文件
主要有如下几个类:
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class AppInitilizer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{RootConfiguration.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfiguration.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
?@Configuration注解的使用:
/*
* WebConfiguration.java Spring配置类,相当于applicationContext.xml配置文件
* */
@ComponentScan("com.mvc.controller")
@EnableWebMvc
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Bean
public SpringResourceTemplateResolver resourceTemplateResolver(){
SpringResourceTemplateResolver resolver=new SpringResourceTemplateResolver();
resolver.setSuffix(".html");
resolver.setPrefix("/WEB-INF/");
return resolver;
}
@Bean
public SpringTemplateEngine templateEngine(@Autowired ITemplateResolver templateResolver){
SpringTemplateEngine engine= new SpringTemplateEngine();
engine.setTemplateResolver(templateResolver);
System.out.println("SpringTemplateEngine:>>" + engine);
return engine;
}
@Bean
public ThymeleafViewResolver viewResolver(@Autowired SpringTemplateEngine templateEngine){
ThymeleafViewResolver viewResolver= new ThymeleafViewResolver();
viewResolver.setOrder(1);
viewResolver.setCharacterEncoding("UTF-8");
viewResolver.setTemplateEngine(templateEngine);
System.out.println("ThymeleafViewResolver:>>"+templateEngine);
return viewResolver;
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
/*
* 配置访问静态js、css、html
* */
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("dist/**").addResourceLocations("/WEB-INF/dist/");
registry.addResourceHandler("plugins/**").addResourceLocations("/WEB-INF/plugins/");
registry.addResourceHandler("pages/**").addResourceLocations("/WEB-INF/pages/");
registry.addResourceHandler("/*.html").addResourceLocations("/WEB-INF/");
}
}
@Configuration
public class RootConfiguration {
}
新建控制器:
@Controller
public class HomeController {
@RequestMapping("/index")
public ModelAndView Index(){
return new ModelAndView("index");
}
}
?前端访问:http://localhost:8080/index
|