一步一步带你搭建后台管理系统之SSM框架整合

一步一步带你搭建后台管理系统之SSM框架整合
README:本文后端采用 SpringMvc、MyBatis、Spring
由于mybatis最新包对pagehelper会有错误,所以本文未采用最新的依赖。

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.wrpys.ssm</groupId>
  <artifactId>SSM</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>SSM</name>

  <!-- 编码 -->
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  </properties>

  <!--Maven依赖 需要更换可以到http://mvnrepository.com进行查询-->
  <dependencies>

    <!--Spring-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.3.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>4.3.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.3.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.3.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.3.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-mock</artifactId>
      <version>2.0.8</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>4.3.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>4.3.5.RELEASE</version>
    </dependency>

    <!-- mybatis-spring -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>

    <!-- mybatis 出现分页使用异常,极有可能是版本问题-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.2.8</version>
    </dependency>
    <!-- mybatis pagehelper -->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>3.7.3</version>
    </dependency>
    <dependency>
      <groupId>com.github.jsqlparser</groupId>
      <artifactId>jsqlparser</artifactId>
      <version>0.9.1</version>
    </dependency>

    <!--servlet、基本包-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>3.0-alpha-1</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>1.8.10</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.10</version>
    </dependency>
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>2.6</version>
    </dependency>
    <dependency>
      <groupId>dom4j</groupId>
      <artifactId>dom4j</artifactId>
      <version>1.6.1</version>
    </dependency>

    <!--mysql驱动包-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.40</version>
    </dependency>
    <!--dbcp连接池-->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>

    <!--json、基本包-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.23</version>
    </dependency>
    <dependency>
      <groupId>xml-apis</groupId>
      <artifactId>xml-apis</artifactId>
      <version>2.0.2</version>
    </dependency>
    <dependency>
      <groupId>commons-net</groupId>
      <artifactId>commons-net</artifactId>
      <version>3.5</version>
    </dependency>

    <!-- 日志文件管理包 -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.22</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.22</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

    <!-- junit4 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

  </dependencies>

  <!--项目编译及其构建-->
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.4</version>
        <configuration>
          <warName>SSM</warName>
          <!-- <packagingExcludes>
          **/resources/**
      </packagingExcludes> -->
          <webResources>
            <resource>
              <directory>src/main/resources/resources/config</directory>
              <targetPath>WEB-INF/classes/resources/config</targetPath>
              <filtering>true</filtering>
            </resource>
            <resource>
              <directory>src/main/java</directory>
              <includes>
                <include>**/*.xml</include>
              </includes>
              <targetPath>WEB-INF/classes</targetPath>
            </resource>
          </webResources>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <version>2.4.3</version>
        <configuration>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <inherited>true</inherited>
        <extensions>true</extensions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
          <testFailureIgnore>true</testFailureIgnore>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-site-plugin</artifactId>
        <!-- 此处由3.2升级为3.3.原因是maven版本3.1的,需要3,3才能兼容.否则会报错:java.lang.NoClassDefFoundError:
            org/sonatype/aether/graph/DependencyFilter -->
        <version>3.3</version>
        <configuration>
          <locales>zh_CN</locales>
        </configuration>
      </plugin>

    </plugins>
  </build>

</project>

配置文件:


jdbc.properties:

#mysql
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url:jdbc:mysql://localhost/ssm_demo
jdbc.username=root
jdbc.password=123456
jdbc.maxActive=10
jdbc.maxIdle=10
jdbc.maxWait=5000
jdbc.initialSize=5
jdbc.validationQuery=SELECT 1
jdbc.testWhileIdle=true
jdbc.testOnBorrow=true
jdbc.timeBetweenEvictionRunsMillis=3600000
jdbc.numTestsPerEvictionRun=50
jdbc.minEvictableIdleTimeMillis=120000
jdbc.removeAbandoned=true
jdbc.removeAbandonedTimeout=6000000

log4j.properties:

log4j.rootLogger=DEBUG,Console,FILE
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
#File Appender
log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender
log4j.appender.FILE.File=C:/soft/logs/SSM.log
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=[%d{HH:mm:ss,SSS}] [%l] [%t] [%-5p] : %m%n

log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=INFO
log4j.logger.java.sql.Statement=INFO
log4j.logger.java.sql.PreparedStatement=INFO

applicationContext.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"
       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">

    <context:annotation-config />
    <!-- 配置component所在的包,自动加载需要管理的Bean -->
    <context:component-scan base-package="com.wrpys.ssm"></context:component-scan>
    <import resource="spring-mybatis.xml" />

</beans>

spring-mybatis.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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="configProperties"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:resources/config/jdbc.properties</value>
            </list>
        </property>
    </bean>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="initialSize" value="${jdbc.initialSize}"></property>
        <property name="maxActive" value="${jdbc.maxActive}"/>
        <property name="maxIdle" value="${jdbc.maxIdle}"/>
        <property name="maxWait" value="${jdbc.maxWait}"/>
        <property name="validationQuery" value="${jdbc.validationQuery}"></property>
        <property name="testWhileIdle" value="${jdbc.testWhileIdle}"></property>
        <property name="testOnBorrow" value="${jdbc.testOnBorrow}"></property>
        <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}"></property>
        <property name="numTestsPerEvictionRun" value="${jdbc.numTestsPerEvictionRun}"></property>
        <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}"></property>
        <property name="removeAbandoned" value="${jdbc.removeAbandoned}"/>
        <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}"/>
    </bean>

    <!-- myBatis文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath*:com/wrpys/ssm/model/mybatis/*.xml" />
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageHelper">
                    <property name="properties">
                        <value>
                            dialect=mysql
                        </value>
                    </property>
                </bean>
            </array>
        </property>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.wrpys.ssm.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

    <!-- 配置事务管理器 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置事务处理面(事务通知) -->
    <tx:advice id="appAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 配置事务属性 -->
            <!-- 默认值: isolation="DEFAULT" timeout="-1" propagation="REQUIRED" read-only="false" -->
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="batch*" propagation="REQUIRED" />
            <tx:method name="read*" propagation="REQUIRED" read-only="true" />
            <tx:method name="get*" propagation="REQUIRED" read-only="true" />
            <tx:method name="count*" propagation="REQUIRED" read-only="true" />
            <tx:method name="find*" propagation="REQUIRED" read-only="true" />
            <tx:method name="*" read-only="true" />
        </tx:attributes>
    </tx:advice>

    <!-- 配置AOP事务 -->
    <aop:config>
        <!-- 配置事务切点 -->
        <aop:pointcut expression="execution(* com.wrpys.ssm.service.*Service.*(..))"
                      id="appPoint" />
        <!-- 结合事务切点与切面 -->
        <aop:advisor advice-ref="appAdvice" pointcut-ref="appPoint" />
    </aop:config>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <bean id="namedTemplate"
          class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
        <constructor-arg index="0" ref="dataSource"></constructor-arg>
    </bean>

</beans>

rest-servlet.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"
       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.xsd">

    <!-- 自动扫描该包下面的类 -->
    <context:component-scan base-package="com.wrpys.ssm" />

    <mvc:resources location="/common/" mapping="/common/**" />
    <mvc:resources location="/pages/" mapping="/pages/**" />

    <!--默认的mvc注解映射的支持 -->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <ref bean="stringHttpMessageConverter" />
            <ref bean="fastJsonHttpMessageConverter" />
        </mvc:message-converters>
    </mvc:annotation-driven>
    <bean id="stringHttpMessageConverter"
          class="org.springframework.http.converter.StringHttpMessageConverter">
        <constructor-arg value="UTF-8" index="0"></constructor-arg><!--
         避免出现乱码 -->
        <property name="supportedMediaTypes">
            <list>
                <value>text/plain;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <bean id="fastJsonHttpMessageConverter"
          class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>application/json;charset=UTF-8</value>
                <value>text/html;charset=UTF-8</value><!-- 避免IE出现下载JSON文件的情况 -->
            </list>
        </property>
        <property name="features">
            <array value-type="com.alibaba.fastjson.serializer.SerializerFeature">
                <value>WriteMapNullValue</value>
                <value>QuoteFieldNames</value>
                <value>DisableCircularReferenceDetect</value>
            </array>
        </property>
    </bean>

    <!-- Default ViewResolver对模型视图名称的解析即在模型视图名称添加前后缀 -->
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/pages/" />
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>


web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <context-param>
    <param-name>webAppRootKey</param-name>
    <param-value>WeddingPhoto.root</param-value>
  </context-param>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      classpath:/resources/applicationContext.xml
    </param-value>
  </context-param>

  <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:/resources/config/log4j.properties</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- spring字符集过滤器 -->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
  </filter-mapping>

  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:resources/rest-servlet.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <!-- 		<url-pattern>*.do</url-pattern> -->
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

到此SSM框架整合完毕。接下来新建一张表进行基本增删改查的测试。
用户表(t_user):
CREATE TABLE `t_user` (
  `user_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(64) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;

在model包下新建类实体类User:
package com.wrpys.ssm.model;

/**
 * @author wrp
 * @Description com.wrpys.ssm.model.User
 * @Date 2017/1/13
 */
public class User {

    private Integer userId;

    private String userName;

    private Integer age;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
在dao包下新建接口UserDao;
package com.wrpys.ssm.dao;

import com.wrpys.ssm.model.User;

import java.util.List;

/**
 * @author wrp
 * @Description com.wrpys.ssm.dao.UserDao
 * @Date 2017/1/13
 */
public interface UserDao {

    List<User> findUserByParams(User user);

    void createUser(User user);

    void deleteUser(User user);

    void batchDeleteUser(List<Integer> userIds);

    void updateUser(User user);

}
在model.mybatis包下新建mapper文件User.xml:
<?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.wrpys.ssm.dao.UserDao" >

    <sql id="inc_whereClause" >
        <where>
            <if test="userId!=null">
                and user_id = #{userId}
            </if>
            <if test="userName!=null and userName!=''">
                and user_name = #{userName}
            </if>
            <if test="age!=null">
                and age = #{age}
            </if>
        </where>
    </sql>

    <insert id="createUser">
        INSERT INTO t_user(user_name, age) VALUES (#{userName, jdbcType=VARCHAR}, #{age, jdbcType=INTEGER})
    </insert>

    <delete id="deleteUser">
        DELETE FROM t_user
        <include refid="inc_whereClause"/>
    </delete>

    <delete id="batchDeleteUser">
        DELETE FROM t_user
        where user_id in
        <foreach collection="list" item="userId" open="(" close=")" separator=",">
            #{userId}
        </foreach>
    </delete>

    <update id="updateUser">
      UPDATE t_user
      <set>
          <if test="userName!=null">
              user_name = #{userName, jdbcType=VARCHAR},
          </if>
          <if test="age!=null">
              age = #{age, jdbcType=INTEGER},
          </if>
      </set>
      where user_id = #{userId}
    </update>

    <select id="findUserByParams" resultType="com.wrpys.ssm.model.User">
        SELECT user_id as userId, user_name as userName, age as age
        from t_user
        <include refid="inc_whereClause"/>
    </select>


</mapper>
在service新建接口UserService:
package com.wrpys.ssm.service;

import com.wrpys.ssm.common.PageInfo;
import com.wrpys.ssm.model.User;

import java.util.List;

/**
 * @author wrp
 * @Description com.wrpys.ssm.service.UserService
 * @Date 2017/1/13
 */
public interface UserService {

    void findUser(PageInfo pageInfo, User user);

    void createUser(User user);

    void deleteUser(User user);

    void batchDeleteUser(List<Integer> userIds);

    void updateUser(User user);

}
在service.impl包下新建类UserServiceImpl:
package com.wrpys.ssm.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wrpys.ssm.common.PageInfo;
import com.wrpys.ssm.dao.UserDao;
import com.wrpys.ssm.model.User;
import com.wrpys.ssm.service.UserService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author wrp
 * @Description com.wrpys.ssm.service.impl.UserServiceImpl
 * @Date 2017/1/13
 */
@Service
public class UserServiceImpl implements UserService {

    Log logger = LogFactory.getLog(UserServiceImpl.class);

    @Autowired
    private UserDao userDao;

    @Override
    public void findUser(PageInfo pageInfo, User user) {
        logger.info("findUser pageInfo:"+ JSON.toJSONString(pageInfo));
        Page<?> page = PageHelper.startPage(pageInfo.getPageNumber(), pageInfo.getPageSize());
        pageInfo.setRows(userDao.findUserByParams(user));
        pageInfo.setTotal(page.getTotal());
    }

    @Override
    public void createUser(User user) {
        userDao.createUser(user);
    }

    @Override
    public void deleteUser(User user) {
        userDao.deleteUser(user);
    }

    @Override
    public void batchDeleteUser(List<Integer> userIds) {
        userDao.batchDeleteUser(userIds);
    }

    @Override
    public void updateUser(User user) {
        userDao.updateUser(user);
    }

}
在ctroller包下先建类UserCtr:
package com.wrpys.ssm.controller;

import com.wrpys.ssm.common.Constans;
import com.wrpys.ssm.common.PageInfo;
import com.wrpys.ssm.common.ResultBean;
import com.wrpys.ssm.model.User;
import com.wrpys.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author wrp
 * @Description com.wrpys.ssm.controller.UserCtr
 * @Date 2017/1/13
 */
@Controller
@RequestMapping(value = "user")
public class UserCtr {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "list", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public PageInfo findUser(PageInfo pageInfo, User user) {
        userService.findUser(pageInfo, user);
        return pageInfo;
    }

    @RequestMapping(value = "add", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ResultBean add(User user) {
        ResultBean rb = new ResultBean();
        userService.createUser(user);
        rb.setFlag(Constans.SUCCESS);
        return rb;
    }

    @RequestMapping(value = "delete", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ResultBean delete(User user) {
        ResultBean rb = new ResultBean();
        userService.deleteUser(user);
        rb.setFlag(Constans.SUCCESS);
        return rb;
    }

    @RequestMapping(value = "batchDeleteUser", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ResultBean batchDeleteUser(@RequestParam(value = "userIds") List<Integer> userIds) {
        ResultBean rb = new ResultBean();
        userService.batchDeleteUser(userIds);
        rb.setFlag(Constans.SUCCESS);
        return rb;
    }

    @RequestMapping(value = "update", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ResultBean update(User user) {
        ResultBean rb = new ResultBean();
        userService.updateUser(user);
        rb.setFlag(Constans.SUCCESS);
        return rb;
    }

}
用到的一些公共类:
静态变量Constans:
package com.wrpys.ssm.common;

/**
 * @author wrp
 * @Description com.wrpys.ssm.common.Common
 * @Date 2017/1/16
 */
public class Constans {

    public final static Integer SUCCESS = 1;
    public final static Integer FAIL = 0;


}
分页信息PageInfo:
package com.wrpys.ssm.common;

import java.util.List;

/**
 * @author wrp
 * @Description com.wrpys.ssm.common.PageInfo
 * @Date 2017/1/13
 */
public class PageInfo<T> {

    private Integer pageNumber;

    private Integer pageSize;

    private Long total;

    private List<T> rows;

    public Integer getPageNumber() {
        return pageNumber;
    }

    public void setPageNumber(Integer pageNumber) {
        this.pageNumber = pageNumber;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Long getTotal() {
        return total;
    }

    public void setTotal(Long total) {
        this.total = total;
    }

    public List<T> getRows() {
        return rows;
    }

    public void setRows(List<T> rows) {
        this.rows = rows;
    }
}
返回结果ResultBean:
package com.wrpys.ssm.common;

/**
 * @author wrp
 * @Description com.wrpys.ssm.common.ResultBean
 * @Date 2017/1/16
 */
public class ResultBean {

    private Integer flag;

    private String msg;

    private Object data;

    public Integer getFlag() {
        return flag;
    }

    public void setFlag(Integer flag) {
        this.flag = flag;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

到此t_user表的基本操作已经写完,启动项目,进行测试。
新增:


修改:


分页查询:
测试数据:

结果:


删除:



到此对增删改查的接口测试完毕。后端的SSM框架搭建完成。过程可能会出现各种个样的报错,希望耐心查询资料或者留言,有时间会过来帮忙解答。接下来篇章将进行前端插件的引入及其封装。
源码地址:http://pan.baidu.com/s/1eSEAsuu

发布了7 篇原创文章 · 获赞 4 · 访问量 5万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览