一.构建Maven工程
二.添加依赖
4.2.6.RELEASE
3.2.7
5.1.29
org.springframework
spring-core
${spring.version}
org.springframework
spring-web
${spring.version}
org.springframework
spring-webmvc
${spring.version}
org.springframework
spring-context-support
${spring.version}
org.springframework
spring-tx
${spring.version}
org.springframework
spring-aspects
${spring.version}
org.springframework
spring-jdbc
${spring.version}
org.mybatis
mybatis
${mybatis.version}
org.mybatis
mybatis-spring
1.2.2
mysql
mysql-connector-java
${mysql.version}
commons-dbcp
commons-dbcp
1.4
commons-pool
commons-pool
1.6
commons-collections
commons-collections
3.2.1
junit
junit
4.11
test
org.codehaus.jackson
jackson-mapper-asl
1.9.13
com.alibaba
fastjson
1.2.13
log4j
log4j
1.2.14
org.slf4j
slf4j-log4j12
1.7.2
jstl
jstl
1.2
taglibs
standard
1.1.2
io.springfox
springfox-swagger2
2.7.0
io.springfox
springfox-swagger-ui
2.7.0
com.fasterxml.jackson.core
jackson-annotations
2.4.4
com.fasterxml.jackson.core
jackson-databind
2.4.4
com.fasterxml.jackson.core
jackson-core
2.4.4
三.配置swagger2
@EnableWebMvc
@EnableSwagger2
@ComponentScan(basePackages = {"com.zc.web.controller"})
@Configuration
public class SwaggerApiConfig extends WebMvcConfigurationSupport{
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.zc.web.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring 中使用Swagger2构建RESTful APIs")
.termsOfServiceUrl("")
.contact(new Contact("zc", "", "[email protected]") )
.version("1.1")
.build();
}
}
四.创建配置文件
1 点击项目右键->source folder->创建resources文件夹
2 点击resources右键->folder->创建config文件夹
3 新建jdbc.properties配置文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
jdbc.username=root
jdbc.password=root
4 新建log4j.properties配置文件
log4j.rootLogger=debug, console, info, error, timer_info_log, timer_error_log
#Output to console(控制台打印)
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%p %d{yyyy-MM-dd HH:mm:ss} %t %C.%M %L-line %m%n
#Output to file(根据时间输出日志到文件)
log4j.appender.timer_info_log=org.apache.log4j.DailyRollingFileAppender
log4j.appender.timer_info_log.Append=true
log4j.appender.timer_info_log.File=${webapp.root}WEB-INF/logfiles/timer_info/timer_info
log4j.appender.timer_info_log.DatePattern='_'yyyy-MM-dd-HH-mm'.log'
log4j.appender.timer_info_log.Threshold=INFO
log4j.appender.timer_info_log.layout=org.apache.log4j.PatternLayout
log4j.appender.timer_info_log.layout.ConversionPattern=%d - %c [%t] %-5p %c %x %l - %m%n
log4j.appender.timer_error_log=org.apache.log4j.DailyRollingFileAppender
log4j.appender.timer_error_log.Append=true
log4j.appender.timer_error_log.File=${webapp.root}WEB-INF/logfiles/timer_error/timer_error
log4j.appender.timer_error_log.DatePattern='_'yyyy-MM-dd-HH-mm'.log'
log4j.appender.timer_error_log.Threshold=error
log4j.appender.timer_error_log.layout=org.apache.log4j.PatternLayout
log4j.appender.timer_error_log.layout.ConversionPattern=%d - %c [%t] %-5p %c %x %l - %m%n
4 配置spring.xml
5 配置spring-mvc.xml
五.编程demo
接下来给大家写一个简单的新增用户demo(需要其余的demo可以联系我,到时候发给你们):
1 我用的mysql5.7,先在数据库新建一张表
CREATE DATABASE test;
USE test;
DROP TABLE IF EXISTS `user_t`;
CREATE TABLE `user_t` (
`user_id` INT(11) NOT NULL AUTO_INCREMENT COMMENT '编号',
`user_name` VARCHAR(200) DEFAULT NULL COMMENT '姓名',
`PASSWORD` VARCHAR(200) DEFAULT NULL COMMENT '密码',
PRIMARY KEY (`user_id`),
UNIQUE KEY `user_name` (`user_name`)
)COMMENT '测试用户表';
2 现在要写mybatis对应的DaoMapper了:在这里要注意的就是参数对应的jdbcType类型要大写
user_id, user_name, password
insert into user_t
(
user_name,
password
)
values
(
#{user.userName, jdbcType=VARCHAR},
#{user.password, jdbcType=VARCHAR}
)
3 接下来写Dao层接口
package com.zc.dao.user;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface IUserDao {
/**
* 新增用户信息
* @param user
* @return
*/
int addUser(@Param("user")UserVo user);
}
-
创建三个实体类
1)用户对象实体package com.zc.model.user; import com.zc.common.BaseVo; public class UserVo extends BaseVo { private String userId; private String userName; private String password; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
2)UserAddRequestDto请求对象实体
package com.zc.facade.dto.request.user;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiParam;
@ApiModel(description = "新增用户请求实体")
public class UserAddRequestDto {
private static final long serivalVersionUID = 1L;
@ApiParam(value = "用户名", required = false)
private String userName;
@ApiParam(value = "用户密码", required = false)
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
3)UserResponseDto请求对象实体
package com.zc.facade.dto.response.user;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
import com.zc.facade.dto.info.UserDto;
public class UserResponseDto {
private static final long serialVersionUID = 1L;
private UserDto user;
public UserDto getUser() {
return user;
}
public void setUser(UserDto user) {
this.user = user;
}
}
5 创建一个IUserService接口
package com.zc.service;
import com.zc.facade.dto.request.user.UserAddRequestDto;
import com.zc.facade.dto.response.user.UserResponseDto;
public interface IUserService {
/**
* 新增用户
* @param requestDto
* @return
* @throws Exception
*/
UserResponseDto addUser(UserAddRequestDto requestDto);
}
6 创建UserServiceImpl实现类
package com.zc.service.impl;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.zc.common.DataGrid;
import com.zc.dao.user.IUserDao;
import com.zc.facade.dto.request.user.UserAddRequestDto;
import com.zc.facade.dto.response.user.UserResponseDto;
import com.zc.model.user.UserVo;
import com.zc.service.IUserService;
@Service("userService")
public class UserServiceImpl implements IUserService {
private final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
@Resource
private IUserDao userDao;
@Override
public UserResponseDto addUser(UserAddRequestDto requestDto) {
UserResponseDto responseDto = new UserResponseDto();
UserVo user = new UserVo();
user.setUserName(requestDto.getUserName());
user.setPassword(requestDto.getPassword());
try {
int n = userDao.addUser(user);
if(n==1){
System.out.println("新增成功");
}else{
System.out.println("新增失败");
}
} catch (Exception e) {
System.out.println(e.getMessage());
logger.error("保存用户信息异常", e);
}
return responseDto;
}
}
7 创建UserController
package com.zc.web.controller.user;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.zc.facade.dto.request.user.UserAddRequestDto;
import com.zc.facade.dto.response.user.UserResponseDto;
import com.zc.service.IUserService;
import com.zc.web.common.ResponseUser;
import com.zc.web.common.RestMessage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@Api(value = "用户服务",description = "提供RESTful风格API的用户的增删改查服务")
@Controller
@RequestMapping("/user")
public class UserController {
private final static Logger logger = LoggerFactory.getLogger(UserController.class);
@Resource
private IUserService userService;
@ApiOperation(value = "新增", notes = "新增用户")
@RequestMapping(value = "/add/userVo", method = RequestMethod.GET)
@ResponseBody
public RestMessage add(UserAddRequestDto requestDto) {
logger.info("add method start,the parameter is :");
logger.info("requestDto:{},{}", requestDto.getUserName(), requestDto.getPassword());
UserResponseDto responseDto = new UserResponseDto();
responseDto = userService.addUser(requestDto);
return new RestMessage(responseDto);
}
}
8 新增用户demo编写完毕;
9 启动tomcat,因为配置了swagger2,我们用swagger2来测试新增接口:
http://IP:port/{context-path}/swagger-ui.html
例如:http://localhost:8080/test/swagger-ui.html
我的博客
我的博客