快速搭建web项目
- 创建maven项目
添加依赖:
注意spring和jackson的版本兼容问题
<!--spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring-version}</version>
</dependency>
<!--spring-web-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<!--tomcat-->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>8.5.38</version>
</dependency>
<!--jackson-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.5</version>
</dependency>
新建配置类extend AbstractAnnotationConfigDispatcherServletInitializer的注解快速配置类,
将DispatcherServlet和Spring应用上下文配置到Servlet容器中,
package com.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebInitilaizer extends AbstractAnnotationConfigDispatcherServletInitializer{
/**根上下文中添加配置,定义分层ApplicationContext共享bean,如数据源配置,
*某个DispatcherServlet上下文找不到的配置会从根上下文中去寻找
*/
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{};//空
}
/**
*DispatcherServlet上下文配置类,未分层就一个上下文
*/
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};//配置类
}
//相当于DispatcherServlet,servlet-mapping的url-pattern
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
原理方面:如果Servlet容器遵循的是Servlet3.0接口,那么Servlet容器加载遵循javax.servlet.ServletContainerInitializer接口的规范,然而spring已经提供了该接口的实现类SpringServletContainerInitializer,方法会寻找WebApplicationInitializer接口实现类添加进初始化集合中
@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer {
@Override
public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext) throws ServletException {
List<WebApplicationInitializer> initializers = new LinkedList<>();
......//寻找WebApplicationInitializer的实现类,然后放入initializers中
AnnotationAwareOrderComparator.sort(initializers);
for (WebApplicationInitializer initializer : initializers) {
initializer.onStartup(servletContext);
}
}
}
然而我们配置的抽象类继承关系如下:
WebApplicationInitializer —> AbstractContextLoaderInitializer —> AbstractDispatcherServletInitializer —> AbstractAnnotationConfigDispatcherServletInitializer
好了,继续我们的全注解配置,再写一个配置类,刚刚getServletConfigClasses()的WebConfig,
1、@Configuration表明配置类
2、@EnableWebMvc启用MVC Java config相当于<mvc:annotation-driven/>
(加载RequestMappingHandlerMapping和RequestMappingHandlerAdapter)
3、@ComponentScan扫描识别我们的controller
4、配置一个视图解析器和handler适配器
package com.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.util.PropertyPlaceholderHelper;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableWebMvc
@ComponentScan(value = "com.*",includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,
value = Controller.class)})
public class WebConfig {
@Bean(name = "internalResourceViewResolver")
public ViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Bean(name = "requestMappingHandlerAdapter")
public HandlerAdapter mappingHandlerAdapter(){
RequestMappingHandlerAdapter handlerAdapter = new RequestMappingHandlerAdapter();
MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
List<MediaType> mediaTypelist = new ArrayList<>();
mediaTypelist.add(MediaType.APPLICATION_JSON_UTF8);
jackson2HttpMessageConverter.setSupportedMediaTypes(mediaTypelist);
handlerAdapter.getMessageConverters().add(jackson2HttpMessageConverter);
return handlerAdapter;
}
}
有了这两个配置类,接下来就可以写controller(忽略@Api、@ApiOperation注解)
@Controller
@Api(value = "Test User 测试",tags={"用户操作接口"})
public class TestController {
@Autowired
private TestService testService;
@ApiOperation(value="/map",notes="map返回json测试")
@RequestMapping("/map")
@ResponseBody
public Map<String,String> map(){
Map<String,String> map = new HashMap<>();
map.put("key","value");
return map;
}
@RequestMapping("/hello")
public ModelAndView hello(){
ModelAndView mav = new ModelAndView();
mav.setViewName("hello");
return mav;
}
}
配置tomcat服务启动
至此基本的控制器层访问已经可以了,无需xml配置,根据需要可适当增添以下配置类(引入相关的jar包)
配置项:数据源、jdbc、flyway(数据库本版管理,自动刷入sql脚本,默认脚本路径如图,sql命名V+版本+双下划线)
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>4.2.0</version>
</dependency>![在这里插入图片描述](https://img-blog.csdnimg.cn/20190321235101105.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xpbmhhb19vYmo=,size_16,color_FFFFFF,t_70)
package com.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.flywaydb.core.Flyway;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
@Configuration
public class ServiceConfig {
@Autowired
private SystemPropertiesConfig systemPropertiesConfig;
@Bean
public DataSource dataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(systemPropertiesConfig.getJdbcUrl());
dataSource.setUsername(systemPropertiesConfig.getJdbcUserName());
dataSource.setPassword(systemPropertiesConfig.getJdbcPassword());
dataSource.setDriverClassName(systemPropertiesConfig.getJdbcDriver());
return dataSource;
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource){
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
@Bean
public Flyway flyway(DataSource dataSource){
Flyway flyway = new Flyway();
flyway.setDataSource(dataSource);
flyway.setBaselineOnMigrate(true);
flyway.setLocations(systemPropertiesConfig.getFlywayDir());
flyway.migrate();
return flyway;
}
}
配置项:swagger(好用的网页端在线接口api文档)
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
package com.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
@EnableWebMvc
public class Swagger2Config {
@Autowired
private SystemPropertiesConfig systemPropertiesConfig;
private boolean swaggerEnabled ;
@Bean
public Docket createRestApi() {
swaggerEnabled = Boolean.parseBoolean(systemPropertiesConfig.getSwaggerEnabled());
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
// 是否开启
.enable(swaggerEnabled).select()
// 扫描的路径包
.apis(RequestHandlerSelectors.basePackage("com.*"))
// 指定路径处理PathSelectors.any()代表所有的路径
.paths(PathSelectors.any()).build().pathMapping("/");
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SpringMvc-Swagger2集成和使用-test示例")
.description("SpringMvc | swagger")
.contact(new Contact("varCode", "http://localhost:8080/test/", "1375354959@qq.com"))
.version("1.0.0")
.build();
}
}
swagger应用顺带引出mvc对静态资源的配置
1、 configureDefaultServletHandling的configurer.enable();相当于<mvc:default-servet-handler>
将静态资源交给tomcat处理(只能读取webapp下的资源,WEB-INF下的资源还得2);
2、addResourceHandlers看结构就和<mvc:resources mapping="xxx" location="xxx">
一致
package com.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class ResourceHandlerConfig implements WebMvcConfigurer {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){
configurer.enable();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
还有注解整合整合mybatis、说起mg,开源代码生成器持久层基本都是生成mapper文件,需要一套前台页面、js+后端jdbc持久层,下次来个freemarker督促学习共同分享!