1. 程式人生 > 實用技巧 >Java從入門到實戰之(6)SSM框架使用

Java從入門到實戰之(6)SSM框架使用

對於ssm框架網上有很多,這裡只是自己為大家提供的一個ssm整合框架參考分享,這個前提是基於maven的管理工具寫的,

一 建立Maven專案具體步驟如下:

二 配置檔案

2.1 配置mybatis-config.xml

2.2 配置mapper.xml

2.3配置jdbc.properties

2.4配置applicationContext.xml

2.5配置springmvc-servlet.xml

2.6配置web.xml

2.7配置log4j.properties

2.8引入依賴

三 測試

3.1建立java檔案

3.1.1 UserController類

3.1.2 User實體類

3.1.3 UserService介面

3.1.4 UserServiceImpl實現類

3.1.5 UserMapper類

3.2建立MySql資料庫表

3.3建立users.jsp檔案

3.4結果

==============================================================================

1.設計資料庫表如下:

 
/*
 
Date: 2019-03-11 23:19:10
 
*/
 
 
 
SET FOREIGN_KEY_CHECKS=0;
 
 
 
-- ----------------------------
 
-- Table structure for tb_user
-- ---------------------------- DROP TABLE IF EXISTS `tb_user`; CREATE TABLE `tb_user` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `user_name` varchar(100) DEFAULT NULL COMMENT '使用者名稱', `password` varchar(100) DEFAULT NULL COMMENT '密碼', `name` varchar(100) DEFAULT NULL COMMENT '姓名', `age` int
(10) DEFAULT NULL COMMENT '年齡', `sex` tinyint(1) DEFAULT NULL COMMENT '性別,1男性,2女性', `birthday` date DEFAULT NULL COMMENT '出生日期', `created` datetime DEFAULT NULL COMMENT '建立時間', `updated` datetime DEFAULT NULL COMMENT '更新時間', PRIMARY KEY (`id`), UNIQUE KEY `username` (`user_name`) ) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8; INSERT INTO `tb_user` VALUES (1, 'zhangsan', '123456', '張三', 30, 1, '1984-8-8', '2014-9-19 16:56:04', '2014-9-21 11:24:59'); INSERT INTO `tb_user` VALUES (2, 'lisi', '123456', '李四', 21, 2, '1991-1-1', '2014-9-19 16:56:04', '2014-9-19 16:56:04'); INSERT INTO `tb_user` VALUES (3, 'wangwu', '123456', '王五', 22, 2, '1989-1-1', '2014-9-19 16:56:04', '2014-9-19 16:56:04'); INSERT INTO `tb_user` VALUES (4, 'zhangwei', '123456', '張偉', 20, 1, '1988-9-1', '2014-9-19 16:56:04', '2014-9-19 16:56:04'); INSERT INTO `tb_user` VALUES (5, 'lina', '123456', '李娜', 28, 1, '1985-1-1', '2014-9-19 16:56:04', '2014-9-19 16:56:04'); INSERT INTO `tb_user` VALUES (6, 'lilei', '123456', '李磊', 23, 1, '1988-8-8', '2014-9-20 11:41:15', '2014-9-20 11:41:15'); INSERT INTO `tb_user` VALUES (8, 'xiaofeng', '123456', '蕭峰', 30, 1, '2018-6-25', '2018-6-25 18:42:25', '2018-6-25 18:42:25'); INSERT INTO `tb_user` VALUES (12, 'zhendeshuai', '565656', '吳彥祖', 26, 1, '2018-6-26', '2018-6-26 14:55:59', '2018-6-26 15:12:12'); INSERT INTO `tb_user` VALUES (14, 'jiumozhi', '123456', '鳩摩智', 30, 1, '2018-6-26', '2018-6-26 23:53:15', '2018-6-26 23:53:15'); INSERT INTO `tb_user` VALUES (21, 'zhangsan1234', '12345', '傑克', 20, 1, '2000-1-1', '2018-7-7 21:50:26', '2018-7-7 21:50:26'); INSERT INTO `tb_user` VALUES (22, 'zhangsanqwe1', '123455', '張三', 30, 1, '1999-2-25', '2018-7-7 21:51:20', '2018-7-7 21:51:20'); INSERT INTO `tb_user` VALUES (25, 'qianjiu', '123456', '錢九', 30, 1, '1989-1-1', '2018-7-7 21:51:20', '2018-7-7 21:51:20'); INSERT INTO `tb_user` VALUES (26, 'zhaoniu', '123456', '趙牛', 28, 1, '1989-1-1', '2018-7-7 21:51:20', '2018-7-7 21:51:20');

2建立一個ssmDemo專案(專案名稱可以自定義),如圖所示:

建立好之後如下圖所示:

專案會報錯,不用急,為什麼呢?因為這是一個不完整的maven專案,缺少web.xml。

右鍵點選專案,如下操作,會自動補全web.xml檔案

3,向ssmzh專案中的pom.xml匯入spring-springmvc-mybatis整合所需要的依賴,具體依賴如下:

<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>com.agu</groupId>
 
<artifactId>SSMDemo</artifactId>
 
<version>1.0-SNAPSHOT</version>
 
<packaging>war</packaging>
 
 
 
 
 
<dependencies>
 
<!--spring-->
 
<dependency>
 
<groupId>org.springframework</groupId>
 
<artifactId>spring-context</artifactId>
 
<version>4.3.13.RELEASE</version>
 
</dependency>
 
<!--配置webmvc-->
 
<dependency>
 
<groupId>org.springframework</groupId>
 
<artifactId>spring-webmvc</artifactId>
 
<version>4.3.13.RELEASE</version>
 
</dependency>
 
<!--配置spring jdbc,用來載入DataSourceTransactionManager-->
 
<dependency>
 
<groupId>org.springframework</groupId>
 
<artifactId>spring-jdbc</artifactId>
 
<version>4.3.13.RELEASE</version>
 
</dependency>
 
<!--配置切面的jar包-->
 
<dependency>
 
<groupId>org.springframework</groupId>
 
<artifactId>spring-aspects</artifactId>
 
<version>4.3.13.RELEASE</version>
 
</dependency>
 
<!--mybatis,用來載入SqlSessionFactoryBean和MapperScannerConfigurer-->
 
<dependency>
 
<groupId>org.mybatis</groupId>
 
<artifactId>mybatis</artifactId>
 
<version>3.2.8</version>
 
</dependency>
 
<dependency>
 
<groupId>org.mybatis</groupId>
 
<artifactId>mybatis-spring</artifactId>
 
<version>1.2.2</version>
 
</dependency>
 
<!--資料庫驅動包-->
 
<dependency>
 
<groupId>mysql</groupId>
 
<artifactId>mysql-connector-java</artifactId>
 
<version>5.1.32</version>
 
</dependency>
 
<!--日誌檔案-->
 
<dependency>
 
<groupId>org.slf4j</groupId>
 
<artifactId>slf4j-log4j12</artifactId>
 
<version>1.7.22</version>
 
</dependency>
 
 
 
<!--json處理工具包-->
 
<dependency>
 
<groupId>com.fasterxml.jackson.core</groupId>
 
<artifactId>jackson-databind</artifactId>
 
<version>2.9.0</version>
 
</dependency>
 
<!-- 連線池,用來載入DruidDataSource-->
 
<dependency>
 
<groupId>com.alibaba</groupId>
 
<artifactId>druid</artifactId>
 
<version>1.0.9</version>
 
</dependency>
 
<!--javaScript標籤庫-->
 
<dependency>
 
<groupId>jstl</groupId>
 
<artifactId>jstl</artifactId>
 
<version>1.2</version>
 
</dependency>
 
<dependency>
 
<groupId>javax.servlet</groupId>
 
<artifactId>servlet-api</artifactId>
 
<version>2.5</version>
 
</dependency>
 
<dependency>
 
<groupId>javax.servlet</groupId>
 
<artifactId>jsp-api</artifactId>
 
<version>2.0</version>
 
</dependency>
 
</dependencies>
 
 
 
<build>
 
<plugins>
 
<!-- 配置Tomcat外掛 -->
 
<plugin>
 
<groupId>org.apache.tomcat.maven</groupId>
 
<artifactId>tomcat7-maven-plugin</artifactId>
 
<configuration>
 
<port>8080</port>
 
<path>/</path>
 
</configuration>
 
</plugin>
 
</plugins>
 
</build>
 
</project>

4,配置spring.xml(企業常用applicationContext.xml命名錶示是spring的配置,我這裡命名為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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

<!--開啟spring註解,掃描spring註解所在的包 -->
<context:component-scan base-package="com.usermanage"/>

<!-- 載入資原始檔 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<!-- 配置資原始檔 -->
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<!--spring 配置連線池,資料來源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${driver}"></property>
<property name="jdbcUrl" value="${url}"></property>
<property name="user" value="${user}"></property>
<property name="password" value="${passwd}"></property>
</bean>

</beans>

5,spring-tx(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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

<!-- 定義事務管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>


<!-- 定義事務策略 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--所有以query開頭的方法都是隻讀的 -->
<tx:method name="query*" read-only="true" />
<tx:method name="get*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="select*" read-only="true" />
<!--其他方法使用預設事務策略 -->
<tx:method name="*" />
</tx:attributes>
</tx:advice>


<aop:config>
<!--pointcut元素定義一個切入點,execution中的第一個星號 用以匹配方法的返回型別,
這裡星號表明匹配所有返回型別。 com.abc.dao.*.*(..)表明匹配cn.itcast.mybatis.service包下的所有類的所有 
方法 -->
<aop:pointcut id="myPointcut" expression="execution(* com.usermanage.service.*.*(..))" />
<!--將定義好的事務處理策略應用到上述的切入點 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut" />
</aop:config>
 

</beans>

6,spring-mybatis.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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- spring整合Mybatis的配置,其實主要是mybatis的相應配置 -->
<!-- 
sqlSession工廠 mapper的介面配置
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 載入全域性的配置檔案 -->
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
<!-- 配置mapper的掃描,找到所有的mapper.xml對映檔案。編碼時放開註釋,如果放開需要在mapper中寫一個mapper也是可以的 -->
<!-- <property name="mapperLocations" value="classpath:mybatis/mapper/*.xml"></property> -->
<!-- 配置類型別名 -->
<property name="typeAliasesPackage" value="com.usermanage.pojo"></property>
</bean>

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <!--配置mapper介面所在路徑,掃描路徑下的所有的mapper介面  如果配置多個mapper的包,使用逗號進行分割
   -->
   <!--在mybatis當中,dao層與mapper是一樣的,只是不同地方叫法不一樣,mapper.xml是寫sql的,是用來操作資料庫的  -->
  <property name="basePackage" value="cn.usermanage.dao,cn.usermanage.mapper" />
</bean>

</beans>

7,springmvc.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: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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">




<!-- 配置推薦使用註解驅動,會預設的載入上面的兩個 HandlerMapping, HandlerAdapter -->
<mvc:annotation-driven />
<!-- 開啟springmvc註解掃描 -->
<context:component-scan base-package="cn.usermanage.controller"></context:component-scan>
<!-- 這個是excelView的載入,原生態ssm不需要,所以這裡是可以省略的 -->
<!-- <bean name="excelView" class="cn.usermanage.view.UserExcelView"></bean> -->

<!-- 檢視解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 字首,這裡是請求的路徑檔案 -->
<property name="prefix" value="/WEB-INF/views/"></property>
<!-- 字尾 ,支援.jsp的請求-->
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 以上是原生態的ssm配置 -->

<!-- 配置第二個檢視解析器 -->
<!-- <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
<property name="order" value="1"></property>
</bean> -->


<!-- 定義檔案上傳解析器 -->
<!-- <bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
設定預設編碼
<property name="defaultEncoding" value="UTF-8"></property>
設定檔案上傳的最大值5MB,5*1024*1024
<property name="maxUploadSize" value="5242880"></property>
</bean> -->

<!-- 解決靜態資源被攔截的問題 -->
<!-- <mvc:default-servlet-handler/> -->


</beans>

8,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>
  <settings>
  <!-- 開啟駝峰匹配 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
  </settings>
  <!-- 分頁助手 -->
  <plugins>
    <!-- com.github.pagehelper為PageHelper類所在包名 -->
    <plugin interceptor="com.github.pagehelper.PageHelper">
    <!-- 資料庫方言 -->
        <property name="dialect" value="mysql"/>
        <!-- 設定為true時,使用RowBounds分頁會進行count查詢 會去查詢出總數 -->
        <property name="rowBoundsWithCount" value="true"/>
    </plugin>
</plugins>

 </configuration>

9,Mybatis-generator的配置(這個需要請先安裝mybatis-generator外掛,然後即可),generatorConfig.xml配置如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration >
<!-- 資料庫jar包驅動路徑必須手動加上去 -->
<classPathEntry location="D:\allworkspace\testspace\mybatis-zidong\src\main\resources\mybatis-generator\mysql-connector-java-5.1.25.jar" />  
<!--資料庫名稱  -->
  <context id="test" >
   <!-- commentGenerator 去除自動生成的註釋 -->  
        <commentGenerator>  
            <property name="suppressAllComments" value="true" />  
            <property name="suppressDate" value="true" />  
        </commentGenerator> 
  <!-- 資料庫驅動,連線,使用者名稱,密碼 -->
    <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8" userId="root" password="123" />
    <!-- pojo實體資訊 ,包名稱與專案名稱-->
    <javaModelGenerator targetPackage="com.usermanage.pojo" targetProject="mybatis-zidong/src/main/java" />
    <!--  mapper資訊-->
    <sqlMapGenerator targetPackage="com.usermanage.mapper" targetProject="mybatis-zidong/src/main/java" />
    <!-- dao介面 -->
    <javaClientGenerator targetPackage="com.usermanage.dao" targetProject="mybatis-zidong/src/main/java" type="XMLMAPPER" />
    <!--表名  ,domainObjectName="Teacher"表示與資料庫所對應的實體-->
    <table schema="teacher" tableName="teacher" domainObjectName="Teacher"
    enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"   
            enableSelectByExample="false" selectByExampleQueryId="false"></table>
  </context>
</generatorConfiguration>

10.jdbc.properties配置如下:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8
user=root

passwd=123456

11.log4j.properties日誌配置如下:

log4j.rootLogger=DEBUG,A1
log4j.logger.org.mybatis=DEBUG
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n

12,配置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" version="2.5">
<display-name>ssmzh</display-name>
<!-- 載入spring相關配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- 這裡使用的是以spring*.xml的萬用字元方式載入配置的 -->
<param-value>classpath:spring/spring*.xml</param-value>
</context-param>
<!--Spring的ApplicationContext 載入 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


<!-- 編碼過濾器,以UTF8編碼 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


<!-- 配置SpringMVC -->
<servlet>
<servlet-name>usermanage</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- 指定載入外部的spring-mvc配置檔案 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
<!-- 這個可以不配,可以省略 -->
<load-on-startup>1</load-on-startup>
</servlet>


<servlet-mapping>
<servlet-name>usermanage</servlet-name>
<!-- 攔截所有的請求,除了jsp。  /xx.html js css 會 -->
<url-pattern>/</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

</web-app>

結構圖所下:

啟動專案輸入:http://www.localhost:8080/SSMDemo/user/list

執行結果如下圖:

那麼到此:一個完整的spring-springmvc-mybatis的整合框架就搭建好了,也許你覺得很複雜,那麼這只是一個框架的開始,這個是必須要會的,不論怎麼樣,一定要多親自搭建,一次,兩次甚至更多,如果連這個基本框架都覺得難,那麼你是否也在想應該放棄了。不管哪個行業都有它的難處,要想獲得更高必須比別人付出更多。