概述
在WEB領域,Java也是在不斷的探索和改進,從開始的JSP--->Struts1--->Struts2+Spring--->Spring MVC--->SpringBoot--->Spring Cloud。在WEB領域,Java框架不斷的變化與改進。Spring Boot將Spring MVC所需要的依賴包環境集成到一個大的包環境中,便於快速開發,特別適合構建微服務系統,另外給我們封裝了各種經常使用的套件,比如mybatis、hibernate、redis、mongodb等。由於Java沒有像其他語言(C#)那也具有屬性的操作,Spring結合IOC與AOP等技術將POJO進行注解到上下文,沒有那么繁瑣的XML配置,調用起來靈活方便。本文主要將自己搭建SpringBoot+mybatisplus+thymeleaf的過程記錄下來,便於以后學習使用。
環境
IDEA 2017.02 + Maven +Jdk1.8+Oracle10g
由於SpringBoot集成Tomcat,這里不需要配置Tomcat,直接調試使用即可。
操作
1、利用Maven搭建項目骨架
1.1、 打開新建項目頁面
1.2、選擇Create New Project,后打開響應的創建項目的頁面,選擇Maven,按下圖標准選擇響應的archetype
1.3、輸入響應的項目名稱信息,點擊Next,為了提高項目的構建速度,我們可以直接訪問http://repo1.maven.org/maven2/archetype-catalog.xml,把這個xml下載下來放到本地的maven目錄中,然后在添加一個參數 archetypeCatalog=internal
1.4、 點擊Next-->Finish,即完成項目的構建,Maven構造完成之后的項目結構如下
2、配置項目代碼結構
2.1、這個時候,我們需要在main下面添加文件夾resources,右鍵單擊resources設置為Resources Root
2.2、由於是spring boot 項目,pom.xml的parent必須繼承spring-boot-starter-parent,同時需要引用spring-boot-starter-web包,里面整合了Spring MVC依賴的包文件。另外由於要使用mybatis訪問數據庫,所以這里需要加入mybatis-spring-boot-starter和Mybatis-plus的包依賴。pom.xml配置如下
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.justin</groupId> <artifactId>htcspringboot</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>Maven Quick Start Archetype</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> <relativePath /> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> <mybatis-starter-version>1.2.0</mybatis-starter-version> <mybatis.plus.version>2.1.0</mybatis.plus.version> <ojdbc14.version>10.2.0.5.0</ojdbc14.version> <druid.version>1.0.28</druid.version> <spring.boot.version>1.5.2.RELEASE</spring.boot.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <version>${spring.boot.version}</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis-starter-version}</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>${mybatis.plus.version}</version> </dependency> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc14</artifactId> <version>${ojdbc14.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2.3、下面我們需要在Resources的目錄下面,添加application.properties文件,在SpringBoot項目中,系統默認讀取項目下的application.properties的文件,所以名稱不能名錯了;在application.properties添加如下內容
# Tomcat server.tomcat.max-threads=1000 server.tomcat.min-spare-threads=30 server.port=812 #修改Tomcat端口 server.context-path=/htc #修改相對路徑 # 環境 dev|test|pro spring.profiles.active=dev cxf.path=/soap #spring.mvc.view.prefix=/WEB-INF/views/ #spring.mvc.view.suffix=.jsp # Mybatis配置 mybatis.mapperLocations=classpath:/mapper/*.xml #Mybatis項目的映射,默認映射到Class下的mapper目錄下,尋找以Mapper.xml結尾的文件 #mybatis.mapper-locations=classpath:mybatis/mapper/*Mapper.xml #mybatis.mapperLocations=classpath:/mapper/**/*.xml # jackson時間格式化 spring.jackson.time-zone=GMT+8 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss #Spring.thymeleaf #資源文件的約定目錄結構 #Maven的資源文件目錄:/src/java/resources #spring-boot項目靜態文件目錄:/src/java/resources/static #spring-boot項目模板文件目錄:/src/java/resources/templates spring.thymeleaf.cache=false spring.thymeleaf.mode=HTML5 spring.thymeleaf.content-type=text/html spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html
2.4、添加application-dev.properties文件,對照application.properties文件,里面放置數據庫的配置信息
spring.datasource.url=jdbc:oracle:thin:@127.0.0.1:1521:LZSORCL #spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.type=oracle.jdbc.pool.OracleDataSource spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver #db spring.datasource.username=javaAcmemgr spring.datasource.password=javaAcmemgr # 下面為連接池的補充設置,應用到上面所有數據源中 # 初始化大小,最小,最大 spring.datasource.initialSize=20 spring.datasource.minIdle=20 spring.datasource.maxActive=100 # 配置獲取連接等待超時的時間 spring.datasource.maxWait=60000 # 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒 spring.datasource.timeBetweenEvictionRunsMillis=60000 # 配置一個連接在池中最小生存的時間,單位是毫秒 spring.datasource.minEvictableIdleTimeMillis=300000 spring.datasource.validationQuery=SELECT 1 FROM DUAL spring.datasource.testWhileIdle=true spring.datasource.testOnBorrow=false spring.datasource.testOnReturn=false # 打開PSCache,並且指定每個連接上PSCache的大小 spring.datasource.poolPreparedStatements=true spring.datasource.maxPoolPreparedStatementPerConnectionSize=20 # 配置監控統計攔截的filters,去掉后監控界面sql無法統計,'wall'用於防火牆 spring.datasource.filters=stat,wall,log4j # 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄 spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 # 合並多個DruidDataSource的監控數據 #spring.datasource.useGlobalDataSourceStat=true
2.5、現在添加修改Mybatis-plus的配置,里面的具體內容不過解釋,可以參考Mybatis-plus官網文檔
package com.justin.config; import com.baomidou.mybatisplus.MybatisConfiguration; import com.baomidou.mybatisplus.MybatisXMLLanguageDriver; import com.baomidou.mybatisplus.entity.GlobalConfiguration; import com.baomidou.mybatisplus.enums.DBType; import com.baomidou.mybatisplus.plugins.PaginationInterceptor; import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean; import org.apache.ibatis.mapping.DatabaseIdProvider; import org.apache.ibatis.plugin.Interceptor; import org.mybatis.spring.boot.autoconfigure.MybatisProperties; import org.mybatis.spring.boot.autoconfigure.SpringBootVFS; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.ResourceLoader; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import javax.sql.DataSource; @Configuration @EnableConfigurationProperties(MybatisProperties.class) public class MybatisPlusConfig { @Autowired private DataSource dataSource; @Autowired private MybatisProperties properties; @Autowired private ResourceLoader resourceLoader = new DefaultResourceLoader(); @Autowired(required = false) private Interceptor[] interceptors; @Autowired(required = false) private DatabaseIdProvider databaseIdProvider; /** * 配置事務管理器 */ @Bean("transactionManager") @Primary public DataSourceTransactionManager transactionManager() throws Exception{ return new DataSourceTransactionManager(dataSource); } /** * mybatis-plus分頁插件 */ @Bean public PaginationInterceptor paginationInterceptor() { //CachePaginationInterceptor page = new CachePaginationInterceptor(); PaginationInterceptor page = new PaginationInterceptor(); page.setDialectType(DBType.ORACLE.getDb()); return page; } /** * 查詢性能分析 */ /*@Bean public PerformanceInterceptor performanceInterceptor() { //CachePaginationInterceptor page = new CachePaginationInterceptor(); PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor(); //PaginationInterceptor page = new PaginationInterceptor(); return performanceInterceptor; } */ /** * 這里全部使用mybatis-autoconfigure 已經自動加載的資源。不手動指定 * 配置文件和mybatis-boot的配置文件同步 * * @return */ @Bean public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean() { MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean(); mybatisPlus.setDataSource(dataSource); mybatisPlus.setVfs(SpringBootVFS.class); if (StringUtils.hasText(this.properties.getConfigLocation())) { mybatisPlus.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation())); } mybatisPlus.setConfiguration(properties.getConfiguration()); if (!ObjectUtils.isEmpty(this.interceptors)) { mybatisPlus.setPlugins(this.interceptors); } // MP 全局配置,更多內容進入類看注釋 GlobalConfiguration globalConfig = new GlobalConfiguration(); globalConfig.setDbType(DBType.ORACLE.name());//數據庫類型 // ID 策略 AUTO->`0`("數據庫ID自增") INPUT->`1`(用戶輸入ID") ID_WORKER->`2`("全局唯一ID") UUID->`3`("全局唯一ID") globalConfig.setIdType(2); //MP 屬性下划線 轉 駝峰 , 如果原生配置 mc.setMapUnderscoreToCamelCase(true) 開啟,該配置可以無。 globalConfig.setDbColumnUnderline(true); mybatisPlus.setGlobalConfig(globalConfig); MybatisConfiguration mc = new MybatisConfiguration(); // 對於完全自定義的mapper需要加此項配置,才能實現下划線轉駝峰 //mc.setMapUnderscoreToCamelCase(true); mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class); mybatisPlus.setConfiguration(mc); if (this.databaseIdProvider != null) { mybatisPlus.setDatabaseIdProvider(this.databaseIdProvider); } if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) { mybatisPlus.setTypeAliasesPackage(this.properties.getTypeAliasesPackage()); } if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) { mybatisPlus.setTypeHandlersPackage(this.properties.getTypeHandlersPackage()); } if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) { mybatisPlus.setMapperLocations(this.properties.resolveMapperLocations()); } return mybatisPlus; } }
2.6、下面來配置數據庫DAO層和業務邏輯層;新建Pojo文件。這里面用到了Mybatisplus的注解內容
package com.justin.model import com.baomidou.mybatisplus.annotations.TableName; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.justin.com.LongSerializer; import java.io.Serializable; @TableName("TBL_EINVOICE") public class Einvoice implements Serializable { private static final long serialVersionUID = 1L; //id private Long id; public String getInvoicenum() { return invoicenum; } public void setInvoicenum(String invoicenum) { this.invoicenum = invoicenum; } public String getInvoicecode() { return invoicecode; } public void setInvoicecode(String invoicecode) { this.invoicecode = invoicecode; } private String invoicenum; private String invoicecode; /** * 設置:id */ public void setId(Long id) { this.id = id; } /** * 獲取:id */ @JsonSerialize(using = LongSerializer.class) public Long getId() { return id; } } public class LongSerializer extends JsonSerializer { @Override public void serialize(Object value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeString(value.toString()); } }
2.7、添加相應DAO,代碼如下,切記EInvoiceMapper要繼承BaseMapper<T>類型,這樣EInvoiceMapper即可實現里面的諸多方法,比如CRUD
package com.justin.dao; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.justin.model.Einvoice; import org.apache.ibatis.annotations.Param; public interface EInvoiceMapper extends BaseMapper<Einvoice> { // Integer countBy(); void updatenum(@Param("INUM") String Invoicenum,@Param("ICODE") String Invoicecode); }
同時我們需要在Resources->Mapper目錄下,新建EInvoiceMapper.xml文件,當然Mapper里面節點,可以不用配置映射內容項;如果配置了則要和EInvoiceMapper.java保持一致;
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.justin.dao.EInvoiceMapper"> <!--<select id="countBy" resultType="int">--> <!--SELECT count(ID) FROM TBL_EINVOICE--> <!--</select>--> <update id="updatenum"> UPDATE TBL_EINVOICE SET INVOICENUM=#{INUM} WHERE INVOICECODE=#{ICODE} </update> </mapper>
2.8、現在配置業務邏輯層的Service代碼,新建EinvoiceService.java文件,內容如下,特別注意需要繼承由Mybatisplus提供的IService<T>接口
package com.justin.serviceapi; import com.baomidou.mybatisplus.service.IService; import com.justin.model.Einvoice; public interface EinvoiceService extends IService<Einvoice> { String GetInvoiceNUmByCode(String InvoiceCode); /** * 插入單個用戶信息 * @param einvoice */ void insertOne(Einvoice einvoice); // //修改代碼結構 void ChangeCode(String num,String Code); }
添加接口實現項EinvoiceServiceImpl,代碼內容如下。特別注意需要繼承由Mybatisplus提供的ServiceImpl類,同時也要實現EinvoiceService的接口
package com.justin.serviceapi.impl; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import com.justin.dao.EInvoiceMapper; import com.justin.model.Einvoice; import com.justin.serviceapi.EinvoiceService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service("einvoiceservice") public class EinvoiceServiceImpl extends ServiceImpl<EInvoiceMapper,Einvoice> implements EinvoiceService { @Autowired private EinvoiceService einvoiceservice; @Override public String GetInvoiceNUmByCode(String InvoiceCode) { EntityWrapper<Einvoice> ew = new EntityWrapper<>(); ew.eq("INVOICECODE", InvoiceCode); Einvoice Result= einvoiceservice.selectOne(ew); if(Result== null){ return "Noting"; } else { return Result.getInvoicenum(); } } @Override public void insertOne(Einvoice einvoice) { einvoiceservice.insert(einvoice); //baseMapper.SumitEinvocie(einvoice.get()); } public void ChangeCode(String num,String Code) { // baseMapper.countBy(); baseMapper.updatenum(num,Code); } }
完成以上配置之后,下面來看Web的入口程序代碼。這個沒什么可說的,需要而別注意啟動程序類需要添加SpringBootApplication標明是springboot的主程序啟動類;添加ResutController注解是為了將Body內容直接輸出到瀏覽器里面;@ResutController和@Controller是有區別的;
package com.justin; import com.justin.model.Einvoice; import com.justin.serviceapi.EinvoiceService; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController @MapperScan("com.justin.dao") public class Application { @Autowired private EinvoiceService einvoiceservice; @RequestMapping("/") public String Greeting() { return "Justin Say Hello WOrld!"; } @RequestMapping("/Add") public String AddEinvoice() { Einvoice Einv=new Einvoice(); Einv.setInvoicecode("98234728"); Einv.setInvoicenum("1111111"); einvoiceservice.insertOne(Einv); return "INser SUCC"; } @RequestMapping("/check/{invoicecode}") public String ShowInfo(@PathVariable("invoicecode") String invoicecode) { return einvoiceservice.GetInvoiceNUmByCode(invoicecode); } @RequestMapping("/Update/{invoicecode}/{invoicenum}") public String UpInfo(@PathVariable("invoicecode") String invoicecode,@PathVariable("invoicenum") String invoicenum) { einvoiceservice.ChangeCode(invoicenum,invoicecode); return "SUCC"; } public static void main(String[] args) { SpringApplication.run(Application.class,args); } }
3、thymeleaf使用
3.1、為了使用thymeleaf提供的模板,我們需要在pom.xml添加spring-boot-starter-thymeleaf依賴包文件,在Springboot中默認規定靜態文件目錄:/src/java/resources/static;模板文件目錄:/src/java/resources/templates目錄下。所以我們在templates里面新建模板文件Eindex.html,內容如下
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Title</title> </head> <body> <p th:text="${Message}"></p> </body> </html>
3.2、為了使用這個模板,我們新建一個控制器HelloController,代碼如下
package com.justin.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import java.util.Map; @Controller @RequestMapping("/HE") public class HelloController { @RequestMapping("/CIndex") public String HIndex(Map<String,Object> map){ map.put("Message","from TemplateController.helloHtml"); return "Eindex"; } }
添加完成之后的,最終的項目結構如下
點擊Application運行之后,在瀏覽器里面輸入 htpp://localhost:812/htc/HE/CIndex 即可預覽自己配置的網頁內容;
thymeleaf能夠自動實現映射,但是有些情況需要注意:
1、如果注解寫的@Controller,則可以在RequestMapping對應方法返回String類型(也就是html對應名稱即可);
@Controller @RequestMapping("msg") public class MessageController { @RequestMapping("/inTimeMsg/{startSendDate}") public String timelyMsg(Map<String, Object> map, @PathVariable("startSendDate") String startSendDate) { //消息日期 if (CommonStringUtils.isNotEmpty(startSendDate)) { Map<String, Object> params = new HashMap<>(); params.put("startSendDate", DateUtil.stringToDate(startSendDate,DateUtil.DF_DATE_TIME)); params.put("recipientid", ContextHelper.getContext().getUserId()); params.put("topnum", 15); params.put("msgtype", 20); List<Message> result = messageService.selectinTimeTopMsg(params); if(result.size()>0) map.put("msgdataList", result); } return "messagelist"; } }
2、如果注解寫的@RestController,則可以在RequestMapping對應方法返回ModelAndView類型(也就是html對應名稱和參數);
@RestController @RequestMapping("msg") public class MessageController { @RequestMapping("/inTimeMsg/{startSendDate}") public ModelAndView timelyMsg(@PathVariable("startSendDate") String startSendDate) { Map<String, Object> map=new HashMap<>(); //消息日期 if (CommonStringUtils.isNotEmpty(startSendDate)) { Map<String, Object> params = new HashMap<>(); params.put("startSendDate", DateUtil.stringToDate(startSendDate,DateUtil.DF_DATE_TIME)); params.put("recipientid", ContextHelper.getContext().getUserId()); params.put("topnum", 15); params.put("msgtype", 20); List<Message> result = messageService.selectinTimeTopMsg(params); if(result.size()>0) map.put("msgdataList", result); } ModelAndView modelAndView=new ModelAndView("messagelist",map); return modelAndView; } }