本文主要是介绍SpringMvc 以配置类的形式代替xml文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、配置类
1.1、创建Mvc 项目之后创建 MyWebApplicationInitializer 类
实现接口 WebApplicationInitializer
public class MyWebApplicationInitializer implements WebApplicationInitializer {@Overridepublic void onStartup(ServletContext servletContext) throws ServletException {//关联AppConfig配置类AnnotationConfigWebApplicationContext context =new AnnotationConfigWebApplicationContext();context.register(AppConfig.class);//前端控制器DispatcherServlet dispatcherServlet = new DispatcherServlet(context);//添加前端控制器到web容器ServletRegistration.Dynamic dynamic =servletContext.addServlet("springmvc", dispatcherServlet);//设置该servlet启动时机 (web容器启动时,实列化servlet)dynamic.setLoadOnStartup(1);//设置servlet的匹配路径dynamic.addMapping("/");//添加编码过滤器servletContext.addFilter("encodingFilter",new CharacterEncodingFilter("UTF-8"));}}
1.2、创建 AppConfig 类
@Configuration
@ComponentScan("com.cxd")
public class AppConfig {@Beanpublic ViewResolver viewResolver() {InternalResourceViewResolver viewResolver =new InternalResourceViewResolver();viewResolver.setPrefix("/WEB-INF/views/");viewResolver.setSuffix(".jsp");return viewResolver;}
}
这样就可以访问页面了
2、用到的jar包
<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>6.1.11</version></dependency><dependency><groupId>jakarta.servlet</groupId><artifactId>jakarta.servlet-api</artifactId><version>6.0.0</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.34</version></dependency></dependencies>
3、常用的jar包以及注解
https://blog.csdn.net/or77iu_N/article/details/141324019?spm=1001.2014.3001.5501
这篇关于SpringMvc 以配置类的形式代替xml文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!