Spring MVC + Spring + MyBatis 框架整合

本文介紹使用SSM框架開發web項目Demo.html

 

1、建立一個web-Poject項目前端

  1.導入相關jar文件至lib下。「相關jar文件」 --提取密碼 oraw java

  2.修改web.xml文件mysql

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name>    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 加載spring容器 -->
   <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:app.xml</param-value>
  </context-param>
  
  <!-- 前端控制器 -->
  <servlet>
      <servlet-name>DispatcherServlet</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <init-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>classpath:springmvc-servlet.xml</param-value>
     </init-param>
  </servlet>
  
  
  <servlet-mapping>
          <servlet-name>DispatcherServlet</servlet-name>
          <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <!-- 解決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>
  </filter>
  
  <filter-mapping>
          <filter-name>characterEncodingFilter</filter-name>
          <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

 

 

2、建立相關配置文件。web

  1.mybatis核心配置文件---mybatis-config.xmlspring

<?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="lazyLoadingEnabled" value="false" />  
        </settings>  
        
    <!-- 配置別名 --> <typeAliases> <package name="com.test.pojo"/> </typeAliases> </configuration>

  2.建立jdbc.properties文件,用於鏈接數據庫相關配置(案例鏈接mysql數據庫)sql

1 driverClassName=com.mysql.jdbc.Driver 2 url=jdbc\:mysql\://localhost\:端口號/數據庫名?useUnicode\=true&characterEncoding\=UTF-8 3 password=ok 4 uname=root

注意:須要改寫上面文件中的端口號和數據庫名方可以使用,mysql默認端口爲3306;數據庫

  3.建立spring核心配置文件,本文案例名稱爲app.xml,可根據本身喜愛起名(特殊字符除外),可是要和web.xml映射的spring配置文件名一致。express

<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- 掃包(service層) -->
    <context:component-scan base-package="com.test.service" />
    
    <!-- 導入鏈接池配置文件 -->
    <context:property-placeholder location="classpath:jdbc.properties" />

    <!-- 數據源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" scope="singleton">
        <property name="driverClassName" value="${driverClassName}"></property>
        <property name="url" value="${url}"></property>
        <property name="username" value="${uname}"></property>
        <property name="password" value="${password}"></property>
    </bean>

    <!-- 配置mybatis SqlSessionFactoryBean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis-config.xml" />
    </bean>


    <!-- Mapper接口所在包名,Spring會自動查找其下的Mapper -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.test.mapper" />
    </bean>


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

    <!-- 事務管理 -->
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" read-only="false" isolation="DEFAULT" />
            <tx:method name="del*" propagation="REQUIRED" read-only="false" isolation="DEFAULT" />
            <tx:method name="update*" propagation="REQUIRED" read-only="false" isolation="DEFAULT" />
            <tx:method name="get*" propagation="NEVER" read-only="true" />
            <tx:method name="query*" propagation="NEVER" read-only="true" />
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <!-- 定義切點 -->
        <aop:pointcut expression="execution(* com.test.service..*.*(..))" id="pointCut" />
        <aop:advisor advice-ref="transactionAdvice" pointcut-ref="pointCut" />
    </aop:config>
</beans>

 

  4.建立springmvc核心配置文件,本文案例名稱爲springmvc-servlet.xml,可根據本身喜愛起名(特殊字符除外),可是要和web.xml中前端控制器映射的配置文件名一致。apache

<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.test.controller"></context:component-scan>


    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json</value>
                    </list>
                </property>
                <property name="features">
                    <list>
                        <value>WriteDateUseDateFormat</value>
                    </list>
                </property>
            </bean>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>


    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="favorParameter" value="true"></property>
        <property name="mediaTypes">
            <map>
                <entry key="json" value="application/json;charset=UTF-8"></entry>
                <entry key="html" value="text/html;charset=UTF-8"></entry>
            </map>
        </property>
        <property name="viewResolvers">
            <list>
                <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="prefix" value="/WEB-INF/jsp/"></property>
                    <property name="suffix" value=".jsp"></property>
                </bean>
            </list>
        </property>
    </bean>
</beans>

 

3、建立須要的包。

先建立一個簡單的數據庫。別忘記修改jdbc.properties文件鏈接數據庫相關配置。

1.實體類、2.控制器 3.數據訪問層 4.業務邏輯層

 

1.建立實體類----屬性和數據庫字段名最好一致,方便映射。

 1 package com.test.pojo;  2 
 3 public class Person {  4     private int id;  5     private String name;  6     public int getId() {  7         return id;  8  }  9     public void setId(int id) { 10         this.id = id; 11  } 12     public String getName() { 13         return name; 14  } 15     public void setName(String name) { 16         this.name = name; 17  } 18 }

2.建立mapper接口和mapper.xml,注意mapper接口和mapper.xml文件名一致,掃包spring容器管理機制.

 

  (1)mapper接口。(查詢操做)

package com.test.mapper; import java.util.List; import com.test.pojo.Person; public interface PersonMapper { List<Person> getPerson();//查詢全部數據
}

  (2)mapper.xml

1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE mapper SYSTEM "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
3 <mapper namespace="com.test.mapper.PersonMapper">
4     <select id="getPerson" resultType="Person">
5  SELECT * FROM person 6     </select>
7 </mapper>

3.建立service層。

  (1)service接口

1 package com.test.service; 2 
3 import java.util.List; 4 
5 import com.test.pojo.Person; 6 
7 public interface PersonService { 8     List<Person> getPerson(); 9 }

  (2)service實現類

 

 1 package com.test.service;  2 
 3 import java.util.List;  4 
 5 import javax.annotation.Resource;  6 
 7 import org.springframework.beans.factory.annotation.Autowired;  8 import org.springframework.stereotype.Service;  9 
10 import com.test.mapper.PersonMapper; 11 import com.test.pojo.Person; 12 
13 @Service 14 public class PersonServiceImp implements PersonService { 15 
16     //兩種注入方式 任選其一 17     
18     // @Resource注入,按名稱注入 名稱爲mapper接口名首字母小寫
19     @Resource(name = "personMapper") 20     private PersonMapper personMapper; 21     
22     /* @Autowired注入,按類型注入 23  @Autowired 24  private PersonMapper personMapper;*/
25     
26     
27  @Override 28     public List<Person> getPerson() { 29         return personMapper.getPerson(); 30  } 31 
32 }

 

 4.建立控制器。

package com.test.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.test.pojo.Person;
import com.test.service.PersonService;

@Controller
public class PersonController {
	
	
	@Autowired
	private PersonService personService;
	
     //返回json格式數據 @RequestMapping("/index") @ResponseBody public Object show(){ List<Person> list = personService.getPerson(); return list; } }

  

 5.部署項目運行。

相關文章
相關標籤/搜索