菜鳥級springmvc+spring+mybatis整合開發用戶登陸功能(上)

因爲本人愚鈍,整合ssm框架真是費勁了全身的力氣,因此打算寫下這篇文章,一來是對整個過程進行一個回顧,二來是方便有像我同樣的笨鳥看過這篇文章後對其有所幫助,若是本文中有不對的地方,也請大神們指教。java

1、代碼結構mysql

整個項目的代碼結構如圖所示: 
這裏寫圖片描述
controller爲控制層,主要用於對業務模塊的流程控制。 
dao爲數據接入層,主要用於與數據庫進行鏈接,訪問數據庫進行操做,這裏定義了各類操做數據庫的接口。 
mapper中存放mybatis的數據庫映射配置。能夠經過查看mybatis相關教程瞭解 
model中存放了咱們的實體類 
service爲業務層,咱們的各類業務都定義在此,由controller調用不一樣業務實現不一樣的操做。web

因爲以前搭建環境都是本身配置依賴環境,致使缺各類缺包或者依賴衝突,因此此次我使用了maven來管理項目,能夠上網查一下相關的教程,使用起來很是方便。 
下面是個人pom.xml文件的配置spring

<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.mjl</groupId>
  <artifactId>testssm</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>testssm Maven Webapp</name>
  <url>http://maven.apache.org</url>



  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>4.1.4.RELEASE</spring.version>
    <jackson.version>2.5.0</jackson.version>
  </properties>
  <dependencies>
    <dependency>



      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>


    <!-- spring配置 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</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-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-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

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

    <!-- mybatis 包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.2.8</version>
    </dependency>

    <!--mybatis spring 插件 -->
    <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>5.1.34</version>
    </dependency>

    <!-- 數據源 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5-pre8</version>
    </dependency>

    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.4</version>
    </dependency>
    <!-- log4j -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</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>
    <!-- json -->
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.13</version>
    </dependency>
    <!-- 文件上傳 -->
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>

    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.2.2</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>testssm</finalName>
  </build>
</project>

 

下面進入主題,直接上代碼,我以前是先看了各類原理,可是看了半天也沒明白,因此你們能夠先把項目跑起來,而後再去對照springmvc的各個模塊進行分析,哪一個模塊執行哪一個操做,我認爲這樣的效果比較好。sql

我我的喜歡先從數據庫與ORM框架與spirng開始搭建,這樣的話在一開始就能夠對ORM框架進行檢驗,省得在最後檢驗的時候出了問題。數據庫

先看web.xml的配置apache

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3          xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 4     <!-- Spring配置 -->
 5     <!-- 配置Spring配置文件路徑,好讓ContextLoaderListener對其加載與解析-->
 6     <context-param>
 7         <param-name>contextConfigLocation</param-name>
 8         <param-value>
 9             classpath*:config/applicationContext.xml
10         </param-value>
11     </context-param>
12     <!-- 配置Spring上下文監聽器,它的做用就是在啓動WEB容器時,就會自動裝在咱們applicationContext.xml配置-->
13     <listener>
14         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
15     </listener>
16     <!-- 配置Spring字符編碼過濾器 -->
17     <filter>
18         <filter-name>encodingFilter</filter-name>
19         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
20         <init-param>
21             <param-name>encoding</param-name>
22             <param-value>UTF-8</param-value>
23         </init-param>
24         <init-param>
25             <param-name>forceEncoding</param-name>
26             <param-value>true</param-value>
27         </init-param>
28     </filter>
29     <filter-mapping>
30         <filter-name>encodingFilter</filter-name>
31         <url-pattern>/*</url-pattern>
32     </filter-mapping>
33 </web-app>

配置完web.xml後,配置spring的applicationContext.xml,它是spring的配置文件,通常與spring集成的框架都要在這裏進行配置。編程

<?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-3.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd">

    <!--引入jdbc配置 -->
    <context:property-placeholder location="classpath*:config/jdbc.properties"/>
    <!--  掃描文件(自動將service層注入)-->
    <context:component-scan base-package="com.mjl.service"/>
    <!--配置數據源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc_driverClassName}"/>
        <property name="jdbcUrl" value="${jdbc_url}"/>
        <property name="user" value="${jdbc_username}"/>
        <property name="password" value="${jdbc_password}"/>
        <!--鏈接池中保存的最大鏈接數目-->
        <property name="maxPoolSize" value="20"/>
        <!--鏈接池中保存的最少鏈接數目-->
        <property name="minPoolSize" value="2"/>
        <!-- 初始化鏈接大小 -->
        <property name="initialPoolSize" value="2"/>
        <!-- 獲取鏈接最大等待時間 -->
        <property name="maxConnectionAge" value="6000"/>
        <!-- 鏈接池最大空閒 -->
        <property name="maxIdleTime" value="60"/>
    </bean>

    <!--配置sqlSessionFactory 並將數據源注入-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入數據源-->
        <property name="dataSource" ref="dataSource"/>
        <!--指定要使用到到mybatis配置文件-->
        <property name="configLocation" value="classpath:config/config.xml"/>
        <!--用於配置mapper映射xml-->
        <property name="mapperLocations" value="classpath*:com/mjl/mapper/*.xml"/>
    </bean>
    <!-- 建立數據映射器-->
    <bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
          <property name="basePackage" value="com.mjl.dao"/>

    </bean>
    <!-- 對數據源進行事務管理 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>

在這裏使用了jdbc.properties來分散配置,jdbc.properties中保存了數據庫的信息,須要根據大家的數據庫配置進行修改。json

jdbc.propertiesapi

1 jdbc_driverClassName=com.mysql.jdbc.Driver
2 jdbc_url=jdbc:mysql://localhost:3307/db_ssm?useUnicode=true&amp;characterEncoding=utf-8
3 jdbc_username=root
4 jdbc_password=1234

而後是爭對mybatis進行配置,因爲我把數據庫配置都配置在applicationcontext.xml中,因此我對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>
    <!--爲com.mjl.model.User設置別名 User 方便調用-->
    <typeAliases>
        <typeAlias alias="User" type="com.mjl.model.User"/>
    </typeAliases>


</configuration>

配置完後,就開始進行數據庫開發了,因爲是一個簡單的登陸功能的實現,因此數據庫也很是簡單。

 1 create database if not exists db_ssm character set utf8;
 2 use db_ssm;
 3 create table tb_user(
 4 id int(10) auto_increment,
 5 username varchar(20) not null,
 6 password varchar(20) not null,
 7 primary key (id)
 8 )ENGINE=InnoDB DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
 9 
10 insert into tb_user(id,username,password) values(1,'alvin',1234);

建立完數據庫後開始寫model下面的實體類

User.java

package com.mjl.model;

/**
 * Created by alvin on 15/9/7.
 */
public class User {
    private int id;
    private String username;
    private String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

數據庫接入層dao的接口,在這裏我使用了mybatis以接口方式編程,這部分借鑑了其餘的教程,有不懂的地方能夠查看http://www.yihaomen.com/article/java/302.htm 該網址的mybatis教程,我以爲寫的很不錯。

 1 package com.mjl.dao;
 2 
 3 import com.mjl.model.User;
 4 
 5 /**
 6  * Created by alvin on 15/9/7.
 7  * 此類爲接口模式下的配置
 8  */
 9 
10 public interface IUserDao {
11     //這裏以接口形式定義了數據庫操做方法,咱們只需
12     // 在Mybatis映射文件中對其進行映射就能夠直接使用
13     public User selectById(int id);
14     public User selectByName(String username);
15 }

mybatis映射文件文件名必須與接口類相同,不然沒法映射成功。

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 3         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 4 
 5   <!--namespace用於與DAO層的接口類進行綁定,這樣咱們無需實現DAO層的接口
 6   類,其接口類就可以自動的找到相關的SQL語句進行綁定實現-->
 7 <mapper namespace="com.mjl.dao.IUserDao">
 8     <!--select表示查詢,它的id名稱必須與DAO層接口的方法名相同,不然沒法綁定-->
 9     <select id="selectByName" parameterType="string" resultType="User">
10         select * from tb_user where username = #{username}
11     </select>
12 
13     <select id="selectById" parameterType="int" resultType="User">
14 
15          select * from tb_user where id = #{id}
16     </select>
17 
18 
19 </mapper>

好了,到這裏mybatis與spring已經整合完畢,咱們須要測試一下mybatis是否與spring整合成功,寫一個test類

 1 package com.mjl.test;
 2 
 3 import com.mjl.dao.IUserDao;
 4 
 5 
 6 import com.mjl.model.User;
 7 import org.springframework.context.ApplicationContext;
 8 import org.springframework.context.support.ClassPathXmlApplicationContext;
 9 
10 
11 /**
12  * Created by Alvin on 15/9/6.
13  */
14 public class Test {
15    private static ApplicationContext ac;
16     static {
17         ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
18     }
19 
20     public static void main(String[] args) {
21         IUserDao mapper = (IUserDao) ac.getBean("IUserDao");
22         System.out.println("獲取alvin");
23         User user = mapper.selectByName("alvin");
24 
25         System.out.println(user.getId()+":"+"username:"+user.getUsername());
26         System.out.println("password:"+user.getPassword());
27 
28     }
29 }

若是成功,以下圖所示: 
這裏寫圖片描述

到這裏mybatis與spring就整合結束了,明天繼續更新下半部分。

相關文章
相關標籤/搜索