1. 程式人生 > >spring+springmvc+mybatis+mysql實現登入功能(上)

spring+springmvc+mybatis+mysql實現登入功能(上)

注:classpath 指的為target資料夾,classpath*為有多個classpath時使用。

1.在idea中建立maven 工程。

具體過程:File -》new project -》選擇maven  勾選create from archetype,選中以webapp結尾的一行,點選next,groupid以及artifactid可以隨意起名,點選next,選擇加號,新增key:archetypeCatalog,value:internal,點選next,之後就隨意起名,放在d盤,最好不是c盤下。next,完成後就出現web工程。

2.建立目錄結構(注意如果建立的有誤,則不能正確讀取到檔案,一個顏色為一組結構,同屬於main下)

層級為:src-》main->(java->com->yy->(controller,,dao->(IUserDao.java),,model->(User.java),,service),,,,resources->(config->(applicationContext.xml,,config.xml,,jdbc.properties),,,mapper->(IUserDao.xml)),,test-》Test.java...,,webapp->**.jsp,與(WEB-INF->(web.xml,log4j.xml)),(target為自動生成的),pom.xml

3.controller為控制層,主要用於對業務模組的流程控制。 
dao為資料接入層,主要用於與資料庫進行連線,訪問資料庫進行操作,這裡定義了各種操作資料庫的介面。 
mapper中存放mybatis的資料庫對映配置。可以通過檢視mybatis相關教程瞭解 
model中存放了我們的實體類 
service為業務層,我們的各種業務都定義在此,由controller呼叫不同業務實現不同的操作。

4.具體各部分程式

(1)pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ -->
<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> <packaging>war</packaging> <name>spring</name> <groupId>com.yy</groupId> <artifactId>spring</artifactId> <version>1.0-SNAPSHOT</version> <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> </dependencies> <build> <plugins> <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>maven-jetty-plugin</artifactId> <version>6.1.7</version> <configuration> <connectors> <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector"> <port>8888</port> <maxIdleTime>30000</maxIdleTime> </connector> </connectors> <webAppSourceDirectory>${project.build.directory}/${pom.artifactId}-${pom.version}</webAppSourceDirectory> <contextPath>/</contextPath> </configuration> </plugin> </plugins> </build> </project>
(2)web.xml具體程式碼
<?xml version="1.0" encoding="UTF-8"?>
<!--
  - This is the Cocoon web-app configurations file
  -->
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!-- Spring配置 -->
    <!-- 配置Spring配置檔案路徑,好讓ContextLoaderListener對其載入與解析-->
<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
classpath*:config/applicationContext.xml
        </param-value>
     </context-param>
<!--
  - Declare Spring context listener which sets up the Spring Application Context
  - containing all Cocoon components (and user defined beans as well).
  -->
  <!-- 配置Spring上下文監聽器,它的作用就是在啟動WEB容器時,就會自動裝在我們applicationContext.xml配置-->
<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
<!-- 配置Spring字元編碼過濾器 -->
<filter>
       <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>

(3)配置完web.xml後,配置spring的applicationContext.xml,它是spring的配置檔案,一般與spring整合的框架都要在這裡進行配置。

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at
      http://www.apache.org/licenses/LICENSE-2.0
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- @version $Id: applicationContext.xml 561608 2007-08-01 00:33:12Z vgritsenko $ -->
<!-- 需要加入context一行解析上下文-->
<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"
xmlns:util="http://www.springframework.org/schema/util"
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.yy.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*:mapper/*.xml"/>
    </bean>
<!-- 建立資料對映器-->
<bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.yy.dao"/>
    </bean>
<!-- 對資料來源進行事務管理 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>()
(4)

在這裡使用了jdbc.properties來分散配置,jdbc.properties中儲存了資料庫的資訊,需要根據你們的資料庫配置進行修改。

jdbc.properties

jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/demo95?useUnicode=true&amp;characterEncoding=utf-8
jdbc_username=root
jdbc_password=123456
(5)

然後是爭對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.yy.model.User設定別名 User 方便呼叫-->
<typeAliases>
        <typeAlias alias="User" type="com.yy.model.User"/>
    </typeAliases>
</configuration>
(6)

建立完資料庫後開始寫model下面的實體類

User.java

package com.yy.model;
/**
 * Created by yy on 2017/9/6.
 */
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;
}
}

(7)

資料庫接入層dao的介面,在這裡我使用了mybatis以介面方式程式設計,這部分借鑑了其他的教程,有不懂的地方可以檢視http://www.yihaomen.com/article/java/302.htm 該網址的mybatis教程,我覺得寫的很不錯。
package com.yy.dao;
import com.yy.model.User;
/**
 * Created by yy on 2017/9/6.
 */
public interface IUserDao {
    public User selectById(int id);
    public User selectByName(String name);
}
(8)mybatis對映檔案檔名必須與介面類相同,否則無法對映成功。
<?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">
<!--namespace用於與DAO層的介面類進行繫結,這樣我們無需實現DAO層的介面
類,其介面類就能夠自動的找到相關的SQL語句進行繫結實現-->
<mapper namespace="com.yy.dao.IUserDao">
<!--select表示查詢,它的id名稱必須與DAO層介面的方法名相同,否則無法繫結-->
<select id="selectByName" parameterType="string" resultType="User">
select * from tb_user where username = #{username}
    </select>
    <select id="selectById" parameterType="int" resultType="User">
select * from tb_user where id = #{id}
    </select>
</mapper>

(9)好了,到這裡mybatis與spring已經整合完畢,我們需要測試一下mybatis是否與spring整合成功,寫一個test類

import com.yy.dao.IUserDao;
import com.yy.model.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * Created by yy on 2017/9/6.
 */
public class Test {
    private static ApplicationContext ac;
    static {
        ac = new ClassPathXmlApplicationContext("config/applicationContext.xml");
}
    public static void main(String[] args) {
        IUserDao mapper = (IUserDao) ac.getBean("IUserDao");
System.out.println("獲取alvin");
User user = mapper.selectByName("yy");
System.out.println(user.getId()+":"+"username:"+user.getUsername());
System.out.println("password:"+user.getPassword());
}

}
如果成功,如下圖所示:

log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
獲取alvin
1:username:yy
password:123