為了賬號安全,請及時綁定郵箱和手機立即綁定

java--最新SSM框架整合日記(上篇)

2017.07.24 16:29 14552瀏覽

換了新環境,電腦上真是啥都沒有了,為了測試開發環境而創建了一個SpringDemo項目,想著好久沒有整合過框架了,不如去官網看看最新的在重新整一套,以后用著也方便。
最后面有源碼哦!!
整合版本

  • Spring 4.3.10.RELEASE
  • Mybatis 3.4.4
  • log4j 1.2.17
  • junit 4.12
  • 等等

電腦環境

  • jdk1.8
  • Eclipse Version: Neon.3 Release (4.6.3)
  • maven 3.5.0
  • tomcat 8.5.16
  • mysql
1.創建項目整理目錄結構

首先先新建一個maven項目,目錄結構如下
圖片描述
然后在在src/main/java文件夾中,新建包

  • cn.SpringDemo.model(存放javabean),
  • cn.SpringDemo.model.result(存放ResultDO),
  • cn.springmvc.dao(存放spring與mybatis連接接口),
  • cn.springmvc.service(service接口),
  • cn.springmvc.service.impl(service接口的實現),
  • cn.springmvc.controller(存放控制層controller)

在src/main/resource文件夾中,新建包

  • conf(存放配置文件),
  • mapper(mybatis的mapper文件)

在src/test/java文件夾中,新建包cn.springmvc.test(存放測試文件)

在WEB-INF文件夾下新建jsp文件夾(存放jsp文件)

目錄結構如下圖所示
圖片描述

2.引入需要的依賴包

推薦一個查詢依賴包的網站,是之前在一個視頻里面看到的

http://search.maven.org/

這里面基本上都是我查詢了各個官網選取了相對最新比較穩定的版本

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>SpringDemo</groupId>
    <artifactId>SpringDemo</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringDemo Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <!-- spring版本號 -->
        <spring.version>4.3.10.RELEASE</spring.version>
        <!-- mybatis版本號 -->
        <mybatis.version>3.4.4</mybatis.version>
        <!-- log4j日志文件管理包版本 -->
        <slf4j.version>1.8.0-alpha2</slf4j.version>
        <log4j.version>1.2.17</log4j.version>
    </properties>
    <dependencies>
        <!-- spring核心包 -->
        <!-- springframe start -->
        <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-oxm</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-jdbc</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-aop</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-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- springframe end -->

        <!-- mybatis核心包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <!-- mybatis/spring包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- mysql驅動包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.29</version>
        </dependency>
        <!-- junit測試包 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- 阿里巴巴數據源包 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.2</version>
        </dependency>

        <!-- json數據 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.5.2</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.2</version>
        </dependency>

        <!-- 日志文件管理包 -->
        <!-- log start -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!-- log end -->

        <!--jsp需要包 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>SpringDemo</finalName>
    </build>
</project>

在這里關于json數據的需要注意,我就在這里爬了半天坑

如果是Spring3.X

        <dependency>  
            <groupId>org.codehaus.jackson</groupId>  
            <artifactId>jackson-core-lgpl</artifactId>  
            <version>1.8.1</version>  
         </dependency>  

        <dependency>  
            <groupId>org.codehaus.jackson</groupId>  
            <artifactId>jackson-mapper-lgpl</artifactId>  
            <version>1.8.1</version>  
        </dependency>

如果是Spring4.X

 <dependency>  
    <groupId>com.fasterxml.jackson.core</groupId>  
    <artifactId>jackson-core</artifactId>  
    <version>2.5.2</version>  
</dependency>  

<dependency>  
    <groupId>com.fasterxml.jackson.core</groupId>  
    <artifactId>jackson-databind</artifactId>  
    <version>2.5.2</version>  
</dependency>  
3.配置數據庫連接屬性

首先先創建一個數據庫

springdemo.sql如下,僅供參考

# Host: 127.0.0.1  (Version: 5.5.40)
# Date: 2017-07-24 14:51:02
# Generator: MySQL-Front 5.3  (Build 4.120)

CREATE TABLE `spring_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用戶id',
  `nickname` varchar(25) DEFAULT NULL COMMENT '用戶昵稱',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用戶表';

#
# Data for table "spring_user"
#

conf/ jdbc.properties

jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/springdemo?useUnicode=true&characterEncoding=utf-8
jdbc_username=root
jdbc_password=root
4.配置spring配置文件

conf/spring.xml

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

    <!-- 引入jdbc配置文件 -->
    <context:property-placeholder location="classpath:conf/jdbc.properties"/>

    <!-- 掃描文件(自動將servicec層注入) -->
    <context:component-scan base-package="cn.SpringDemo.service"/>
</beans>

注意上面的www.springframework.org/schema/beans/spring-beans-4.3.xsd,如果不確定后面的版本可以去查看下符合當前版本的,比如訪問
/www.springframework.org/schema/beans/ 可以看到4.3是當前最新的。
后面的全部同這里一樣,注意修改查看
圖片描述

conf/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:p="http://www.springframework.org/schema/p"
  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:util="http://www.springframework.org/schema/util"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.3.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util-4.3.xsd">

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
    destroy-method="close" >
    <property name="driverClassName">
      <value>${jdbc_driverClassName}</value>
    </property>
    <property name="url">
      <value>${jdbc_url}</value>
    </property>
    <property name="username">
      <value>${jdbc_username}</value>
    </property>
    <property name="password">
      <value>${jdbc_password}</value>
    </property>
    <!-- 連接池最大使用連接數 -->
    <property name="maxActive">
      <value>20</value>
    </property>
    <!-- 初始化連接大小 -->
    <property name="initialSize">
      <value>1</value>
    </property>
    <!-- 獲取連接最大等待時間 -->
    <property name="maxWait">
      <value>60000</value>
    </property>
    <!-- 連接池最大空閑 -->
    <property name="maxIdle">
      <value>20</value>
    </property>
    <!-- 連接池最小空閑 -->
    <property name="minIdle">
      <value>3</value>
    </property>
    <!-- 自動清除無用連接 -->
    <property name="removeAbandoned">
      <value>true</value>
    </property>
    <!-- 清除無用連接的等待時間 -->
    <property name="removeAbandonedTimeout">
      <value>180</value>
    </property>
    <!-- 連接屬性 -->
    <property name="connectionProperties">
      <value>clientEncoding=UTF-8</value>
    </property>
  </bean>

    <!-- mybatis文件配置,掃描所有mapper文件 -->
      <bean id="sqlSessionFactory"
          class="org.mybatis.spring.SqlSessionFactoryBean"
          p:dataSource-ref="dataSource"
          p:configLocation="classpath:conf/mybatis-config.xml"
          p:mapperLocations="classpath:mapper/*.xml"/><!-- configLocation為mybatis屬性 mapperLocations為所有mapper-->

   <!-- spring與mybatis整合配置,掃描所有dao -->
 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
        p:basePackage="cn.SpringDemo.dao" 
        p:sqlSessionFactoryBeanName="sqlSessionFactory"/>

   <!-- 對數據源進行事務管理 -->
  <bean id="transactionManager" 
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
        p:dataSource-ref="dataSource"/>
</beans>
5.編寫jsva代碼

cn.SpringDemo.model/User.java

package cn.SpringDemo.model;

import org.springframework.stereotype.Component;

/**
 * 用戶
 * @author yezi
 *
 */
@Component
public class User {

    private int id;
    private String nickname;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getNickname() {
        return nickname;
    }
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", nickname=" + nickname + "]";
    }

}

cn.SpringDemo.dao/UserDAO.java

package cn.SpringDemo.dao;

import java.util.List;

import cn.SpringDemo.model.User;
/**
 * 用戶Dao層
 * @author yezi
 *
 */
public interface UserDAO {

    /**
     * 添加一個用戶
     * @param user
     * @return
     */
    public int insertUser(User user);

    /**
     * 獲取全部用戶
     * @return
     */
    public List<User> getAllUsers();
}

cn.SpringDemo.model.result/ResultDO.java

package cn.SpringDemo.model.result;

/**
 * 
 * @author yezi
 *
 * @param <T>
 */
public class ResultDO<T> {
    private String message;
    private T result;
    private boolean success;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getResult() {
        return result;
    }

    public void setResult(T result) {
        this.result = result;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

}

cn.SpringDemo.service/UserService.java

package cn.SpringDemo.service;

import java.util.List;

import cn.SpringDemo.model.User;
import cn.SpringDemo.model.result.ResultDO;
/**
 * 用戶服務接口層
 * @author yezi
 *
 */
public interface UserService {

    /**
     * 添加一個用戶
     * @param user
     * @return
     */
    public ResultDO insertUser(User user);

    /**
     * 獲取全部用戶列表
     * @return
     */
    public ResultDO<List<User>> getAllUsers();
}

cn.SpringDemo.service.impl/UserServiceImpl.java

package cn.SpringDemo.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.SpringDemo.dao.UserDAO;
import cn.SpringDemo.model.User;
import cn.SpringDemo.model.result.ResultDO;
import cn.SpringDemo.service.UserService;

/**
 * 用戶服務實現層
 * @author yezi
 *
 */
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDAO userDAO;

    /**
     * 添加一個用戶
     */
    @Override
    public ResultDO insertUser(User user) {
        // TODO Auto-generated method stub
        boolean success = false;
        ResultDO resultDO = new ResultDO();
        if(user!=null){
            if(userDAO.insertUser(user)==1){
                success=true;
                resultDO.setMessage("插入成功!!");
            }else{
                resultDO.setMessage("插入失敗!!");
            }
        }else{
            resultDO.setMessage("傳入空值!!");
        }
        resultDO.setSuccess(success);
        return resultDO;
    }

    /**
     * 獲取全部用戶
     */
    @Override
    public ResultDO<List<User>> getAllUsers() {
        // TODO Auto-generated method stub
        ResultDO<List<User>> resultDO = new ResultDO<List<User>>();
        boolean success = false;
        List<User> users = userDAO.getAllUsers();
        if(!users.isEmpty()){
            resultDO.setResult(users);
            resultDO.setMessage("獲取用戶列表成功!!");
            success=true;
        }else{
            resultDO.setMessage("獲取用戶列表為空!!");
        }
        resultDO.setSuccess(success);
        return resultDO;
    }

}
6.mybatis配置

conf/mybatis-config.xml

<?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>
         <!-- <typeAlias alias="User" type="cn.SpringDemo.model.User" /> -->
         <!-- 自動掃描整個包 -->
         <package name="cn.SpringDemo.model"/> 
    </typeAliases> 

    <!-- 映射map -->
    <mappers>
    </mappers>

    <!-- 配置全局屬性 -->

    <!-- <settings>
        使用JDBC的getGeneratedKeys獲取自增主鍵
        <setting value="true" name="useGeneratedKeys" />
        <setting value="true" name="useColumnLabel" />
        <setting value="true" name="mapUnderscoreToCamelCase" />
    </settings> -->

</configuration>

mapper/UserMapper.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="cn.SpringDemo.dao.UserDAO">
    <resultMap id="UserMap" type="cn.SpringDemo.model.User">
        <id column="id" property="id" />
        <result column="nickname" property="nickname" />
    </resultMap>

    <!--添加一個用戶 -->
    <insert id="insertUser" parameterType="User" keyProperty="id">
        insert into spring_user(
        nickname
        )
        values
        (
        #{nickname}
        )
    </insert>

    <!-- 查詢全部用戶 -->
    <select id="getAllUsers" resultMap="UserMap">
        select id,nickname from spring_user
    </select>

</mapper>

以上完成了插入用戶和查詢全部用戶的功能!!

7 . junit測試

cn.SpringDemo.test/UserTest.java

package cn.SpringDemo.test;

import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.SpringDemo.model.User;
import cn.SpringDemo.service.UserService;

public class UserTest {

private UserService userService;

    @Before
    public void before(){                                                                    
        @SuppressWarnings("resource")
        ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"classpath:conf/spring.xml"
                ,"classpath:conf/spring-mybatis.xml"});
        userService = (UserService) context.getBean("userServiceImpl");
    }

    /**
     * 添加用戶
     */
    @Test
    public void addUser(){
        User user = new User();
        user.setNickname("yezi");
        System.out.println(userService.insertUser(user).getMessage());
    }

    /**
     * 獲取全部用戶
     */
    @Test
    public void getAllUser(){
        List<User> users = userService.getAllUsers().getResult();
        for (User user : users) {
            System.out.println(user.getId()+"----"+user.getNickname());
        }
    }
}

測試結果:
圖片描述
圖片描述
說明插入用戶和查詢全部用戶功能已完成!!


點擊此處進入java--最新SSM框架整合日記(下篇)

源碼在下篇里面哦!!


本人小小菜鳥,難免會有錯誤,希望大神們看到能夠及時指出。????? ????

參考資料

http://projects.spring.io/spring-framework/ Spring官網

http://www.mybatis.org/mybatis-3/zh/getting-started.html mybatis

點擊查看更多內容

本文原創發布于慕課網 ,轉載請注明出處,謝謝合作

13人點贊

若覺得本文不錯,就分享一下吧!

評論

相關文章推薦

正在加載中
意見反饋 幫助中心 APP下載
官方微信

舉報

0/150
提交
取消
lpl竞猜