springmvc整合mybatis

導(dǎo)入所需要的jar包

  • spring的jar包
  • mybatis的jar包
    • mybatis-3.4.5.jar
    • mybatis-spring-1.3.1.jar
  • springmvc的jar包
    • spring-webmvc-5.0.0.RELEASE.jar

配置mybatis: mybatis.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>
  <!--可以在這里配置別名-->
</configuration>

配置spring dao層: spring-dao.xml

db.properties:

jdbcUrl=jdbc:mysql://localhost:3306/test
driverClass=com.mysql.jdbc.Driver
user=root
password=root
minPoolSize=5 
maxPoolSize=30
initialPoolSize=10
maxIdleTime=60
acquireIncrement=5
idleConnectionTestPeriod=60
acquireRetryAttempts=30

spring-dao.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.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util.xsd">

    <!-- 加載配置文件 -->
    <context:property-placeholder location="classpath:db.properties"/>

    <!-- 配置數(shù)據(jù)源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="${driverClass}"/>
        <property name="jdbcUrl" value="${jdbcUrl}"/>
        <property name="user" value="${user}"/>
        <property name="password" value="${password}"/>
        <!--連接池中保留的最小連接數(shù)。-->
        <property name="minPoolSize" value="${minPoolSize}"/>
        <!--連接池中保留的最大連接數(shù)。Default: 15 -->
        <property name="maxPoolSize" value="${maxPoolSize}"/>
        <!--初始化時獲取的連接數(shù),取值應(yīng)在minPoolSize與maxPoolSize之間。Default: 3 -->
        <property name="initialPoolSize" value="${initialPoolSize}"/>
        <!--最大空閑時間,maxIdleTime秒內(nèi)未使用則連接被丟棄。若為0則永不丟棄。Default: 0 -->
        <property name="maxIdleTime" value="${maxIdleTime}"/>
        <!--當(dāng)連接池中的連接耗盡的時候c3p0一次同時獲取的連接數(shù)。Default: 3 -->
        <property name="acquireIncrement" value="${acquireIncrement}"/>
        <!--每60秒檢查所有連接池中的空閑連接。Default: 0 --> 
        <property name="idleConnectionTestPeriod" value="${idleConnectionTestPeriod}"/>
        <!--定義在從數(shù)據(jù)庫獲取新連接失敗后重復(fù)嘗試的次數(shù)。Default: 30 -->
        <property name="acquireRetryAttempts" value="${acquireRetryAttempts}"/>
    </bean>
    
    <!-- SQLSessionFactory的配置 -->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis/Configuration.xml"/>
        <!-- 掃描domain包 使用別名 -->
        <property name="typeAliasesPackage" value="com.gongxm.domain"/>
    </bean>
    <!-- mapper代理形式dao的配置 -->
    <!-- 配置包掃描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.gongxm.mapper"/>
    </bean>

</beans>

配置service層: spring-service.xml

spring-service.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.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util.xsd">

    <!-- 配置包掃描器 -->
    <context:component-scan base-package="com.gongxm.service"/>
    
</beans>

配置事務(wù)層: spring-tx.xml

spring-tx.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.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util.xsd">
    
    <!-- 事務(wù)管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 指定數(shù)據(jù)源 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!-- 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    
    <!-- 切面 -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.gongxm.service.*.*(..))"/>
    </aop:config>
    
</beans>

配置springmvc: springmvc.xml

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

    <!-- 配置包掃描器,掃描controller -->
    <context:component-scan base-package="com.gongxm.controller"/>
    
    <!-- 配置注解驅(qū)動, 配置了這個就不用配置處理器和適配器了 -->
    <mvc:annotation-driven/>
    
    <!-- 配置視圖解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

配置web.xml

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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>springmvc-mybatis</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
    
    <!-- 初始化spring容器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/spring-*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoader</listener-class>
    </listener>
    
    <!-- 配置前端控制器 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <!-- 指定springmvc的配置文件位置 -->
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

</web-app>

數(shù)據(jù)綁定

  • springmvc默認支持的數(shù)據(jù)類型: 請求可以直接使用的對象, 以及返回的類型
    @RequestMapping("/itemEdit") //方法中的這些參數(shù)都是由框架傳遞, 需要使用哪個就定義哪個
    public String editItem(HttpServletRequest request, 
            HttpServletResponse response, HttpSession session, Model model) {
        //從request中取參數(shù)
        String strId = request.getParameter("id");
        int id = new Integer(strId);
        //調(diào)用服務(wù)
        Items items = itemService.getItemById(id);
        //把結(jié)果傳遞給頁面
        //ModelAndView modelAndView = new ModelAndView();
        //modelAndView.addObject("item", items);
        //設(shè)置邏輯視圖
        //modelAndView.setViewName("editItem");
        //return modelAndView;
        //設(shè)置返回結(jié)果
        model.addAttribute("item", items);
        //返回邏輯視圖
        return "editItem";
    }
  • 簡單類型的數(shù)據(jù)綁定
    // 直接寫Integer id就可以接收到客戶端發(fā)送過來的id參數(shù), 
    //不過方法上的參數(shù)名必須要與客戶端的參數(shù)名相同!
    @RequestMapping("/itemEdit") 
    public String editItem(Integer id, Model model) {
        Items items = itemService.getItemById(id);
        //把數(shù)據(jù)傳遞給頁面
        model.addAttribute("item", items);
        //返回邏輯視圖
        return "editItem";
    }
  • 當(dāng)請求參數(shù)名稱與方法參數(shù)名稱不一致時, 可以使用注解進行映射:
    @RequestMapping("/itemEdit")
    public String editItem(@RequestParam(value="id",defaultValue="1",required=true)Integer ids, Model model) {
        Items items = itemService.getItemById(ids);
        //把數(shù)據(jù)傳遞給頁面
        model.addAttribute("item", items);
        //返回邏輯視圖
        return "editItem";
    }

@RequestParam(value="id",defaultValue="1",required=true)Integer ids
意思是把請求參數(shù)中的id映射到ids上, 如果沒有該參數(shù), 可以使用默認值: defaultValue="1"
required=true的意思是該參數(shù)必須要有值

  • 當(dāng)需要接收一個pojo類型的參數(shù)時, 要求表單中的name屬性與pojo的屬性名相同!
    @RequestMapping("/updateitem")
    public String updateItem(Items items) {
        itemService.updateItem(items);
        //返回成功頁面
        return "success";
    }
  • 綁定包裝pojo
    包裝對象定義如下:
Public class QueryVo {
  private Items items;
}

頁面定義:

<input type="text" name="items.name" />
<input type="text" name="items.price" />

Controller方法定義如下:

    @RequestMapping("/queryitem")
    public String queryItem(QueryVo queryVo) {
        //打印綁定結(jié)果
        System.out.println(queryVo.getItems().getId());
        System.out.println(queryVo.getItems().getName());
        return "success";
    }
  • 自定義參數(shù)綁定
    自定義Converter
public class DateConverter implements Converter<String, Date> {

    @Override
    public Date convert(String source) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return simpleDateFormat.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}

配置Converter

    <!-- 加載注解驅(qū)動 -->
    <mvc:annotation-driven conversion-service="conversionService"/>
    <!-- 轉(zhuǎn)換器配置 -->
    <bean id="conversionService"
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.gongxm.convert.DateConverter"/>
            </set>
        </property>
    </bean>

配置方式2(了解)

<!-- 轉(zhuǎn)換器配置 -->
    <bean id="conversionService"
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.gongxm.convert.DateConverter"/>
            </set>
        </property>
    </bean>
    <!-- 自定義webBinder -->
    <bean id="customBinder" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
        <property name="conversionService" ref="conversionService" />
    </bean>
    <!--注解適配器 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
         <property name="webBindingInitializer" ref="customBinder"></property> 
    </bean>
    <!-- 注解處理器映射器 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>

解決POST亂碼的問題

在web.xml文件中加入以下內(nèi)容:

    <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>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,362評論 6 544
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,577評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,486評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,852評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 72,600評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,944評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,944評論 3 447
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,108評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,652評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 41,385評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,616評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,111評論 5 364
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,798評論 3 350
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,205評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,537評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,334評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 48,570評論 2 379

推薦閱讀更多精彩內(nèi)容