SpringMVC+Spring+Mybatis整合

建立web工程

用eclipse或idea建立一個web工程,在這裏演示使用idea,項目命名爲ssmhtml

創建工程目錄框架

根據習慣,簡歷包目錄,分別爲前端

  1. config
    在其中建立兩個子包mybatis和spring,分別用來放置spring、mybatis配置文件
  2. mapper
    用來放置mybatis的mapper接口和mapper.xml
  3. service
    service層的javabean
  4. controller
    controller的javabean
  5. pojo
    簡單的POJO類

這裏寫圖片描述

在WEB-INF下創建兩個目錄java

  1. lib
    jar包目錄
  2. views
    jsp視圖目錄

這裏寫圖片描述

導入jar包

一共須要以下jar包mysql

  1. spring全部包
  2. mybatis
  3. spring-mybatis整合包
  4. aspectj
  5. jstl
  6. log4j
  7. c3p0
  8. mysql

這裏寫圖片描述

百度雲下載 連接:http://pan.baidu.com/s/1dDB8cxV 密碼:3cqpweb

添加mybatis配置文件

在config.mybatis下建立mybatis.xml配置文件,SSM整合和mybatis在不須要二級緩存等配置時,mybatis配置文件只須要一個框架,不須要書寫具體內容,框架以下spring

<?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和springmvc配置文件

  • springmvc

在config.spring下建立springmvc.xml文件,用來配置springmvcsql

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


       <!--自動掃描controller 加入IOC容器-->
       <context:component-scan base-package="com.elin4it.ssm.controller"/>

       <!--配置映射器和適配器-->
       <mvc:annotation-driven></mvc:annotation-driven>

       <!--配置視圖渲染類-->
       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <!--配置物理解析路徑-->
              <property name="prefix" value="/WEB-INF/views/"/>
              <property name="suffix" value=".jsp"/>
       </bean>


</beans>
  • applicationContext-dao.xml

在config.spring下建立applicationContext-dao.xml文件,用來配置DAO層的內容,在這裏鏈接數據庫的數據源使用C3P0,因此在這以前先在config中添加db.properties來指定數據庫鏈接信息數據庫

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://127.0.0.1:3306/mybatis?characterEncoding=UTF-8
jdbc.username = root
jdbc.password = root

applicationContext-dao.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" 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">

       <!--添加數據庫配置文件-->
       <context:property-placeholder location="classpath:com/elin4it/ssm/config/db.properties"/>

       <!--設置數據源c3p0-->
       <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
              <property name="driverClass" value="${jdbc.driver}"/>
              <property name="jdbcUrl" value="${jdbc.url}"/>
              <property name="user" value="${jdbc.username}"/>
              <property name="password" value="${jdbc.password}"/>
              <property name="maxPoolSize" value="50"/>
              <property name="minPoolSize" value="5"/>
              <property name="maxIdleTime" value="60"/>
       </bean>

       <!--配置sqlsessionFactory-->
       <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
              <!--配置mybatis配置文件-->
              <property name="configLocation" value="classpath:com/elin4it/ssm/config/mybaits/SqlMapConfig.xml"/>
              <!--配置數據源-->
              <property name="dataSource" ref="dataSource"/>
       </bean>

       <!--配置自動掃描mapper,將mapper接口加入到IOC容器-->
       <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
              <property name="basePackage" value="com/elin4it/ssm/mapper"/>
              <property name="sqlSessionFactoryBeanName" value="sqlSession"/>
       </bean>
</beans>
  • applicationContext-service.xml

在config.spring中添加applicationContext-service.xml,用來把service層的javabean注入到IOC容器中後端

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


       <!--將service加入到IOC容器-->
       <context:component-scan base-package="com.elin4it.ssm.service"/>
</beans>
  • applicationContext-transtion.xml

在config.spring中添加applicationContext-transtion.xml,用來配置AOP事務

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

       <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
              <property name="dataSource" ref="dataSource"/>
       </bean>

       <tx:advice id="txAdvice" transaction-manager="transactionManager">
              <tx:attributes>
                     <tx:method name="find*" propagation="REQUIRED"/>
                     <tx:method name="add*" propagation="REQUIRED"/>
                     <tx:method name="delete*" propagation="REQUIRED"/>
                     <tx:method name="update*" propagation="REQUIRED"/>
              </tx:attributes>
       </tx:advice>

       <aop:config>
              <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.elin4it.ssm.service.*.*(..))"/>
       </aop:config>
</beans>

添加log4j配置文件

爲了方便mybatis的調試,使用log4j做爲日誌輸出,在src根目錄中添加log4j.properties

log4j.rootLogger=DEBUG,Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.org.apache=INFO

修改web.xml文件

web.xml須要實現三個功能

  • 配置spring文件
<!--設置spring 配置文件的位置-->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:cn/elinzhou/OrderSpringMVC/config/spring/applicationContext-*.xml</param-value>
</context-param>
<!--配置spring listener-->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
  • 配置springmvc中的前端控制器
<!--配置springmvc-->
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <!--springmvc配置文件位置-->
        <param-value>classpath:cn/elinzhou/OrderSpringMVC/config/spring/springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
  • 解決post亂碼問題
<!--解決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>

建立pojo類

這裏使用一張用戶表作示例,表結構以下

DROP TABLE IF EXISTS `user`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user` ( `id` int(11) NOT NULL auto_increment, `username` varchar(32) NOT NULL COMMENT '用戶名稱', `sex` char(1) default NULL COMMENT '性別', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8;

根據表結構創建POJO類

package cn.elinzhou.OrderSpringMVC.pojo;

import java.util.Date;

public class User {
    private Integer id;

    private String username;

    private String sex;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }
    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex == null ? null : sex.trim();
    }
}

建立mapper接口和mapper.xml

mapper.java

package com.elin4it.ssm.mapper;

import com.elin4it.ssm.pojo.User;
import java.util.List;

public interface UserMapper {
    //查詢用戶列表
    List<User> findUser() throws Exception;
}

mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.elin4it.ssm.mapper.UserMapper" >
  <select id="findUser" resultMap="com.elin4it.ssm.pojo.User">
    select
    id, username, birthday, sex, address
    from user
  </select>

</mapper>

建立service接口和實現

建立一個service接口,添加一個方法,用來查詢所用用戶
UserService.java

package com.elin4it.ssm.service;

import com.elin4it.ssm.pojo.User;

import java.util.List;

/** * Created by elin on 15-7-1. */
public interface UserService {
    List<User> findUser()throws Exception;
}

添加UserService的實現類UserServiceImpl.java

package com.elin4it.ssm.service;

import com.elin4it.ssm.mapper.UserMapper;
import com.elin4it.ssm.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/** * Description: UserServiceImpl * Author: Elin Zhou * Create: 2015-07-01 20:59 */
@Service
public class UserServiceImpl implements UserService {

    //自動注入mapper接口
    @Autowired
    private UserMapper userMapper;


    @Override
    public List<User> findUser() throws Exception {
        //調用mapper接口中的方法,獲取用戶列表
        List<User> users = userMapper.findUser();
        return users;
    }
}

建立controller

建立後端控制器,前端控制器根據用戶請求映射到後端控制器中的方法,而且返回視圖和數據來渲染視圖

package com.elin4it.ssm.controller;

import com.elin4it.ssm.pojo.User;
import com.elin4it.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/** * Description: UserController * Author: Elin Zhou * Create: 2015-07-01 19:30 */
@Controller
@RequestMapping("/user")
public class UserController {
    //自動注入service   
    @Autowired
    private UserService userService;

    @RequestMapping("/findUser")
    public String findUser(Map<String,Object> map) throws Exception{
    //調用service中的查詢用戶列表方法來獲取用戶列表
        List<User> users = userService.findUser();
        //把用戶列表放到形參傳入的map中,至關於執行request.addAttribute()方法
        map.put("users",users);

        return "user/userList";
    }
}

建立對應的jsp頁面

在WEB-INF的views文件夾中添加user文件加,用來存放用戶相關的視圖,在添加一個userList.jsp文件

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%-- Created by IntelliJ IDEA. User: elin Date: 15-7-1 Time: 下午8:53 To change this template use File | Settings | File Templates. --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title></title>
</head>
<body>
  <h1>userList</h1>
  <table>
    <tr><td>id</td><td>username</td><td>sex</td></tr>
    <c:forEach items="${users}" var="i">
      <tr>
        <td>${i.id}</td>
        <td>${i.username}</td>
        <td>${i.sex}</td>
      </tr>
    </c:forEach>
  </table>
</body>
</html>
相關文章
相關標籤/搜索