1、基本概念

1.1、Spring

        Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。 简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。

1.2、SpringMVC  

        Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring MVC 分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。

1.3、MyBatis

       MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。MyBatis是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO)MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

 

2.需要的jar包

   需要的jar包主要分为以下几类:

      1.mysql数据库驱动包以及数据库连接池相关包

      2.mybatis框架包和mybatis+spring框架整合包

      3.spring包

jar包如下图所示:

3.配置school-mybatis.xml

      该配置文件默认存放在src目录下,school-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:mybatis="http://mybatis.org/schema/mybatis-spring"  
       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://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd  
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">      
    
     <!-- 自动扫描 -->  
    <context:component-scan base-package="cn.wallance" />  
    <!-- 引入配置文件 -->  
    <bean id="propertyConfigurer"  
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="location" value="classpath:jdbc.properties" />  
    </bean>  
  
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
        destroy-method="close">  
        <property name="driverClassName" value="${driver}" />  
        <property name="url" value="${url}" />  
        <property name="username" value="${username}" />  
        <property name="password" value="${password}" />  
        
        <!-- 配置连接池的初始值 -->
        <property name="initialSize" value="1" />
        <!-- 连接池的最大值 -->
        <!-- <property name="maxActive" value="500"/> -->
        <!-- 最大空闲时,当经过一个高峰之后,连接池可以将一些用不到的连接释放,一直减少到maxIdle为止 -->
        <!-- <property name="maxIdle" value="2"/> -->
        <!-- 当最小空闲时,当连接少于minIdle时会自动去申请一些连接 -->
        <property name="minIdle" value="1" />
        <property name="maxActive" value="100" />
        <property name="maxIdle" value="20" />
        <property name="maxWait" value="1000" /> 
    </bean>  
    
    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <!-- 自动扫描mapping.xml文件 -->  
        <property name="mapperLocations" value="classpath:cn/wallance/mapping/*.xml"></property>  
    </bean>  
  
    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="cn.wallance.dao" />  
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
    </bean>  
  
    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->  
    <bean id="transactionManager"  
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean>    
         
</beans>

ps:jdbc.properties文件内容如下所示:

 

4.配置school-servlet.xml文件

  school-servlet.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:context="http://www.springframework.org/schema/context"
    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-3.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

      <!-- 开启注解 -->
      <mvc:annotation-driven/>
      <!-- 设置组件扫描的基础包 -->
      <context:component-scan base-package="cn.wallance.web"/>
      
      <!-- 配置视图解析器 -->
      <bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
          <property name="prefix" value="/WEB-INF/school/" />
          <property name="suffix" value=".jsp" />
      </bean>
      
      

        
</beans>

 

 5.配置web.xml,整合SSM框架

   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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 
  <!-- 配置DispatcherServlet -->
  <servlet>
     <servlet-name>school</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
     <servlet-name>school</servlet-name>
     <url-pattern>/</url-pattern>
  </servlet-mapping>
  
 
  <!-- Spring 的监听器可以通过这个上下文参数来获取school-mybatis.xml的位置 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:school-mybatis.xml</param-value>   
  </context-param>
  
    <!-- 创建Spring的监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  

  
  <!-- 创建字符过滤器 -->
  <filter>
     <filter-name>CharacterFilter</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>CharacterFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  
</web-app>

 

6.项目整体框架

6.1 dao包介绍

   主要是数据库操作(基于mybatis),分别是一个dao接口和一个dao类。

   IUserDao接口:

package cn.wallance.dao;

import java.util.List;

import cn.wallance.domain.User;

public interface IUserDao {
    public abstract List<User> selectAll();
}

  IUSerDaoImpl类:

package cn.wallance.dao;

import java.util.List;

import javax.annotation.Resource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;

import cn.wallance.domain.User;

@Repository("userDao")
public class UserDaoImpl extends SqlSessionDaoSupport implements IUserDao {
    
    
    @Resource
    public void setSuperSessionFactory(SqlSessionFactory sessionFactory){
        this.setSqlSessionFactory(sessionFactory);
    }
    
    
    public List<User> selectAll() {
        // TODO Auto-generated method stub
        List<User> users = this.getSqlSession().selectList("getUser");
        return users;
    }

}

   6.2 service包

    IUSerService接口:

package cn.wallance.service;

import java.util.List;

import cn.wallance.domain.User;

public interface IUserService {
    public abstract List<User> selectAll();

}

  UserServiceImpl类:

package cn.wallance.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import cn.wallance.dao.IUserDao;
import cn.wallance.domain.User;


@Service("userService")
public class UserServiceImpl implements IUserService {
    private IUserDao userDao;
    
    
    public IUserDao getUserDao() {
        return userDao;
    }

    @Resource
    public void setUserDao(IUserDao userDao) {
        this.userDao = userDao;
    }


    @Override
    public List<User> selectAll() {
        // TODO Auto-generated method stub
        return userDao.selectAll();
    }

}

    6.3 mapping包

  该包下主要是mapper文件

  usermapper.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="cn.wallance.mapping.classMapper">
    <select id="getUser" resultType="cn.wallance.domain.User">
        select * from users
    </select>
</mapper>

    6.4 domain包

      该包下主要是实体类。

     USer类如下所示:

package cn.wallance.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;


@Entity
public class User {
    private int id;
    private String name;
    private int age;
    
    public User(){
    }
    
    public User(int id, String name, int age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }
    
    @GeneratedValue
    @Id
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    

}

   6.5.web包

    该包下主要是contrller类: 

package cn.wallance.web;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.wallance.domain.User;
import cn.wallance.service.IUserService;


@Controller
public class HomeController {
    private IUserService userService;
    
    
    public IUserService getUserService() {
        return userService;
    }

    @Resource
    public void setUserService(IUserService userService) {
        this.userService = userService;
    }


    @RequestMapping(value="/",method=RequestMethod.GET)
    public String home(Model model){
        List<User> users = userService.selectAll();
        model.addAttribute("users", users);
        return "home";
    }

}

   6.6 Jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP \'index.jsp\' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
    <table>
       <tr>
        <td>ID</td>
        <td>NAME</td>
        <td>AGE</td>
       </tr>
       <c:forEach items="${users}" var="user">
       <tr>
       <td>${user.id}</td>
       <td>${user.name}</td>
       <td>${user.age}</td>
       </tr>
       </c:forEach>
    </table>
  </body>
</html>

 

7.项目实际运行效果

至此,SSM框架整合工作已经全部完成,大家可以在此基础上进行进一步的功能扩展!

 

写在最后:

     代码GitHub地址:https://github.com/bywallance01/SSM_School_System

 

 

     

版权声明:本文为bywallance原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/bywallance/archive/2016/10/19/5978583.html