SSM 框架快速整合实例--学生查询

一、快速准备

SSM 框架即 Spring 框架、SpringMVC 框架、MyBatis 框架,关于这几个框架的基础和入门程序,我前面已经写过几篇文章作为基础和入门介绍了。对于这 3 个框架还不熟悉的同学,可以参考一下几篇文章:

【SSH框架】之Spring系列(一)

Spring框架系列(二)之Bean的注解管理

Spring框架系列之AOP思想

Spring 框架系列之 JDBC 整合

Spring 框架系列之事务管理

SpringMVC 框架系列之初识与入门实例

SpringMVC 框架系列之组件概述与配置详解

MyBatis 框架之基础初识

MyBatis 框架之快速入门程序

如果已经陆续学习过 SSM 框架相关知识的,可以忽略掉这一部分,直接看下面的内容。

二、快速创建项目

鉴于 jar 包依赖于管理的方便,我们使用 Maven 进行项目的管理和开发,所以这一步我们使用 IDEA 快速创建一个 Maven 项目,关于如何使用 IDEA 快速创建 Maven 项目,这里就不进行过多赘述了,大家可以参考下面这篇文章:

Maven 项目管理工具基础系列(一)

三、快速配置 jar 包依赖

Maven 项目创建完成后,快速打开并配置 pom.xml 文件,具体配置如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0modelVersion>
  <groupId>com.ssm.examplegroupId>
  <artifactId>SsmDemoartifactId>
  <packaging>warpackaging>
  <version>0.0.1-SNAPSHOTversion>
  <name>SSMDemo Maven Webappname>
  <url>http://maven.apache.orgurl>
  <dependencies>

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>4.3.7.RELEASEversion>
        dependency>

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>4.3.7.RELEASEversion>
        dependency>

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aspectsartifactId>
            <version>4.3.7.RELEASEversion>
        dependency>

        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.4.2version>
        dependency>

        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>1.3.1version>
        dependency>

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.41version>
        dependency>

        
        <dependency>
            <groupId>c3p0groupId>
            <artifactId>c3p0artifactId>
            <version>0.9.1version>
        dependency>

        
        <dependency>
            <groupId>jstlgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>

        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>3.0.1version>
            <scope>providedscope>
        dependency>

        
      <dependency>
          <groupId>junitgroupId>
          <artifactId>junitartifactId>
          <version>3.8.1version>
      dependency>

  dependencies>

    
    <build>
        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
        resources>
    build>

project>

四、快速配置编码过滤和资源加载

打开 web.xml 文件,快速配置开启 Spring 、SpringMVC 编码过滤以及静态资源加载,具体配置代码如下:

<web-app>
  <display-name>Archetype Created Web Applicationdisplay-name>

  
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:applicationContext.xmlparam-value>
  context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>

  
  <servlet>
    <servlet-name>mvc-dispatcherservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:springmvc.xmlparam-value>
    init-param>
  servlet>

  <servlet-mapping>
    <servlet-name>mvc-dispatcherservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>

  
  <filter>
      <filter-name>CharacterEncodingFilterfilter-name>
      <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
      <init-param>
          <param-name>encodingparam-name>
          <param-value>utf-8param-value>
      init-param>
      <init-param>
          <param-name>forceRequestEncodingparam-name>
          <param-value>trueparam-value>
      init-param>
      <init-param>
          <param-name>forceResponseEncodingparam-name>
          <param-value>trueparam-value>
      init-param>
  filter>
  <filter-mapping>
      <filter-name>CharacterEncodingFilterfilter-name>
      <url-pattern>/*url-pattern>
  filter-mapping>

  
  <servlet-mapping>
    <servlet-name>defaultservlet-name>
    <url-pattern>*.jsurl-pattern>
  servlet-mapping>

  <servlet-mapping>
    <servlet-name>defaultservlet-name>
    <url-pattern>*.cssurl-pattern>
  servlet-mapping>

web-app>

五、快速配置 Spring 配置文件

resources 文件夹下新建 applicationContext.xml 文件,配置 MyBatis 和数据库相关信息,具体代码配置如下:


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

    
    <context:property-placeholder location="classpath:db.properties"/>

    
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.user}">property>
        <property name="password" value="${jdbc.password}">property>
        <property name="driverClass" value="${jdbc.driverClass}">property>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}">property>
        <property name="initialPoolSize" value="5">property>
        <property name="maxPoolSize" value="10">property>
    bean>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="dataSource" ref="dataSource"/>
        
        <property name="mapperLocations" value="classpath:com/ssm/example/dao/*.xml"/>
        
        <property name="configLocation" value="classpath:mybatis-config.xml">property>
    bean>

    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        
        <property name="basePackage" value="com.ssm.example.dao"/>
    bean>

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

    
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            
            <tx:method name="*"/>
            <tx:method name="get*" read-only="true"/>
        tx:attributes>
    tx:advice>

    
    <aop:config>
        
        <aop:pointcut expression="execution(* com.ssm.example.service.impl.*.*(..))" id="txPoint"/>
        
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
    aop:config>
beans>

六、快速配置数据库连接信息

resources 文件夹下新建 db.properties 文件,配置数据库连接相关信息,具体代码配置如下:

jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm_example?useUnicode=true&characterEncoding=UTF-8
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root

七、快速配置数据库操作辅助信息

resources 文件夹下新建 mybatis-config.xml 文件,配置相关的数据库操作辅助信息,具体代码配置如下:



<configuration>
    <settings>
        
        <setting name="logImpl" value="STDOUT_LOGGING" />
    settings>

    <typeAliases>
        
        <package name="com.ssm.example.entity"/>
    typeAliases>

configuration>

八、快速配置 SpringMVC 注解扫描和视图解析器

resources 文件夹下新建 springmvc.xml 文件,配置相关的数据库操作辅助信息,具体代码配置如下:


<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-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    
    <mvc:annotation-driven />

    
    <context:component-scan base-package="com.ssm.example">context:component-scan>

    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/">property>
        <property name="suffix" value=".jsp">property>
    bean>

beans>

九、快速新建数据表

新建 MySQL 数据库,快速新建数据表 ssm_example,具体建表代码如下:


DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `gender` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `email` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `tel` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `cla` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

INSERT INTO `student` VALUES (1, '孔乙己', '男', '[email protected]', '13509856897', '计算机1班');
INSERT INTO `student` VALUES (2, '阿强', '女', '[email protected]', '12345678909', '软件工程');
INSERT INTO `student` VALUES (3, '阿福', '男', '[email protected]', '13657898762', '数学专业');
INSERT INTO `student` VALUES (4, '阿霞', '女', '[email protected]', '12378645987', '英语专业');
INSERT INTO `student` VALUES (5, '指南者', '男', '[email protected]', '13587690873', '打杂搬砖专业');

SET FOREIGN_KEY_CHECKS = 1;

十、快速新建实体类

快速新建实体类 Student.java,具体代码如下:

package com.ssm.example.entity;

public class Student {

    private int id;
    private String name;
    private String gender;
    private String email;
    private String tel;
    private String cla;

    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 String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getTel() {
        return tel;
    }
    public void setTel(String tel) {
        this.tel = tel;
    }
    public String getCla() {
        return cla;
    }
    public void setCla(String cla) {
        this.cla = cla;
    }


}

十一、快速书写业务代码

快速新建 StuentController.java 控制类,具体代码如下:

package com.ssm.example.controller;

import java.util.List;

import com.ssm.example.entity.Student;
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 com.ssm.example.service.StudentService;

@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    /**
     * 查找所有学生
     * @return
     */
    @RequestMapping(value="/findAll")
    public ModelAndView test(){
        List list = studentService.findAll();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        modelAndView.addObject("list", list);
        return modelAndView;
    }

}

快速新建 StudentService.java 接口,代码如下:

package com.ssm.example.service;

import java.util.List;

import com.ssm.example.entity.Student;

public interface StudentService {
    public List findAll();
}

快速新建 StudentServiceImpl.java 类实现接口,具体代码如下:

package com.ssm.example.service.impl;

import java.util.List;

import com.ssm.example.dao.StudentDAO;
import com.ssm.example.entity.Student;
import com.ssm.example.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDAO studentDAO;

    public List findAll() {
        // TODO Auto-generated method stub
        return studentDAO.findAll();
    }

}

快速新建 dao 接口 StudentDAO.java,具体代码如下:

package com.ssm.example.dao;

import java.util.List;

import com.ssm.example.entity.Student;

public interface StudentDAO {
    public List findAll();
}

快速新建 dao 接口代理文件 StudentDAO.xml,具体代码如下:


 

    <mapper namespace="com.ssm.example.dao.StudentDAO">

        <resultMap type="Student" id="studentMap">
            <id property="id" column="id"/>
            <result property="name" column="name"/>
            <result property="gender" column="gender"/>
            <result property="email" column="email"/>
            <result property="tel" column="tel"/>
            <result property="cla" column="cla"/>
        resultMap>

        <select id="findAll" resultMap="studentMap">
            select * from student
        select>

    mapper>

十二、新建访问页面

快速新建访问页面 index.jsp,并且页面使用 bootstrap 框架作轻度渲染,具体代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page isELIgnored="false" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>学生列表title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
head>
<body>
<br><br><br>
    <div class="container" align="center">
        <div class="row">
            <div class="col-md-12">
                <h1>SSM 框架快速整合实例--学生查询h1>
            div>
        div>
        <br>
        <div class="row">
            <div class="col-md-12">
                <table class="table table-hover" id="emps_table">
                    <thead>
                        <tr>
                            <th>
                                <input type="checkbox" id="check_all"/>
                            th>
                            <th>编号th>
                            <th>姓名th>
                            <th>性别th>
                            <th>电子邮箱th>
                            <th>联系电话th>
                            <th>班级th>
                            <th>操作th>
                        tr>
                    thead>
                    <tbody>
                        <c:forEach items="${list }" var="student">
                            <tr>
                                <td><input type='checkbox' class='check_item'/>td>
                                <td>${student.id }td>
                                <td>${student.name }td>
                                <td>${student.gender }td>
                                <td>${student.email }td>
                                <td>${student.tel }td>
                                <td>${student.cla }td>

                                <td>
                                    <button class="btn btn-primary btn-sm edit_btn">
                                        <span class="glyphicon glyphicon-pencil">编辑span>
                                    button>  
                                    <button class="btn btn-danger btn-sm delete_btn">
                                        <span class="glyphicon glyphicon-trash">删除span>
                                    button>
                                td>
                            tr>
                        c:forEach>
                    tbody>
                table>
            div>
        div>

    div>
body>
html>

十三、快速进行测试

到这里,SSM 框架整合程序就已经书写完毕,部署并启动 Tomcat 服务器,然后到浏览器地址栏测试,结果如下:

SSM 框架快速整合实例--学生查询_第1张图片

项目源码地址:点击这里直接获取源码



扫描二维码关注微信公众号,了解更多


SSM 框架快速整合实例--学生查询_第2张图片

你可能感兴趣的:(Maven,Spring,SpringMVC,MyBatis)