上一篇文章实现了spring纯注解方式整合mybatis,上一篇连接 https://www.cnblogs.com/jzfanqiejiang/articles/14128551.html
这篇我们实现spring整合springmvc
准备包:
javax.servlet-api 4.0.1
spring-webmvc 5.2.4.RELEASE
jackson-databind 2.12.0
jackson-core 2.12.0
准备好之后先看一遍项目目录吧,因为是接着上一篇的项目继续写的
可以发现只多了一个SpringWebApplnit.java和WebMvcConfig.java和web目录
SpringWebApplnit.java:
package com.hbjt.application; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import javax.servlet.Filter; /** * @Author 于某 */ public class SpringWebAppInit extends AbstractAnnotationConfigDispatcherServletInitializer { //AbstractAnnotationConfigDispatcherServletInitializer //被自动加载负责应用程序中 servlet 上下文中的 DispatcherServlet 和 Spring 其他上下文的配置。 //重写这三个方法(这是我的理解) 具体可以百度,好像是spring实现了WebApplicationInitializer接口,然后servlet3.0就可以搜到然后自动装配 //spring容器 @Override protected Class<?>[] getRootConfigClasses() { return new Class[]{ApplitationJava.class}; } //springmvc容器 @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{WebMvcConfig.class}; } //dispatcherServlet映射关系 @Override protected String[] getServletMappings() { return new String[]{"/"}; } }
WebMvcConfig.java:
package com.hbjt.application; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.validation.MessageCodesResolver; import org.springframework.validation.Validator; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.HandlerMethodReturnValueHandler; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.config.annotation.*; import org.springframework.web.servlet.view.InternalResourceViewResolver; import java.util.List; /** * @Author 于某 */ @Configuration @EnableWebMvc @ComponentScan("com.hbjt.controller") public class WebMvcConfig implements WebMvcConfigurer { //WebMvcConfigurer //web配置器,在springboot中也非常常用,我感觉稍微比WebMvcConfigurationSupport好用一些 @Bean public InternalResourceViewResolver resourceViewResolver() { InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver(); //请求视图文件的前缀地址 internalResourceViewResolver.setPrefix("/jsp/"); //请求视图文件的后缀 internalResourceViewResolver.setSuffix(".jsp"); internalResourceViewResolver.setExposeContextBeansAsAttributes(true); return internalResourceViewResolver; } /** * 视图配置 * * @param registry */ public void configureViewResolvers(ViewResolverRegistry registry) { registry.viewResolver(resourceViewResolver()); } public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } }
这样就搭建好了,只需要自己在controller层创建一个类标注上controller注解就可以使用了