spring mvc+myBatis配置詳解


spring mvc

Spring框架(框架即:編程注解+xml配置的方式)MVC是Spring框架的一大特征,Spring框架有三大特征(IOC(依賴注入),AOP(面向切面),MVC(建模M-視圖V-控制器C)。框架一般用於團隊開發,使用分層的方式使每個人完成不同的模塊,然后再組合在一起,使完成項目。

以下是Spring mvc具有的能加速開發的功能列表:

  • Spring mvc中提供了一個DispatchServlet,無需額外開發
  • Spring mvc中使用基於xml的配置文件,可以編輯,而無需重新編譯應用程序
  • Spring mvc實例化控制器,並根據用戶輸入來構造Bean。
  • Spring mvc可以自動綁定用戶輸入,並正確的轉換數據類型。例如,Spring mvc能自動解析字符串,並設置float或decimal類型的屬性.
  • Spring mvc可以校驗用戶輸入,若校驗不通過,則重定向回輸入表單。輸入校驗是可選的,支持編程方式以及聲明。關於這一點,Spring mvc內置了常見的校驗器
  • Spring mvc是Spring框架的一部分,可以利用Spring提供的其他能力。
  • Spring mvc支持國際化和本地化。支持根據用戶區域顯示多國語言
  • Spring mvc支持多種視圖技術。最常見的JSP技術以及其他技術包括Velocity和FreeMarker.

配置spring mvc

1、導入Spring需要的jar 包

  

2、配置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:context="http://www.springframework.org/schema/context" 
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
    xmlns:jee="http://www.springframework.org/schema/jee" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<!-- HandlerMapping -->
<mvc:annotation-driven/>
開啟spring mvc注解掃描,如果不基於注解:   該類需要繼承  CommandController   或者 其他很多 參見  spring幫助.我用的是基於注解的,這樣比較方便
<!-- 掃描Controller,Service -->
<context:component-scan 
    base-package="com.包名"/>
開啟組件掃描,請確保所有的控制器都在基本包下,並且不要制定一個太寬泛的基本包
</beans>

補充:

  第一個為開啟spring mvc注解掃描,如果不基於注解:   該類需要繼承  CommandController   或者 其他很多 參見  spring幫助.我用的是基於注解的,這樣比較方便

  第二個為開啟組件掃描

    Spring使用掃描機制來找到應用程序中所有基於注解的控制器類,為了能保證Spring你那個找到你的控制器,

    a.需要在Spring mvc中配置spring-context

    b.在<context:component-scan base-package="com.包名"/>元素中指定控制器類的基本包

基於此,在Controller中可以方便調用了,實例見最下方

 3.部署web.xml

DispatcherServlet作為Spring mvc框架中的一級控制器(前端控制器),是瀏覽器發送請求的入口

該Servlet的全稱是org.springframework.web.servlet.DispatcherServlet.

要使用這個Servlet,需要把他配置在部署描述符(web.xml),應用servlet和servlet-mapping元素如下:

相關解釋:

1、servlet元素內的on-startup元素是可選的。if存在,表示它將在應用程序啟動時就裝在servlet並調用它的init方法。else,則在該servlet的第一個請求是加載。

2、Dispatcher Servlet將會使用spring mvc諸多默認組件。此外,初始化時,它會尋找一個在應用程序下的web-INF目錄下 的配置文件,該配置文件的命名規則如下;

    servletName-servlet.xml

其中servletName是在部署描述符中的Dispatcher Servlet的名字。如圖所示,本例中的servlet-name為springmvc,則在初始化的時候會找到第二步配置的springmvc.xml文件.

3、當然springmvc.xml文件也可以放到應用程序目錄中的任何地方,<init-param></init-param>元素就是為了實現這個功能的。

其中的<param-name>不用改,而<param-value>則包含配置文件的路勁。

補充一下:(1)Spring可以通過指定classpath*:與classpath:前綴加路徑的方式從classpath加載文件,如bean的定義文件.

  classpath*:的出現是為了從多個jar文件中加載相同的文件.

  classpath:只能加載找到的第一個文件

     (2) url-pattern的寫法

    1 三種寫法

    ① 完全匹配

        <url-pattern>/test/list.do</url-pattern>

    ② 目錄匹配

        <url-pattern>/test/*</url-pattern>

    ③ 擴展名匹配

      <url-pattern>*.do</url-pattern>

    2 注意事項

  • 容器會首先查找完全匹配,如果找不到,再查找目錄匹配,如果也找不到,就查找擴展名匹配。
  • 如果一個請求匹配多個“目錄匹配”,容器會選擇最長的匹配。
  • 定義”/*.action”這樣一個看起來很正常的匹配會報錯?因為這個匹配即屬於路徑映射,也屬於擴展映射,導致容器無法判斷。
  • “/” 是用來定義default servlet映射的。
  • *.do它不是一個文件,並沒有一個真正的.do文件存在,只是一個servlet映射.意思是URL里一切以.do結尾的URL都驅動servlet里設置的那個類;
    而*則是所有請求都交由servlet里設置的那個類處理!

二、MyBatis的配置和使用

  Spring與MyBatis結合,主要是由Spring管理數據庫訪問組件Dao,數據庫訪問組件主要是基於MyBatis實現,在Spring環境中使用MyBatis實現數據庫訪問組件過程是:首先需要引入一個Spring和MyBatis整合的開發包 mybatis-spring-1.2.2.jar。在Spring配置中定義SqlSessionFactoryBean,等價於SqlSessionFactory放入Spring容器管理。(不需要開發者利用手工創建SqlSessionFactory對象,需要開發者定義式注入連接信息和SQL定義的XML信息)在Spring配置中定義MapperFactoryBean,可以根據指定的Mapper接口生成一個Mapper實現類接口。需引入引入開發包:spring ioc,spring aop,dbcp,mybatis,驅動,mybatis-spring.jar。添加Spring框架的配置文件主要有applicationContext.xml,根據user表編寫實體類User,編寫UserMapper.xml(定義SQL語句),並且編寫UserMapper接口(與UserMapper.xml映射),在applicationContext.xml中配置組件SqlSessionFactoryBean,Mapper FactoryBean。最后測試MapperFactoryBean生成的UserMapperDao實例。

  MyBatis的兩個特點:

  1.MyBatis采用SQL與Entity映射,對JDBC封裝程度較輕

  2.MyBatis自己寫SQL,更具有靈活性

 配置MyBatis

(1)導入jar包

 

 (2)創建數據庫

 (3)添加MyBatis.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:jdbc="http://www.springframework.org/schema/jdbc"  
    xmlns:jee="http://www.springframework.org/schema/jee" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">

<bean id="dbcp" 
class="org.apache.commons.dbcp.BasicDataSource">
    <property name="username" value="****">
    </property>
    <property name="password" value="***">
    </property>
    <property name="driverClassName" 
        value="com.mysql.jdbc.Driver">
    </property>
    <property name="url" 
        value="jdbc:mysql:///cloud_note">
    </property>

    <!-- <property name="url" value="jdbc:mysql://localhost:3306/cloud_note?useUnicode=true&amp;characterEncoding=utf-8"></property> -->
</bean>

<bean id="ssf" 
class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dbcp">
    </property>
    <property name="mapperLocations" 
value="classpath:com/niuniu/sql/*.xml">
    </property>
</bean>

<bean id="mapperscanner" 
class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="sqlSessionFactory" ref="ssf">
    </property>
    <property name="basePackage" 
        value="com.niuniu.dao">
    </property>
</bean>

</beans>

  (4)定義表所對應的實體類,如下圖所示

  

  代碼如下:

package com.niuniu.entity;

import java.io.Serializable;

public class User implements Serializable {
    private String cn_user_id;
    private String cn_user_name;
    private String cn_user_password;
    private String cn_user_token;
    private String cn_user_nick;
    public String getCn_user_id() {
        return cn_user_id;
    }
    public void setCn_user_id(String cnUserId) {
        cn_user_id = cnUserId;
    }
    public String getCn_user_name() {
        return cn_user_name;
    }
    public void setCn_user_name(String cnUserName) {
        cn_user_name = cnUserName;
    }
    public String getCn_user_password() {
        return cn_user_password;
    }
    public void setCn_user_password(String cnUserPassword) {
        cn_user_password = cnUserPassword;
    }
    public String getCn_user_token() {
        return cn_user_token;
    }
    public void setCn_user_token(String cnUserToken) {
        cn_user_token = cnUserToken;
    }
    public String getCn_user_nick() {
        return cn_user_nick;
    }
    public void setCn_user_nick(String cnUserNick) {
        cn_user_nick = cnUserNick;
    }
    
}

  (5)定義操作users表的sql映射文件UserMapping.xml

  

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"      
 "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="com.niuniu.dao.UserDao">

<insert id="save" parameterType="com.niuniu.entity.User">
    insert into cn_user(
        cn_user_id,cn_user_name,
    cn_user_password,cn_user_token,
    cn_user_nick)
    values(#{cn_user_id},#{cn_user_name},#{cn_user_password},#{cn_user_token},#{cn_user_nick})
</insert>
<select id="findByName" parameterType="string"
resultType="com.niuniu.entity.User">
select * from cn_user
where cn_user_name=#{name}
</select>

</mapper>

  (6)寫Controller,進行測試。

@Controller//將類名前加上該注解,當spring啟動或者web服務啟動  spring會自動掃描所有包(當然,這個可以設置,見上述Springmvc的配置)

         作用:  就是告訴服務器這個類是MVC中的C, 這個類可以接收用戶請求、處理用戶請求


@RequestMapping("/note")//這個控制類里面可以有很多方法,哪個方法用來處理用戶請求,就在那個方法前面 加  @RequestMapping(“/xxxxx請求路徑”)

public class LoadNoteDetailController {
    @Resource//直接使用@Resource注解一個域(field)同樣是可能的。通過不暴露setter方法,代碼愈發緊湊並且還提供了域不可修改的額外益處。
//正如下面將要證明的,@Resource注解甚至不需要一個顯式的字符串值,在沒有提供任何值的情況下,域名將被當作默認值。
//該方式被應用到setter方法的時候,默認名是從相應的屬性衍生出來,換句話說,命名為'setDataSource'的方法被用來處理名為'dataSource'的屬性。
private NoteService noteService; @RequestMapping("/loaddetail.do")//映射到JSP的前台頁面中ajax發布的請求,打開相應的頁面↑ @ResponseBody public NoteResult execute(String noteId){ NoteResult result=noteService.loadDetail(noteId); return result;//當請求處理完畢后,返回值決定了該處理完畢后,用戶將跳轉到那個頁面.這個很重要。service調util } }

 知識補充:

 

@Resource

 

@Resource默認按照ByName自動注入,有兩個重要的屬性:name和type,而Spring將@Resource注解的name屬性解析為bean的名字,而type屬性 則解析為bean的類型。所以,如果使用name屬性,則使用byName的自動注入策略,而使用type屬性時則使用byType自動注入策略。如果既 不制定name也不制定type屬性,這時將通過反射機制使用byName自動注入策略。

 

@ResponseBody

作用:

      該注解用於將Controller的方法返回的對象,通過適當的HttpMessageConverter轉換為指定格式后,寫入到Response對象的body數據區。

使用時機:

      返回的數據不是html標簽的頁面,而是其他某種格式的數據時(如json、xml等)使用;

 

 

    

 


免責聲明!

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



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