Spring MVC + Spring + MyBatis 框架整合

2018-07-29 08:39:57来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

本文介绍使用SSM框架开发web项目Demo.

 

一、创建一个web-Poject项目

  1.导入相关jar文件至lib下。“相关jar文件” --提取密码 oraw 

  2.修改web.xml文件

<?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>

 

 

二、创建相关配置文件。

  1.mybatis核心配置文件---mybatis-config.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>  
        <settings>  
            <setting name="lazyLoadingEnabled" value="false" />  
        </settings>  
        
    <!-- 配置别名 --> <typeAliases> <package name="com.test.pojo"/> </typeAliases> </configuration>

  2.创建jdbc.properties文件,用于连接数据库相关配置(案例连接mysql数据库)

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配置文件名一致。

<?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中前端控制器映射的配置文件名一致。

<?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> 

 

三、创建需要的包。

先创建一个简单的数据库。别忘记修改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.部署项目运行。

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:[图解Java]读写锁ReentrantReadWriteLock

下一篇:【Java学习】javac和java命令