1.新建maven Web项目
image
image
选择maven所在目录conf下的settings.xml文件,repository选择maven仓库的路径
image
image
web项目创建成功
image
2.搭建SSM代码目录框架
2.1创建项目代码目录
src的main下新建resources,在resources目录下右键->Mark Directory as->resourcesRoot,然后在src下新建java目录,在java目录下右键->Mark Directory as->Sourcse Root,然后在java下新建包
com.noah.contacts.bean -------->实体对象,对应数据库中的表
com.noah.contacts.controller -------->web 接口路由控制
com.noah.contacts.service -------->web 服务
com.noah.contacts.dao -------->数据库访问
com.noah.contacts.mapper -------->数据库到实体映射
com.noah.contacts.swagger -------->swagger API框架
image
2.2修改pom.xml
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
noah
WebTest
1.0-SNAPSHOT
war
WebTest Maven Webapp
http://www.example.com
UTF-8
UTF-8
4.2.5.RELEASE
3.2.8
8.0.11
1.7.7
1.2.17
javax
javaee-api
7.0
junit
junit
4.12
ch.qos.logback
logback-classic
1.2.2
com.fasterxml.jackson.core
jackson-databind
2.8.7
mysql
mysql-connector-java
8.0.11
runtime
com.mchange
c3p0
0.9.5.2
org.mybatis
mybatis
${mybatis.version}
org.mybatis
mybatis-spring
1.3.1
org.springframework
spring-core
${spring.version}
org.springframework
spring-beans
${spring.version}
org.springframework
spring-context
${spring.version}
org.springframework
spring-jdbc
${spring.version}
org.springframework
spring-tx
${spring.version}
org.springframework
spring-web
${spring.version}
org.springframework
spring-webmvc
${spring.version}
org.springframework
spring-test
${spring.version}
tk.mybatis
mapper
3.3.8
io.springfox
springfox-swagger2
2.7.0
io.springfox
springfox-swagger-ui
2.7.0
WebTest
org.mybatis.generator
mybatis-generator-maven-plugin
1.3.2
src/main/resources/generatorConfig.xml
true
true
Generate MyBatis Artifacts
generate
org.mybatis.generator
mybatis-generator-core
1.3.2
2.3 修改web.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
WebTest
ChatRobot_Alpha_0.0.1
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
encodingFilter
/*
SpringMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-*.xml
1
true
SpringMVC
/
index.jsp
2.4 在resources下新增spring-mvc.xml如下:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
application/json;charset=UTF-8
2.5 在swagger包下新建SwaggerConfig.java文件如下,配置Swagger
package com.noah.contacts.swagger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/*重要!如果你的项目引入junit测试,此处需要使用@WebAppConfiguration,如果没有使用junit使用@Configuration(很多的博客都没有注明这个问题,为此我花了非常多的时间解决问题)*/
@WebAppConfiguration
@EnableSwagger2//重要!
@EnableWebMvc
@ComponentScan(basePackages = "com.XXXXX.control")//扫描control所在的package请修改为你control所在package
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("XXX项目接口文档")
.description("XXX项目接口测试")
.version("1.0.0")
.termsOfServiceUrl("")
.license("")
.licenseUrl("")
.build();
}
}
2.6 在resources下新增mybatis配置文件spring-mybatis.xml如下:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
2.7 在resources目录下新增数据库连接配置文件jdbc.properties如下:
jdbc.driver=com.mysql.cj.jdbc.Driver
#数据库地址
jdbc.url=jdbc:mysql://localhost:3306/contacts?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong
#用户名
jdbc.username=xxxx
#密码
jdbc.password=xxxxxxxxx
#最大连接数
c3p0.maxPoolSize=30
#最小连接数
c3p0.minPoolSize=10
#关闭连接后不自动commit
c3p0.autoCommitOnClose=false
#获取连接超时时间
c3p0.checkoutTimeout=10000
#当获取连接失败重试次数
c3p0.acquireRetryAttempts=2
2.8 在resources目录下添加mybatis自动映射配置(pom.xml中插件中声明的配置文件),MyBatis Generator自动生成实体、mapper和dao层
/p>
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN "
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
driverClass="${jdbc.driver}"
connectionURL="${jdbc.url}"
userId="${jdbc.username}"
password="${jdbc.password}">
targetProject="src/main/java">
targetProject="src/main/java">
targetProject="src/main/java" type="XMLMAPPER">
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false"
>
运行方法:使用maven运行mybatis-generator-maven-plugin插件:工程名->Plugins->mybatis-generator->mybatis-generator:generate->Run Maven Build,这里自动生成了数据库中的User表。
image.png
3.编写测试代码
先把项目的结构晒一下
image.png
3.1 修改User.java ,之前用的mybatis-generator-maven-plugin插件虽然通过配置文件自动生成了 bean、dao、mapper,但是生成的代码看起来不太简洁,后面就改用tk.mybatis的框架(前面的pom.xml中已经集成)
package com.noah.contacts.bean;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
/***
* 表名默认使用类名,驼峰转下划线(只对大写字母进行处理),如UserInfo默认对应的表名为user_info。
* 表名可以使用@Table(name = "tableName")进行指定,对不符合第一条默认规则的可以通过这种方式指定表名.
* 字段默认和@Column一样,都会作为表字段,表字段默认为Java对象的Field名字驼峰转下划线形式.
* 可以使用@Column(name = "fieldName")指定不符合第3条规则的字段名
* 使用@Transient注解可以忽略字段,添加该注解的字段不会作为表字段使用.
* 建议一定是有一个@Id注解作为主键的字段,可以有多个@Id注解的字段作为联合主键.
* 如果是MySQL的自增字段,加上@GeneratedValue(generator = "JDBC")即可。如果是其他数据库,可以参考官网文档。
*/
@Table(name="user")
public class User {
@Id
@Column(name = "_id")
private Long id;
private String name;
private String password;
private String mobile;
@Column(name = "registTime")
private Date registTime;
@Column(name = "lastLoginTime")
private Date lastLoginTime;
@Column(name = "deviceMac")
private String deviceMac;
private String openid;
private String session_key;
public Long get_id() {
return id;
}
public void set_id(Long _id) {
this.id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile == null ? null : mobile.trim();
}
public Date getRegistTime() {
return registTime;
}
public void setRegistTime(Date registTime) {
this.registTime = registTime;
}
public Date getLastLoginTime() {
return lastLoginTime;
}
public void setLastLoginTime(Date lastLoginTime) {
this.lastLoginTime = lastLoginTime;
}
public String getDeviceMac() {
return deviceMac;
}
public void setDeviceMac(String deviceMac) {
this.deviceMac = deviceMac == null ? null : deviceMac.trim();
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid == null ? null : openid.trim();
}
public String getSession_key() {
return session_key;
}
public void setSession_key(String session_key) {
this.session_key = session_key == null ? null : session_key.trim();
}
}
3.2 项目一般会有同一的数据返回格式,这里我定义一个统一的返回对象为BaseResponse,代码如下,里面加入了swagger的描述
package com.noah.contacts.bean;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "通用返回对象" , description = "BaseResponse 为返回的具体的数据对象")
public class BaseResponse {
@ApiModelProperty(value = "成功或异常标志位,1为成功,0为异常",dataType = "Integer",required = true)
private int result;
@ApiModelProperty(value = "描述",dataType = "String",required = true)
private String msg;
@ApiModelProperty
private T data;
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
3.3 删除bean下除了User和BaseResponse外的mybatis-generator-maven-plugin插件生成的其他文件,删除mapper下的文件,修改dao下的UserDao.java如下:
package com.noah.contacts.dao;
import com.noah.contacts.bean.User;
import tk.mybatis.mapper.common.Mapper;
public interface UserDao extends Mapper {
}
3.4 增加UserController.java,IUserService.java,Userservice.java
package com.noah.contacts.controller;
import com.noah.contacts.bean.BaseResponse;
import com.noah.contacts.bean.User;
import com.noah.contacts.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@Controller
@Scope(value="prototype")
@RequestMapping("/user")
@Api(value = "/user",tags = "用户管理接口")
public class UserContorller {
@Resource
private IUserService userService;
@ResponseBody
@RequestMapping(value = "/doLogin", method = RequestMethod.POST)
@ApiOperation(value = "登录", notes = "获取用户信息", httpMethod = "POST")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", name = "username", value = "用户名", required = true, dataType = "String"),
@ApiImplicitParam(paramType = "query", name = "password", value = "密码", required = true, dataType = "String")})
public BaseResponse doLogin(@RequestParam("username") String username, @RequestParam("password") String password) throws Exception {
BaseResponse response = new BaseResponse();
response.setResult(1);
response.setMsg("登录成功");
User user = userService.doLogin(username, password);
response.setData(user);
return response;
}
}
package com.noah.contacts.service;
import com.noah.contacts.bean.User;
public interface IUserService {
public User doLogin(String name, String password);
}
package com.noah.contacts.service;
import com.noah.contacts.bean.User;
import com.noah.contacts.dao.UserDao;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service("IUserService")
public class UserService implements IUserService{
@Resource
UserDao userMapper;
public User doLogin(String name, String password) {
User selectUser = new User();
selectUser.setName(name);
selectUser.setPassword(password);
User result = userMapper.selectOne(selectUser);
return result;
}
}
image.png