1. 程式人生 > >基於maven和SSM(spring+springMVC+mybatis)的例項

基於maven和SSM(spring+springMVC+mybatis)的例項

1、環境搭建

搭建maven環境,DOC下輸入mvn -v檢視是否配置成功maven環境。新建mvn工程選擇webapp,雙擊進入

這裡寫圖片描述

工程結構:
這裡寫圖片描述

2、自動生成程式碼

檔案結構:
這裡寫圖片描述
生成方法:
本地路徑 D:\generator下新建如下檔案,匯入圖中包(前提是本地搭建好了maven環境,DOC下輸入mvn -v檢視是否配置成功),在路徑D:\generator>下,DOC執行命令:

java -jar mybatis-generator-core-1.3.5.jar -configfile generator.xm
l -overwrite
![這裡寫圖片描述](https://img-blog.csdn.net/20170808115632628?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMjM0ODkzMDM=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)

圖中檔案資料:

<?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>  
    <!-- 資料庫驅動包位置 -->  
    <classPathEntry
location="D:\generator\mysql-connector-java-5.1.30.jar" />
<!-- <classPathEntry location="C:\oracle\product\10.2.0\db_1\jdbc\lib\ojdbc14.jar" />--> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressAllComments"
value="true" />
</commentGenerator> <!-- 資料庫連結URL、使用者名稱、密碼 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test02?characterEncoding=utf8" userId="root" password="root"> <!--<jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@localhost:1521:orcl" userId="msa" password="msa">--> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 生成模型的包名和位置 --> <javaModelGenerator targetPackage="andy.model" targetProject="D:\generator\src"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- 生成的對映檔案包名和位置 --> <sqlMapGenerator targetPackage="andy.mapping" targetProject="D:\generator\src"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- 生成DAO的包名和位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="andy.dao" targetProject="D:\generator\src"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 要生成那些表(表是已經存在的)(更改tableName和domainObjectName就可以) --> <table tableName="emps" domainObjectName="Emps" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" /> <!-- <table tableName="course_info" domainObjectName="CourseInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" /> --> <!--<table tableName="course_user_info" domainObjectName="CourseUserInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" /> --> </context> </generatorConfiguration>

注意檔案路徑必須正確
將生成問加你copy到專案檔案中

需要建立表格及模擬匯入資料:

DROP TABLE IF EXISTS  emps;  
CREATE TABLE emps 
(id int(10) NOT NULL, 
name varchar(30) NOT NULL, 
age int(10) NOT NULL, 
salary float NOT NULL, 
PRIMARY KEY (id)
) 
ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into emps(id,name,age,salary) values (1,'zjx',21,100);
insert into emps(id,name,age,salary) values (2,'zht',22,110);
insert into emps(id,name,age,salary) values (3,'qqq',23,120);
insert into emps(id,name,age,salary) values (4,'www',24,130);
insert into emps(id,name,age,salary) values (5,'aaa',25,140);
insert into emps(id,name,age,salary) values (6,'qzzzqq',26,150)

3、配置檔案

工程配置檔案結構:
這裡寫圖片描述

檔案說明:
1>jdbc.properties:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test02?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull
username=root
password=root
#定義初始連線數  
initialSize=0
#定義最大連線數 
maxActive=20
#定義最大空閒  
maxIdle=20
#定義最小空閒  
minIdle=1
#定義最長等待時間  
maxWait=60000  

2>log4j.properties:

#定義LOG輸出級別  
log4j.rootLogger=INFO,Console,File  
#定義日誌輸出目的地為控制檯  
log4j.appender.Console=org.apache.log4j.ConsoleAppender  
log4j.appender.Console.Target=System.out  
#可以靈活地指定日誌輸出格式,下面一行是指定具體的格式  
log4j.appender.Console.layout = org.apache.log4j.PatternLayout  
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n  

#檔案大小到達指定尺寸的時候產生一個新的檔案  
log4j.appender.File = org.apache.log4j.RollingFileAppender  
#指定輸出目錄  
log4j.appender.File.File = logs/ssm.log  
#定義檔案最大大小  
log4j.appender.File.MaxFileSize = 10MB  
# 輸出所以日誌,如果換成DEBUG表示輸出DEBUG以上級別日誌  
log4j.appender.File.Threshold = ALL  
log4j.appender.File.layout = org.apache.log4j.PatternLayout  
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n  

3>applicationContext-dao.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" xmlns:task="http://www.springframework.org/schema/task"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd  
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 引入配置檔案 -->
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />

        <!-- 連線池最大數量 -->
        <property name="maxActive" value="30"></property>
        <!-- 連線池最大空閒 -->
        <property name="maxIdle" value="5"></property>

    </bean>

    <!--spring與mybatis整合 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自動掃描mapping.xml檔案 -->
        <!-- <property name="mapperLocations" value="classpath:com/ssm/mapping/*.xml"></property> -->
        <!-- 全域性配置 -->
        <!-- 若不保留mybatis配置檔案用上面那條替換這一條 -->
        <property name="configLocation" value="classpath:sqlMapConfig.xml" />
    </bean>

    <!-- DAO介面所在包名,Spring會自動查詢其下的類 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 掃描包路徑,需要掃描多個包中間用逗號隔開 -->
        <property name="basePackage" value="andy.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>
</beans>

4>applicationContext-services.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" xmlns:task="http://www.springframework.org/schema/task"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd  
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    <!-- 自動掃描 -->
    <context:component-scan base-package="andy.service.impl" />
</beans>

5>applicationContext-transaction.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:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd  
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 資料來源dataSource在applicationContext-dao.xml中配置了 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 啟用事務 -->
    <tx:annotation-driven transaction-manager="transactionmanager" />
</beans>

6>sqlMapConfig.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>
    <mappers>
        <!-- 註冊empsMapper.xml檔案 -->
        <mapper resource="andy/mapping/EmpsMapper.xml" />
    </mappers>
</configuration>  

7>spring-mvc.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-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">
    <!-- 自動掃描該包,使SpringMVC認為包下用了@controller註解的類是控制器 -->
    <context:component-scan base-package="andy.controller" />
    <!-- 處理靜態資源 和解放MVC的原有功能-->  
    <mvc:default-servlet-handler/>  
    <mvc:annotation-driven>   </mvc:annotation-driven> 
    <!--避免IE執行AJAX時,返回JSON出現下載檔案 -->
    <bean id="mappingJacksonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <!-- 啟動SpringMVC的註解功能,完成請求和註解POJO的對映 -->
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON轉換器 -->
            </list>
        </property>
    </bean>
    <!-- 定義跳轉的檔案的前後綴 ,檢視模式配置 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 這裡的配置我的理解是自動給後面action的方法return的字串加上字首和字尾,變成一個 可用的url地址 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- 配置檔案上傳,如果沒有使用檔案上傳可以不用配置,當然如果不配,那麼配置檔案中也不必引入上傳元件包 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 預設編碼 -->
        <property name="defaultEncoding" value="utf-8" />
        <!-- 檔案大小最大值 -->
        <property name="maxUploadSize" value="10485760000" />
        <!-- 記憶體中的最大值 -->
        <property name="maxInMemorySize" value="40960" />
    </bean>

</beans>  

4、service介面及類

檔案結構:
這裡寫圖片描述
1>介面IEmpsService

package andy.service;

import andy.model.Emps;

public interface IEmpsService {  
    public Emps getEmpsById(int id);  
}  

2>實現類EmpsServiceImpl

package andy.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import andy.dao.EmpsMapper;
import andy.model.Emps;
import andy.service.IEmpsService;

@Service("empsService")  
public class EmpsServiceImpl implements IEmpsService {  
    @Resource  
    private EmpsMapper empsDao;  
    @Override
    public Emps getEmpsById(int id) {  
        // TODO Auto-generated method stub  
        return this.empsDao.selectByPrimaryKey(id);  
    }    
}  

5、controller類

檔案結構:
這裡寫圖片描述

類EmpsController:

package andy.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;  

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.stereotype.Controller; 

import andy.model.Emps;
import andy.service.IEmpsService;  

@Controller  
@RequestMapping("/emps")  // url路徑
public class EmpsController {  
    @Resource  
    private IEmpsService empsService;  

    @RequestMapping("/getById")  //url路徑
    public ModelAndView  getById(HttpServletRequest request,ModelAndView model){  
        int id = Integer.parseInt(request.getParameter("id"));  
        Emps emps = this.empsService.getEmpsById(id);  
        model.addObject("emps", emps); //檢視模型,向頁面傳遞物件
        model.setViewName("empsList");  //指定檢視檔案,路徑在spring-mvc下指定
        return model;  
    }  
}