Java服务器端编程程序员首页投稿(暂停使用,暂停投稿)

基于Maven的Spring+SpringMvc+Mybatis

2017-09-30  本文已影响304人  形影相随_371e

一.构建Maven工程

二.添加依赖

<properties>
<spring.version>4.2.6.RELEASE</spring.version>
<mybatis.version>3.2.7</mybatis.version>
<mysql.version>5.1.29</mysql.version>
</properties>

    <!-- Spring包 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${spring.version}</version>
</dependency>
<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>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring.version}</version>
</dependency>

<!-- mybatis驱动包 -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>${mybatis.version}</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.2.2</version>
</dependency>

<!-- mysql驱动包 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql.version}</version>
</dependency>

<!-- dbcp数据源 -->
<dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.4</version>
</dependency>
<dependency>
    <groupId>commons-pool</groupId>
    <artifactId>commons-pool</artifactId>
    <version>1.6</version>
</dependency>
<dependency>
    <groupId>commons-collections</groupId>
    <artifactId>commons-collections</artifactId>
    <version>3.2.1</version>
</dependency>

<!-- junit测试包 -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
</dependency>

<!-- json数据 -->
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.13</version>
</dependency>

<!-- log4j日志包 -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.14</version>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.2</version>
</dependency>

<!-- jstl 标签库 -->
<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>
<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>

<!-- swagger -->
<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>
<dependency>  
    <groupId>com.fasterxml.jackson.core</groupId>  
    <artifactId>jackson-annotations</artifactId>  
    <version>2.4.4</version>  
</dependency>  
<dependency>  
    <groupId>com.fasterxml.jackson.core</groupId>  
    <artifactId>jackson-databind</artifactId>  
    <version>2.4.4</version>  
</dependency>  
<dependency>  
    <groupId>com.fasterxml.jackson.core</groupId>  
    <artifactId>jackson-core</artifactId>  
    <version>2.4.4</version>  
</dependency>
</dependencies>

三.配置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", "", "admin@qq.com")  )
            .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

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" 
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

<!-- jdbc配置 -->
<context:property-placeholder location="classpath:config/jdbc.properties" />

<!-- 自动将Service层注入 -->
<context:component-scan base-package="com.zc.service" />

<!-- dbcp数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driver}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    
    <property name="maxActive" value="20" />
    <property name="maxIdle" value="10" />
    <property name="maxWait" value="10000" />
    <property name="defaultAutoCommit" value="false" />     
</bean>

<!-- mybatis的配置文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="mapperLocations" value="classpath:mybatis/*.xml"></property>
</bean>

<!-- spring与mybatis整合配置,扫描所有dao -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.zc.dao"></property>
</bean>
</beans>

5 配置spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
  <beans xmlns="http://www.springframework.org/schema/beans"
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"
xmlns:aop="http://www.springframework.org/schema/aop" 
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
       
 <!-- 扫描controller (controller层注入) -->
 <context:component-scan base-package="com.zc.web.controller" />    
 
 <!-- 启动注解支持 -->
 <mvc:default-servlet-handler/>
 <mvc:annotation-driven />
 
 <!-- 静态资源 -->
 <mvc:resources location="/WEB-INF/js/" mapping="/js/**" />
 <mvc:resources location="/WEB-INF/css/" mapping="/css/**" />
 <mvc:resources location="/WEB-INF/image/" mapping="/image/**"/>
 
 <!-- 视图解析器 -->
 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
    <property name="prefix" value="/WEB-INF/view/"></property>
    <property name="suffix" value=".jsp"></property>
 </bean>
 
 <!-- Enables swgger ui-->
 <mvc:default-servlet-handler/>
 <mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/>
 <mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>
       
</beans>          

五.编程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类型要大写

<?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.zc.dao.user.IUserDao">
<resultMap type="com.zc.model.user.UserVo" id="BaseResultMap">
    <result column="user_id" property="userId" jdbcType="VARCHAR" />
    <result column="user_name" property="userName" jdbcType="VARCHAR" />
    <result column="password" property="password" jdbcType="VARCHAR" />
</resultMap>

<sql id="Base_Column_List">
    user_id, user_name, password
</sql>

<insert id="addUser" parameterType="com.zc.model.user.UserVo">
    insert into user_t
    (
        user_name,
        password
    )
    values
    (
        #{user.userName, jdbcType=VARCHAR},
        #{user.password, jdbcType=VARCHAR}
    )
</insert>
</mapper>

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. 创建三个实体类
    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<UserResponseDto> 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<UserResponseDto>(responseDto);
}

}

8 新增用户demo编写完毕;

9 启动tomcat,因为配置了swagger2,我们用swagger2来测试新增接口:
http://IP:port/{context-path}/swagger-ui.html
例如:http://localhost:8080/test/swagger-ui.html

swagger-1.png swagger-2.png
上一篇下一篇

猜你喜欢

热点阅读