使用idea實現SSM框架整合


SM框架整合

1      使用idea創建一個maven webapp項目

 

 

 

 

 

 

 

 

 

到此為止項目初步建立,需要等待maven對項目結構進行組織,直到狀態欄的進度條完成,且項目的目錄結構如下:

 

 

2      因為是SSM,需要操作數據庫,現在准備數據以及表,此處選擇mysql數據庫

2.1   准備表

復制代碼
-- auto-generated definition
create table student
(
 ID int auto_increment
  primary key,
 stuName varchar(32) null,
 stuAge tinyint null,
 mobile varchar(11) null,
 address varchar(256) null,
 EntranceTime date null
)
;
復制代碼

 

2.2   准備初始化數據

復制代碼
INSERT INTO test.student (stuName, stuAge, mobile, address, EntranceTime) VALUES ('何靖', 8, '110', '天府三街', '2017-06-06');
INSERT INTO test.student (stuName, stuAge, mobile, address, EntranceTime) VALUES ('小強', 18, '69776977', '中和鎮', '2017-06-06');
INSERT INTO test.student (stuName, stuAge, mobile, address, EntranceTime) VALUES ('小迪', 22, '1456789', '天華苑', '2017-06-01');
INSERT INTO test.student (stuName, stuAge, mobile, address, EntranceTime) VALUES ('情歌', 24, '6454422', '成都', '2017-05-31');
INSERT INTO test.student (stuName, stuAge, mobile, address, EntranceTime) VALUES ('周三', 23, '1223154', '德陽', '2017-06-01');
INSERT INTO test.student (stuName, stuAge, mobile, address, EntranceTime) VALUES ('紅牛', 32, '120', '黃山', '2017-05-31');
INSERT INTO test.student (stuName, stuAge, mobile, address, EntranceTime) VALUES ('大米', 16, '180', '新希望', '2017-06-04');
INSERT INTO test.student (stuName, stuAge, mobile, address, EntranceTime) VALUES ('小米', 22, '180', '貝立美', '2017-06-04');
INSERT INTO test.student (stuName, stuAge, mobile, address, EntranceTime) VALUES ('黑米', 36, '180', '新希望', '2017-06-04');
INSERT INTO test.student (stuName, stuAge, mobile, address, EntranceTime) VALUES ('紅米', 24, '180', '一樓', '2017-06-04');
INSERT INTO test.student (stuName, stuAge, mobile, address, EntranceTime) VALUES ('大豆', 25, '180', '二流', '2017-06-04');
INSERT INTO test.student (stuName, stuAge, mobile, address, EntranceTime) VALUES ('綠豆', 26, '180', '三樓', '2017-06-04');
INSERT INTO test.student (stuName, stuAge, mobile, address, EntranceTime) VALUES ('灰豆', 19, '180', '四樓', '2017-06-04');
INSERT INTO test.student (stuName, stuAge, mobile, address, EntranceTime) VALUES ('歐陽修', 23, '122', '五棵松', '2017-05-28');
INSERT INTO test.student (stuName, stuAge, mobile, address, EntranceTime) VALUES ('韓明', 12, '120', '鳥巢', '2017-05-29');
INSERT INTO test.student (stuName, stuAge, mobile, address, EntranceTime) VALUES ('李修', 21, '120', '長安', '2017-06-14');
INSERT INTO test.student (stuName, stuAge, mobile, address, EntranceTime) VALUES ('韓梅梅', 12, '2132354354', '大坪', '2017-06-01');
INSERT INTO test.student (stuName, stuAge, mobile, address, EntranceTime) VALUES ('東北F4', 99, '121313121', '鐵嶺', '2017-06-01');
INSERT INTO test.student (stuName, stuAge, mobile, address, EntranceTime) VALUES ('趙四', 32, '44111221', '東北', '2017-06-07');
復制代碼

 

 

3      對項目目錄結構進行完善

3.1   JDK環境確認

 

 

 

 

3.2   編譯環境確認

 

 

3.3   配置源碼、資源、web、測試的目錄

 

 

 

3.4   配置web容器tomcat

  1. 點擊菜單中run-edit configurations打開運行配置的界面

  

 

先不要點OK,記住哦。

 

 

 

3.5   建立常見的代碼包結構

 

 

4      增加必要的依賴

通過在pom.xml中增加相關依賴。

4.1   增加阿里雲的maven遠程庫,加快依賴加載速度。

復制代碼
<!-- 阿里雲maven資源庫 -->
<repositories>
  <repository>
    <id>alimaven</id>
    <name>aliyun maven</name>
    <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
  </repository>
</repositories>
復制代碼

 

 

4.2   增加jstl與javaee的相關依賴

復制代碼
<!-- 添加jstl依賴 -->
<dependency>
  <groupId>jstl</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>
<dependency>
  <groupId>javax</groupId>
  <artifactId>javaee-api</artifactId>
  <version>7.0</version>
</dependency>
復制代碼

 

4.3   增加數據庫相關依賴

復制代碼
<!-- 添加mysql驅動依賴 -->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.41</version>
</dependency>
復制代碼

 

4.4   增加JUNIT相關依賴

復制代碼
<!-- 添加junit4依賴 -->
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <!-- 指定范圍,在測試時才會加載 -->
  <scope>test</scope>
</dependency>
復制代碼

 

 

4.5   增加mybatis相關依賴

復制代碼
<!-- 添加mybatis依賴 -->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.2.8</version>
</dependency>

<!--CGLIB&asm 用於mybaitis緩存以及spring中的一些依賴-->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.3.1</version>
</dependency>

復制代碼

 

 

 

4.6   增加spring 核心相關依賴

復制代碼
<!-- 添加spring核心依賴 -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-core</artifactId>
  <version>4.2.5.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>4.2.5.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context-support</artifactId>
  <version>4.2.5.RELEASE</version>
</dependency>
<!-- spring aop -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aop</artifactId>
  <version>4.2.5.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aspects</artifactId>
  <version>4.2.5.RELEASE</version>
</dependency>

<!-- spring test-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.2.5.RELEASE</version>
<scope>test</scope>
</dependency>

復制代碼

 

 

4.7   增加spring與mybatis集成的相關依賴

復制代碼
<!-- spring的數據庫操作需求的依賴包-->
<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>

<!-- 添加mybatis/spring整合包依賴 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>

<!-- 添加數據庫連接池C3P0依賴 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.1</version>
</dependency>

復制代碼

 

4.8   增加springmvc相關依賴

復制代碼
<!-- spring mvc 依賴庫-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>4.2.5.RELEASE</version>
</dependency>
復制代碼

 

4.9   增加jackson相關依賴

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

 

 

4.10     增加文件上傳相關依賴

復制代碼
<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.1</version>
</dependency>
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.4</version>
</dependency>
 
復制代碼

 

4.11     增加日志相關依賴

復制代碼
<!-- 添加日志相關jar包 -->
<dependency>
  <groupId>log4j</groupId>
  <artifactId>log4j</artifactId>
  <version>1.2.17</version>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-api</artifactId>
  <version>1.7.18</version>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-log4j12</artifactId>
  <version>1.7.18</version>
</dependency>
復制代碼

 

 

4.12     增加其他依賴

復制代碼
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.5</version>
</dependency>
 
復制代碼

 

4.13     添加mybatis的分頁組件

  1. 將pageutil.jar拷貝到WEB-INF/lib目錄,如果沒有則創建

 

 

  1. 將pageutil.jar添加到編譯環境。

 

 

 

5      配置mybatis

在resource目錄下建立mybatis.xml

復制代碼
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPEconfiguration
        PUBLIC"-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!-- 這個配置使全局的映射器啟用或禁用緩存 -->
        <setting name="cacheEnabled" value="false"/>
        <!-- 全局啟用或禁用延遲加載。當禁用時,所有關聯對象都會即時加載 -->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!-- 當啟用時,有延遲加載屬性的對象在被調用時將會完全加載任意屬性。否則,每種屬性將會按需要加載 -->
        <setting name="aggressiveLazyLoading" value="false"/>
        <!-- 當啟用時,字段自動映射為駝峰形式  -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- 指定MyBatis如何自動映射列到字段/屬性。PARTIAL只會自動映射簡單,沒嵌套的結果。FULL會自動映射有任意復雜的結果(嵌套的或其他情況)-->
        <setting name="autoMappingBehavior" value="PARTIAL"/>
    </settings>
    <!-- 別名定義 -->
    <typeAliases>
        <!-- 針對包定義別名,以后在mybaits的mapper文件中,使用這個包中的類可以直接寫類名就好了 -->
        <package name="com.deng.ssm.bean"/>
    </typeAliases>
    <!--添加自定插件,此插件用於分頁,其實現在pageutil.jar中-->
    <plugins>
        <plugin interceptor="page.PageInterceptor">
            <!--指定數據庫方言為mysql-->
            <property name="dialect" value="page.dialect.MySQLDialect"></property>
        </plugin>
    </plugins>
</configuration>
復制代碼

 

6      定義數據庫連接的相關屬性信息

在resource目錄下新建文件jbdc.properties

復制代碼
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://39.108.103.56:3306/test?useUnicode=true&characterEncoding=UTF-8
username=root
password=10@idccom
#定義初始連接數
initialSize=2
#定義最大連接數
maxActive=20
#定義最小連接數
minActive=2
#定義最長等待時間
maxWait=60000
#是否在連接關閉時自動提交事務
autoCommitOnClose=false
#當獲取連接失敗重試次數
acquireRetryAttempts=2
復制代碼

 

7      實現spring以及與mybatis的整合的配置

在resource目錄下新建spring-mybaits.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: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-4.0.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-4.0.xsd
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
                         http://www.springframework.org/schema/aop
                        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
                        ">
    <!-- 自動掃描 -->
    <context:component-scan base-package="com.deng.ssm.service" />
    <!-- 引入實現JDBC配置文件 -->
    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>
    <!-- 2.數據庫連接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- 配置連接池屬性 -->
        <!-- 此處 ${Driver} 中的 ${屬性名} 是訪問屬性文件中的指定屬性-->
        <property name="driverClass" value="${driver}" />
        <property name="jdbcUrl" value="${url}" />
        <property name="user" value="${username}" />
        <property name="password" value="${password}" />
        <!-- c3p0連接池的私有屬性 -->
        <property name="maxPoolSize" value="${maxActive}" />
        <property name="minPoolSize" value="${minActive}" />
        <property name="initialPoolSize" value="${initialSize}"/>
        <!-- 關閉連接后不自動commit -->
        <property name="autoCommitOnClose" value="${autoCommitOnClose}" />
        <!-- 獲取連接超時時間 -->
        <property name="checkoutTimeout" value="${maxWait}" />
        <!-- 當獲取連接失敗重試次數 -->
        <property name="acquireRetryAttempts" value="2" />
    </bean>
    <!-- spring和MyBatis整合,通過spring來管理MyBatis的SqlSessionFactory會話工廠 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--  指定數據庫連接池引用 -->
        <property name="dataSource" ref="dataSource" />
        <!--  指定mybatis的配置文件路徑,該配置文件下不需要再定義數據庫連接信息和mapper信息了,但是可以
        有一些關於mybatis的配置信息-->
        <property name="configLocation" value="classpath:mybatis.xml"/>
        <!-- 指定mybatis的mapper配置文件路徑,*代表通配符所有的意思
         value可以指定多個,由英文逗號分隔
         -->
        <property name="mapperLocations" value="classpath:com/deng/ssm/mapper/*.xml"></property>
    </bean>
    <!-- 定義sqlSession對象,通過SqlSessionTemplate來產生,需要在構造方法中指定會話工廠
     相當於原來mybatis中的sessionFactory.openSession();SqlSessionTemplate是線程安全的,所以采用單例模式
     -->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate" destroy-method="clearCache">
        <!--注入會話工廠-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
        <!--定義采用何種形式操作數據庫,需要注意若是BATCH的話增刪改返回的將不是影響的行數
        默認為SIMPLE-->
        <!--<constructor-arg index="1" value="BATCH"/>-->
    </bean>
    <!--
        定義mybaits的DAO接口所在的包名,spring會自動查找其下的接口,並為其自動創建bean,無需我們定義
     -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.deng.ssm.dao" />
        <property name="sqlSessionTemplateBeanName" value="sqlSessionTemplate"/>
    </bean>
    <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- (事務管理)使用注解的方式來管理實務 -->
    <!--<tx:annotation-driven transaction-manager="transactionManager"/>-->
    <!-- 定義事務的切面(通知) -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager" >
        <tx:attributes >
            <!-- 定義方法的事務規則 -->
            <tx:method  name="add*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="del*" propagation="REQUIRED"/>
            <tx:method name="modify*" propagation="REQUIRED"/>
            <tx:method name="*" propagation="NEVER" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <!--通過AOP啟用事務-->
    <aop:config>
        <aop:pointcut id="pt" expression="execution(* com.deng.ssm.service.impl.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt" />
    </aop:config>
</beans>
 
復制代碼

 

8      Spring mvc的配置

在resource目錄下新建spring-mvc.xml

復制代碼
<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-4.0.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">
    <!-- 定義自動掃描包的路徑,在此處僅掃描Controller所在的包,如果有多個需要逗號分隔。
    需要注意:此處掃描和spring的自動掃描的包不要出現重疊
    -->
    <context:component-scan base-package="com.deng.ssm.controller"/>
    <!-- spring 3.2版本之后可以不用配置 -->
    <context:annotation-config/>
    <!-- 在springMVC-servlet.xml中配置<mvc:default-servlet-handler />后,會在Spring MVC上下文中定義一個
    org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler,它會像一個檢查員,
    對進入DispatcherServlet的URL進行篩查,如果發現是靜態資源的請求,就將該請求轉由Web應用服務器默認的Servlet處理,
    如果不是靜態資源的請求,才由DispatcherServlet繼續處理。
    -->
    <mvc:default-servlet-handler/>
    <!-- 注冊spring mvc的注解驅動,只有注冊了springmvc才能使用完整的注解功能 -->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <!-- 將StringHttpMessageConverter的默認編碼設為UTF-8 -->
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8" />
            </bean>
            <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
            <!-- 將Jackson2HttpMessageConverter的默認格式化輸出設為true -->
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="prettyPrint" value="true"/>
                <!-- 避免IE執行AJAX時,返回JSON出現下載文件 -->
                <property name="supportedMediaTypes" >
                    <list>
                        <value>application/json;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <!--InternalResourceViewResolver:用於支持Servlet、JSP視圖解析;
    viewClass:JstlView表示JSP模板頁面需要使用JSTL標簽庫,classpath中必須包含jstl的相關jar包;
    prefix和suffix:查找視圖頁面的前綴和后綴(前綴[邏輯視圖名]后綴),比如傳進來的邏輯視圖名為hello,
    則該該jsp視圖頁面應該存放在“WEB-INF/jsp/hello.jsp”;-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!-- 用於文件上傳 upload file,dependency commons-fileupload.jar -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 單上傳行為的最大上傳文件大小,單位為字節 -->
        <property name="maxUploadSize" value="52428800"/>
        <!-- 允許上傳的單個文件的最大大小,單位為字節 -->
        <property name="maxUploadSizePerFile" value="52428800"/>
    </bean>
</beans>
復制代碼

 

9      配置WEB.xml

復制代碼
<!DOCTYPEweb-appPUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
  <!--  定義spring相關的配置文件路徑,除了springmvc之外的 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      classpath:/spring-mybatis.xml
    </param-value>
  </context-param>
  <!-- 用於處理post請求中文亂碼的過濾器 -->
  <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>
  <!--  通過serlvetContext監聽器來加載spring容器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- spring mvc的核心servlet -->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--初始化參數-->
    <init-param>
      <!--通過初始化參數contextConfigLocation指定springmvc配置文件的路徑-->
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:/spring-mvc.xml</param-value>
    </init-param>
    <!--  當應用啟動時加載該servlet -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <!--
    /:支持RESTful,便於檢索。
    /*:不能返回視圖。
    *.do(必須以.do結尾的路徑才能訪問。)
    -->
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>
 
復制代碼

 

10 配置log4j

在resource目錄下新建log4j.properties

復制代碼
log4j.rootLogger=DEBUG,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
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.org.apache=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
復制代碼

 

 

 

11 通過一個顯示所有學生的實例來驗證框架是否搭建完成

11.1     創建學生bean

在com.deng.ssm.bean下建立類Student

復制代碼
package com.deng.ssm.bean;
import java.util.Date;
public class Student {
    
private Integer id;
    private String stuName;
    private int stuAge;
    private String mobile;
    private String address;
    private Date entranceTime;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getStuName() {
        return stuName;
    }
    public void setStuName(String stuName) {
        this.stuName = stuName;
    }
    public int getStuAge() {
        return stuAge;
    }
    public void setStuAge(int stuAge) {
        this.stuAge = stuAge;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public Date getEntranceTime() {
        return entranceTime;
    }
    public void setEntranceTime(Date entranceTime) {
        this.entranceTime = entranceTime;
    }
}

復制代碼

 

11.2     新建學生的數據操作接口IStudentDAO

在com.deng.ssm.dao下建立接口IStudentDAO

復制代碼
package com.deng.ssm.dao;

import com.deng.ssm.bean.Student;

import java.util.List;

public interface IStudentDAO {
public List<Student> searchAll();
}

復制代碼

 

 

11.3     建立學生的Mapper文件

在resource的com/deng/ssm/mapper目錄下新建StudentMapper.xml

復制代碼
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPEmapper
        PUBLIC"-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--  注意命名空間為該maper文件對應的DAO的全路徑 -->
<mapper namespace="com.deng.ssm.dao.IStudentDAO" >
    <!--定義resultmap
        type的值為Student實體類名稱,因為指定包的別名所以不用全路徑
        -->
    <resultMap id="student_map" type="Student">
        <id property="id" column="id"/>
        <result property="stuName" column="stuName"/>
        <result property="stuAge" column="stuAge"/>
        <result property="mobile" column="mobile"/>
        <result property="address" column="address"/>
        <result property="entranceTime" column="entranceTime"/>
    </resultMap>
    <!--需要注意id的值等於接口中方法的名字-->
    <select id="searchAll" resultMap="student_map">
        select id,stuName, stuAge, mobile, address, EntranceTime
        from student
    </select>
</mapper>
復制代碼

 

11.4     建立學生的service接口

在包com.deng.ssm.service下建立StudentService接口

復制代碼
package com.deng.ssm.service;

import com.deng.ssm.bean.Student;

import java.util.List;

public interface StudentService {
public List<Student> searchAll();
}

復制代碼

 

 

11.5     實現學生的service接口

在包com.deng.ssm.service.impl下建立StudentServiceImpl實現類

復制代碼
package com.deng.ssm.service.impl;

import com.deng.ssm.bean.Student;
import com.deng.ssm.dao.IStudentDAO;
import com.deng.ssm.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

//通過@Service注解定義為一個Service bean
@Service
public class StudentServiceImpl implements StudentService {
// 自動裝配DAO的實例
@Autowired
private IStudentDAO studentDAO;
public List<Student> searchAll() {
return studentDAO.searchAll();
}
}

復制代碼

 

 

11.6     實現學生Controller

在包com.deng.ssm.controller下建立StudentController

復制代碼
package com.deng.ssm.controller;

import com.deng.ssm.bean.Student;
import com.deng.ssm.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller //該注解代表這個類是一個Controller
@RequestMapping("/student") //將這個類映射一個路勁各位/student,該可以不要
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping(
"/search")
public String searchAll(Model model){
model.addAttribute(
"students",studentService.searchAll());
return "index";
}
}

復制代碼

 

11.7     建立jsp頁面,來顯示所有的學生

在/WEB-INF/jsp下建立index.jsp

復制代碼
<%--
  Created by IntelliJ IDEA.
  User: dengcl
  Date: 2017/6/22
  Time: 11:48
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java"
isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>學生信息</title>
</head>
<body>
<%--<h1>學生信息</h1>--%>
<table width="100%">
    <caption>所有學生信息</caption>
    <thead>
        <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>年齡</th>
            <th>手機</th>
            <th>地址</th>
            <th>入學時間</th>
        </tr>
    </thead>
    <tbody>
        <c:forEach items="${requestScope.students}" var="stu">
            <tr>
                <td>${stu.id}</td>
                <td>${stu.stuName}</td>
                <td>${stu.stuAge}</td>
                <td>${stu.mobile}</td>
                <td>${stu.address}</td>
                <td>${stu.entranceTime}</td>
            </tr>
        </c:forEach>
    </tbody>
</table>
</body>
</html>
復制代碼

 

11.8     啟動應用,測試

打開瀏覽器,輸入http://ip:port/上下文/student/search查看結果

 

分頁組件下載

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM