SSM框架整合

Posted biaogejiushibiao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SSM框架整合相关的知识,希望对你有一定的参考价值。

1.工具IDEA

2.新建maven工程:

技术分享图片

3.整合所需jar包:maven引入

单元测试:junit

日志:logging,logback,

JSON:jackson-databind

Spring:spring-core,spring-context,spring-test,spring-tx,spring-beans,spring-jdbc,spring-web,spring-webmvc

Mybatis:mybatis,mybatis-spring,pagehelper(分页插件)

mysql:mysql-connector-java

数据源:druid

JSTL:jstl

技术分享图片
<?xml version="1.0" encoding="UTF-8"?>

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>TestSsmProject</groupId>
  <artifactId>TestSsmProject</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>TestSsmProject Maven Webapp</name>
  <!-- FIXME change it to the project‘s website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.2</version>
    </dependency>

    <!-- 实现slf4j接口并整合 -->
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.2.2</version>
    </dependency>

    <!-- JSON -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.8.7</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.2.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.6</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.0.18</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>compile</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.3.10.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.12.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.12.RELEASE</version>
      <scope>test</scope>
    </dependency>
    <!-- mybatis分页插件依赖 -->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>4.0.0</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-jxpath/commons-jxpath -->
    <dependency>
      <groupId>commons-jxpath</groupId>
      <artifactId>commons-jxpath</artifactId>
      <version>1.3</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.ibatis/ibatis-sqlmap -->
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>24.0-jre</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-core-asl -->
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-core-asl</artifactId>
      <version>1.9.13</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>TestOneMaven</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.7.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
    </resources>
  </build>
</project>
pxm.xml

4.配置文件:

日志:

技术分享图片
# Global logging configuration
#在开发环境下日志级别要设置成DEBUG,生产环境设置成info或error
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] --> %m%n
log4j.properties

数据库信息:

技术分享图片
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test_crud?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc.username=root
jdbc.password=root
validationQuery=SELECT 1
db.properties

spring配置文件:

技术分享图片
<?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: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">
    <!--扫描配置文件-->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
    <!--扫描-->
    <context:component-scan base-package="xin.mikey.www">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
    <!--配置数据源-->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close">
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="0" />
        <!-- 连接池最大使用连接数量 -->
        <property name="maxActive" value="20" />
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="0" />
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="60000" />
        <property name="validationQuery" value="${validationQuery}" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <property name="testWhileIdle" value="true" />
        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="25200000" />
        <!-- 打开removeAbandoned功能 -->
        <property name="removeAbandoned" value="true" />
        <!-- 1800秒,也就是30分钟 -->
        <property name="removeAbandonedTimeout" value="1800" />
        <!-- 关闭abanded连接时输出错误日志 -->
        <property name="logAbandoned" value="true" />
        <!-- 监控数据库 -->
        <!-- <property name="filters" value="stat" /> -->
        <property name="filters" value="mergeStat" />
    </bean>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 配置数据库表对应的java实体类 -->
        <property name="typeAliasesPackage" value="xin.mikey.www.pojo" />
        <!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->
        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
        <property name="mapperLocations" value="classpath:xin/mikey/www/mapper/*.xml" />
    </bean>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="xin.mikey.www.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置基于注解的声明式事务 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
applicationContext.xml

SprintMvc配置文件:

技术分享图片
<?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-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <!-- 配置自动扫描的包 -->
    <context:component-scan base-package="xin.mikey.www.controller"></context:component-scan>

    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--
        default-servlet-handler 将在 SpringMVC 上下文中定义一个 DefaultServletHttpRequestHandler,
        它会对进入 DispatcherServlet 的请求进行筛查, 如果发现是没有经过映射的请求, 就将该请求交由 WEB 应用服务器默认的
        Servlet 处理. 如果不是静态资源的请求,才由 DispatcherServlet 继续处理

        一般 WEB 应用服务器默认的 Servlet 的名称都是 default.
        若所使用的 WEB 服务器的默认 Servlet 名称不是 default,则需要通过 default-servlet-name 属性显式指定

    -->
    <mvc:default-servlet-handler/>

    <mvc:annotation-driven/>

    <!--<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">-->
        <!--<property name="converters">-->
            <!--<set>-->
                <!--<ref bean="employeeConverter"/>-->
            <!--</set>-->
        <!--</property>-->
    <!--</bean>-->
    <!--<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">-->
        <!--<property name="basename" value="i18n"></property>-->
    <!--</bean>-->

    <!--<mvc:view-controller path="/i18n" view-name="i18n"></mvc:view-controller>-->

    <!--<mvc:view-controller path="/i18n2" view-name="i18n2"></mvc:view-controller>-->

    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"
    ></bean>

    <mvc:interceptors>
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
        <!--<bean class="com.mikey.www.interceptors.FirstInterceptor"></bean>-->

        <!--配置拦截器(不)作用的路径-->
        <!--<mvc:interceptor>-->
            <!--<mvc:mapping path="/emps"/>-->
            <!--<bean class="com.mikey.www.interceptors.SecondInterceptor"></bean>-->
        <!--</mvc:interceptor>-->
    </mvc:interceptors>

    <!--配置MultipartResolver-->
    <!--<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">-->
        <!--<property name="defaultEncoding" value="UTF-8"></property>-->
        <!--<property name="maxUploadSize" value="1024000"></property>-->
    <!--</bean>-->

    <!--配置自定义拦截器-->
    <!--<bean class="com.mikey.www.interceptors.FirstInterceptor"></bean>-->
    <!--&lt;!&ndash;配置使用simplemappingException&ndash;&gt;-->
    <!--<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">-->
        <!--&lt;!&ndash;<property name="exceptionAttribute" value="ex"></property>&ndash;&gt;-->
        <!--<property name="exceptionMappings">-->
            <!--<props>-->
                <!--<prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>-->
            <!--</props>-->
        <!--</property>-->
    <!--</bean>-->

</beans>
springmvc.xml

Mybatis全局配置文件:

技术分享图片
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <typeAliases>
        <package name="mikey.www.pojo"></package>
    </typeAliases>
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->
            <property name="dialect" value="mysql"/>
        </plugin>
    </plugins>
</configuration>
SqlMapConfig.xml

配置web.xml文件:

技术分享图片
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID" version="2.5">

  <!-- 配置 SpringMVC 的 DispatcherServlet -->
  <!-- The front controller of this Spring Web application, responsible for handling all application requests -->

  <!--过滤器解决工程编码-->
  <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>
  </filter-mapping>


  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext</param-value>
  </context-param>
  <servlet>
    <servlet-name>springDispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc/springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <!-- Map all requests to the DispatcherServlet for handling -->
  <servlet-mapping>
    <servlet-name>springDispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!-- 配置 HiddenHttpMethodFilter: 把 POST 请求转为 DELETE、PUT 请求 -->
  <filter>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>

  <!--放行静态资源文件-->
  <filter-mapping>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/js/*</url-pattern>
    <url-pattern>/css/*</url-pattern>
    <url-pattern>/fonts/*</url-pattern>
    <url-pattern>/images/*</url-pattern>
  </servlet-mapping>

</web-app>
web.xml

 

项目结构目录:

技术分享图片

编写mapper接口及映射文件:

技术分享图片
<?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="xin.mikey.www.mapper.UserMapper">
    <!--<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>-->

    <resultMap id="userMap" type="xin.mikey.www.pojo.User">
        <id column="id" property="id"/>
        <result column="user_id" property="userid"/>
        <result column="user_sex" property="sex"/>
        <result column="user_age" property="age"/>
        <result column="user_email" property="email"/>
        <result column="user_name" property="username"/>
        <result column="user_pwd" property="password"/>
    </resultMap>
    <select id="findUserById" parameterType="String" resultMap="userMap">
        SELECT * FROM user WHERE id=#{value}
    </select>

    <insert id="saveUser" parameterType="user" >
        insert user(id,user_id,user_sex,user_age,user_email,user_name,user_pwd) value(#{id},#{userid},#{sex},#{age},#{email},#{username},#{password})
    </insert>
    <select id="getAllUser" resultMap="userMap">
        SELECT * from USER
    </select>
    <select id="findUserByIds" parameterType="int" resultMap="userMap">
        SELECT * FROM user where
        <!--SELECT * FROM `user` WHERE user_id=1 or user_id=2;-->
        <foreach collection="array" item="id" separator="or">
            user_id=#{id}
        </foreach>
    </select>
    <!--update-->
    <update id="updateUser" parameterType="user">
        update user set id=#{id},user_id=#{userid},user_sex=#{sex},user_age=#{age},user_email=#{email},user_name=#{username},user_pwd=#{password} where  id=#{id}
    </update>
    <!--delete-->
    <delete id="deleteUser" parameterType="java.lang.String">
        delete from user where id=#{value}
    </delete>
    <!--userLogin-->
    <select id="userLogin" parameterType="user" resultMap="userMap">
        SELECT * from user where user_email=#{usereamil} and user_pwd=#{password}
    </select>
    <!--rigister-->
    <insert id="userRegister" parameterType="user">
        insert USER(id,user_email,user_pwd) value (#{id},#{email},#{password})
    </insert>
</mapper>
UserMapper.xml
技术分享图片
package xin.mikey.www.mapper;
import org.springframework.stereotype.Repository;
import xin.mikey.www.pojo.User;

import java.util.List;

/**
 * @author Mikey
 * @Title:
 * @Description:
 * @date 2018/10/15 18:34
 * @Version 1.0
 */
@Repository
public interface UserMapper {
   public User findUserById(String id) throws Exception;
   public List<User> findUserByIds(int[] ids) throws Exception;
   public void saveUser(User user) throws  Exception;
   public void deleteUser(String id) throws Exception;
   public void updateUser(User user) throws Exception;
   public List<User> getAllUser() throws Exception;
}
userMapper.java

pojo类:

技术分享图片
package xin.mikey.www.pojo;

import org.springframework.stereotype.Component;

/**
 * @author Mikey
 * @Title:
 * @Description:
 * @date 2018/10/15 18:32
 * @Version 1.0
 */
@Component
public class User {
    private String id;
    private Integer userid;
    private String username;
    private Integer sex;
    private Integer age;
    private String email;
    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;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Integer getUserid() {
        return userid;
    }

    public void setUserid(Integer userid) {
        this.userid = userid;
    }

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=‘" + id + ‘‘‘ +
                ", userid=‘" + userid + ‘‘‘ +
                ", username=‘" + username + ‘‘‘ +
                ", sex=" + sex +
                ", age=" + age +
                ", email=‘" + email + ‘‘‘ +
                ", password=‘" + password + ‘‘‘ +
                ‘}‘;
    }
}
User.java

DAO层:

技术分享图片
package xin.mikey.www.dao.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import xin.mikey.www.dao.UserDao;
import xin.mikey.www.mapper.UserMapper;
import xin.mikey.www.pojo.User;

import java.util.List;

/**
 * @author Mikey
 * @Title:
 * @Description:
 * @date 2018/10/15 19:14
 * @Version 1.0
 */
@Repository
public class UserDaoImpl  implements UserDao {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User findUserById(String id) throws Exception {
        return userMapper.findUserById(id);
    }

    @Override
    public List<User> findUserByIds(int[] ids) throws Exception {
        return userMapper.findUserByIds(ids);
    }

    @Override
    public void saveUser(User user) throws Exception {

        userMapper.saveUser(user);
    }

    @Override
    public void deleteUser(String id) throws Exception {
        userMapper.deleteUser(id);
    }

    @Override
    public void updateUser(User user) throws Exception {
        userMapper.updateUser(user);
    }

    @Override
    public List<User> getAllUser() throws Exception {
        List<User> allUser =userMapper.getAllUser();
        return allUser;
    }

}
UserDaoImpl.java
技术分享图片
package xin.mikey.www.dao;
import org.springframework.stereotype.Repository;
import xin.mikey.www.pojo.User;

import java.util.List;

/**
 * @author Mikey
 * @Title:
 * @Description:
 * @date 2018/10/15 19:13
 * @Version 1.0
 */
@Repository
public interface UserDao{
    public User findUserById(String id) throws Exception;
    public List<User> findUserByIds(int[] ids) throws Exception;
    public void saveUser(User user) throws  Exception;
    public void deleteUser(String id) throws Exception;
    public void updateUser(User user) throws Exception;
    public List<User> getAllUser() throws Exception;
}
UserDao

Service层:

技术分享图片
package xin.mikey.www.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xin.mikey.www.dao.UserDao;
import xin.mikey.www.pojo.User;
import xin.mikey.www.service.UserService;

import java.util.List;

/**
 * @author Mikey
 * @Title:
 * @Description:
 * @date 2018/10/15 19:30
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Override
    public User findUserById(String id) throws Exception {
        return userDao.findUserById(id);
    }

    @Override
    public List<User> findUserByIds(int[] ids) throws Exception {
        return this.userDao.findUserByIds(ids);
    }

    @Override
    public void saveUser(User user) throws Exception {
        this.userDao.saveUser(user);
    }

    @Override
    public void deleteUser(String id) throws Exception {
        this.userDao.deleteUser(id);
    }

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

    @Override
    public List<User> getAllUser() throws Exception {
        return this.userDao.getAllUser();
    }
}
UserServiceImpl.java
技术分享图片
package xin.mikey.www.service;
import org.springframework.stereotype.Service;
import xin.mikey.www.pojo.User;

import java.util.List;

/**
 * @author Mikey
 * @Title:
 * @Description:
 * @date 2018/10/15 19:29
 * @Version 1.0
 */
@Service
public interface UserService {
    public User findUserById(String id) throws Exception;
    public List<User> findUserByIds(int[] ids) throws Exception;
    public void saveUser(User user) throws  Exception;
    public void deleteUser(String id) throws Exception;
    public void updateUser(User user) throws Exception;
    public List<User> getAllUser() throws Exception;
}
UserService.java

Controller层:

技术分享图片
package xin.mikey.www.controller;

import com.sun.org.glassfish.gmbal.ParameterNames;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import xin.mikey.www.pojo.User;

import java.util.List;
import java.util.Map;

/**
 * @author Mikey
 * @Title:
 * @Description:
 * @date 2018/10/15 19:13
 * @Version 1.0
 */
@Controller
public interface UserController {
    /**
     * 通过id查找用户信息
     * @return
     * @throws Exception
     */
    public String findUserById(@RequestParam("userid") String id,Map<String,Object> map) throws Exception;
    public String findUserByIds(@RequestParam("ids") String ids,Map<String,Object> map) throws Exception;
    public String saveUser(User user,Map<String,Object> map) throws  Exception;
    public String deleteUser(String id,Map<String,Object> map) throws Exception;
    public String updateUser(User user,Map<String,Object> map) throws Exception;

    public String userLogin(@RequestParam("eamil") String email,@RequestParam("password") String pwd,Map<String,Object> map);
}
UserController .java
技术分享图片
package xin.mikey.www.controller.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import xin.mikey.www.controller.UserController;
import xin.mikey.www.pojo.User;
import xin.mikey.www.service.UserService;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author Mikey
 * @Title:
 * @Description:
 * @date 2018/10/15 19:32
 * @Version 1.0
 */

@Controller
@SessionAttributes("user")
@RequestMapping("/user")
public class UserControllerImpl implements UserController {
    private String SCU="success";
    @Qualifier("userServiceImpl")
    @Autowired
    private UserService userService;

    @RequestMapping("/loginUI")
    public String loginUI(){
        System.out.println("loginUI");
        return "login";
    }

    @RequestMapping("/findUserById/{id}")
    public String findUserById(@PathVariable("id") String id, Map<String,Object> map) throws Exception {
        User user= this.userService.findUserById(id);
        map.put("user",user);
        return "edit";
    }

    @Override
    @RequestMapping("/findUserByIds")
    public String findUserByIds(String ids, Map<String,Object> map) throws Exception {
//        this.userService.findUserByIds();
    return null;
    }

    @RequestMapping("/addWork")
    public String addWorkUI(){
        return "addwork";
    }
    @Override
    @RequestMapping("/saveUser")
    public String saveUser(User user, Map<String,Object> map) throws Exception {
        user.setId(UUID.randomUUID().toString());
        user.setPassword("000");
        userService.saveUser(user);
        return "redirect:addWork";
    }

    @Override
    @RequestMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id") String id, Map<String,Object> map) throws Exception {
        System.out.println("ID="+id);
        userService.deleteUser(id);
        return "redirect:/user/getAll";
    }

    @Override
    @RequestMapping(value = "/updateUser",method = RequestMethod.PUT)
    public String updateUser(User user, Map<String,Object> map) throws Exception {
        userService.updateUser(user);
        return "redirect:/user/getAll";
    }
    @Override
    @RequestMapping("/login")
    public String userLogin(String email, String pwd, Map<String, Object> map) {
        System.out.println("Message="+email+"//"+pwd);

        return "main";
    }

    @RequestMapping("/getAll")
    public String getAllUser(Map<String,Object> map){
        List<User> list= null;
        try {
            list = userService.getAllUser();
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("users",list);
        return "showAll";
    }

    @RequestMapping("/getAllPage/{str_pageNo}")
    public ModelAndView getAllUserPage(@PathVariable(value = "str_pageNo",required = false) String str_pageNo, Map<String,Object> maps) throws Exception {
        //拿到用户需要的是哪一页的文章数据

        if(str_pageNo == null){
            //开始使用分页插件,准备查询第一页的8条数据
            PageHelper.startPage(1, 8);
        } else{
            //准备查询 第X页 的8条数据
            PageHelper.startPage(Integer.parseInt(str_pageNo), 8);
        }
        //参数Map
        final Map<String,Object> map = Maps.newHashMap();
        //获取所有作者的所有文章
        final List<User> articles = userService.getAllUser();
        //将查询结果放入分页控件中
        final PageInfo<User> pageInfo=new PageInfo<User>(articles);
        //组装数据,在JSP页面可以通过 ${articles} 或者 ${pageInfo}请求获取数据
        map.put("users",articles);
        map.put("pageInfo",pageInfo);
        //返回某个具体的JSP页面,并且携带上map里面的存储的数据
        return new ModelAndView("showAll",map);
    }
}
UserControllerImpl .java

 

以上是关于SSM框架整合的主要内容,如果未能解决你的问题,请参考以下文章

SSM 项目整合详细解读

520前,我放弃陪女朋友时间,被迫写代码:“SSM框架整合+excel文件上传到数据库+数据更新“

SSM框架整合

Java EE互联网轻量级框架整合开发— SSM框架(中文版带书签)原书代码

手把手整合SSM框架

黑马程序员最全SSM框架用户角色案例(SSM整合版)