JAVA WEB快速入门系列之前的相关文章如下:(文章全部本人【梦在旅途原创】,文中内容可能部份图片、代码参照网上资源)
今天是第五篇,也是该系列文章的最后一篇,接上篇《JAVA WEB快速入门之从编写一个基于SpringMVC框架的网站了解Maven、SpringMVC、SpringJDBC》,通过上篇文章的详细介绍,知道如何使用maven来快速构建spring MVC应用,也能够使用spring MVC+springJDBC实现网站开发,而本文所涉及的知识则是在这基础之上继续提升,核心是讲解如何使用spring boot来更快速的构建spring MVC,并通过mybatis及代码生成相关DAO,同时利用VUE前端框架开发前后端分离的网站,用户体验更好,废话不多说,直接进入本文主题。
(提示:本文内容有点长,涉及的知识点也比较多,若是新手建议耐心看完!)
一、创建Spring Boot+SpringMVC空项目
1.1通过https://start.spring.io/官网快速生成一个Spring Boot+SpringMVC空项目,如下图示:
设置后点击页面的生成项目按钮,即可生成并下载spring boot项目代码压缩包,然后使用IDE导入存在的maven project即可。
1.2调整项目,解决一些踩坑点
1.2.1.调整spring boot App启动类(如:SpringbootdemoApplication)到根包目录或在启动类上显式添加@ComponentScan注解,并指定包路径,如下代码所示,cn.zuowenjun.boot是根包目录,其余都是cn.zuowenjun.boot的子包
package cn.zuowenjun.boot;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;//import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication//指定为Spring Boot启动入口,内含多个spring所需要的注解
@MapperScan(basePackages="cn.zuowenjun.boot.mapper")//设置Mybaits扫描的mapper包路径//@ComponentScan(basePackages= {"cn.zuowenjun.controller"})//如果不在根包目录,则需指定spring管理的相关包路径
@EnableTransactionManagement //启动事务管理
public classSpringbootdemoApplication {public static voidmain(String[] args) {
SpringApplication.run(SpringbootdemoApplication.class, args);
}
}
1.2.2.解决POM文件报:
Description Resource Path Location Type
Execution default-resources of goal org.apache.maven.plugins:maven-resources-plugin:3.1.0:resources failed: Unable to load the mojo 'resources' (or one of its required components) from the plugin 'org.apache.maven.plugins:maven-resources-plugin:3.1.0'
直接在POM中添加如下resources依赖:
org.apache.maven.plugins
maven-resources-plugin
2.5
maven-plugin
1.2.3.设置热编译启动模式,以便可以随时更改代码后即时生效
org.springframework.boot
spring-boot-devtools
true
org.springframework.boot
spring-boot-maven-plugin
true
设置后项目的视图就有如下显示效果:
1.3演示请求REST API分别返回JSON、XML
创建好spring boot空项目环境后,我们就可以开始编写相关代码了,在此仅贴出实现了REST API分别响应返回JSON、XML格式的Controller,实现步骤如下:
1.3.1在cn.zuowenjun.boot.controller包中创建DemoController,并编写hellojson、helloxml Action方法,代码如下:
packagecn.zuowenjun.boot.controller;import org.springframework.web.bind.annotation.*;import cn.zuowenjun.boot.domain.*;
@RestControllerpublic classDemoController {
@RequestMapping(value="/hello/json",produces="application/json;charset=utf-8")publicHelloDto hellojson()
{
HelloDto dto=newHelloDto();
dto.setMessage("hello,zuowenjun.cn,hello java spring boot!");returndto;
}
@RequestMapping(value="/hello/xml",produces="text/xml;charset=utf-8")publicHelloDto helloxml()
{
HelloDto dto=newHelloDto();
dto.setMessage("hello,zuowenjun.cn,hello java spring boot!");returndto;
}
}
如上代码简要说明:@RestController相当于是:@Controller、@ResponseBody,这个可以查看@RestController注解类代码就知道;@RequestMapping指定请求映射,其中produces设置响应内容格式(可理解为服务端是生产者,而用户在浏览器端【客户端】是消费端),还有consumes属性,这个是指可接收请求的内容格式(可理解为用户在浏览器端发送请求是消息的生产者,而服务端接收并处理该请求为消息的消费者),当然还有其它一些属性,大家可以参见我上篇文章或网络其它大神的相关文章加以了解。
另外需要注意,默认spring MVC只返回JSON格式,若需返回XML格式,还需添加XML JAR包依赖,如下:(可以看到version这里我指定了版本号区间,表示2.5.0及以上版本都可以,有些依赖spring-boot-starter-parent中都有提前配置依赖管理,我们只需要指定groupId、artifactId即可,version就会使用spring boot中的默认版本,当然也可以强制指定版本)
com.fasterxml.jackson.jaxrs
jackson-jaxrs-xml-provider
[2.5.0,)
由于项目中同时添加JSON及XML的JAR包,按照spring MVC的默认响应处理流程是:如果未指定produces,则当请求的header中指定了accept类型,则自动格式化并返回该accept所需的类型,如果未指定accept类型,则优先是响应XML,当找不到XML依赖包时才会响应JSON,故如果项目中同时有JSON及XML,那么最好显式指定produces或者请求头上指明accept类型 这一点与ASP.NET WEB API原理相同,因为都是符合REST架构风格的。
效果如下:
二、使用Mybatis框架完成Domain层、DAO层(这里是Mapper层) ---提示:由于篇幅有限,只贴出重点能体现不同知识点的代码,其余可以到GITHUB上查看下载源码进行详细了解
2.0:首先在application.properties配置mybatis的相关选项,如下所示:
mybatis.type-aliases-package=cn.zuowenjun.boot.domain #包类型别名,这样在XML中就可以简写成类名
mybatis.config-location=classpath:mybatis/mybatis-config.xml #指定mybatis的配置文件路径
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml #指定mapper XML的存放路径
#这里是使用SQL SERVER,如果是其它DB则使用其它驱动
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.url=jdbc:sqlserver://DBIP:Port;DatabaseName=testDB
spring.datasource.username=dbuser
spring.datasource.password=dbpassword
其次添加mybatis-spring-boot-starter maven依赖,它会自动添加相关的mybatis依赖包,配置如下:
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2
2.1全手写JAVA代码实现Mybatis的CRUD;
2.1.1.在cn.zuowenjun.boot.domain包【实体模型或称领域模型层,这里算不上真正的领域模型,最多算是贫血的领域模型】中定义数据实体模型(Goods:商品信息),代码如下:
packagecn.zuowenjun.boot.domain;importjava.math.BigDecimal;importjava.util.Date;public classGoods {private intid;privateString title;privateString picture;privateBigDecimal price;privateString introduction;private intcategoryId;privateString lastEditBy;privateDate lastEditTime;publicGoods() {
}public Goods(intid,String title,String picture,
BigDecimal price,String introduction,intcategoryId,String lastEditBy,Date lastEditTime) {this.setId(id);this.setTitle(title);this.setPicture(picture);this.setPrice(price);this.setIntroduction(introduction);this.setCategoryId(categoryId);this.setLastEditBy(lastEditBy);this.setLastEditTime(lastEditTime);
}public intgetId() {returnid;
}public void setId(intid) {this.id =id;
}publicString getTitle() {returntitle;
}public voidsetTitle(String title) {this.title =title;
}publicString getPicture() {returnpicture;
}public voidsetPicture(String picture) {this.picture =picture;
}publicBigDecimal getPrice() {returnprice;
}public voidsetPrice(BigDecimal price) {