天天看點

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.0</modelVersion>
  <groupId>com.ssm.example</groupId>
  <artifactId>SsmDemo</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SSMDemo Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>

		<!-- 配置 SpringMVC 依賴包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>

        <!-- Spring JDBC 依賴包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>

        <!-- Spring AOP 依賴包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>

        <!--MyBatis 依賴包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.2</version>
        </dependency>
        
        <!-- Spring 整合 MyBatis 依賴包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>

		<!-- MySQL 驅動依賴包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.41</version>
        </dependency>
		
        <!-- C3P0 資料源依賴包 -->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1</version>
        </dependency>
        
        <!-- jstl 依賴包 -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

		<!-- ServletAPI 依賴包-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>

        <!-- junit 測試依賴包 -->
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
      </dependency>

  </dependencies>

    <!-- 如果不添加此節點,mybatis 的 mapper.xml 檔案都會被漏掉 -->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

</project>

           

四、快速配置編碼過濾和資源加載

打開

web.xml

檔案,快速配置開啟 Spring 、SpringMVC 編碼過濾以及靜态資源加載,具體配置代碼如下:

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  
  <!-- 啟動Spring的容器  -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!-- SpringMVC的前端控制器,攔截所有請求  -->
  <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <!-- 字元編碼過濾器,一定要放在所有過濾器之前 -->
  <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>
	  <init-param>
		  <param-name>forceRequestEncoding</param-name>
		  <param-value>true</param-value>
	  </init-param>
	  <init-param>
		  <param-name>forceResponseEncoding</param-name>
		  <param-value>true</param-value>
	  </init-param>
  </filter>
  <filter-mapping>
	  <filter-name>CharacterEncodingFilter</filter-name>
	  <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!-- 加載靜态資源 -->
  <servlet-mapping>
  	<servlet-name>default</servlet-name>
  	<url-pattern>*.js</url-pattern>
  </servlet-mapping>
  
  <servlet-mapping>
  	<servlet-name>default</servlet-name>
  	<url-pattern>*.css</url-pattern>
  </servlet-mapping>
  
</web-app>

           

五、快速配置 Spring 配置檔案

resources

檔案夾下建立

applicationContext.xml

檔案,配置 MyBatis 和資料庫相關資訊,具體代碼配置如下:

<?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"
	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"/>
	
	<!-- 配置 C3P0 資料源 -->
	<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>
	
	<!-- 配置 MyBatis SqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 指定 MyBatis 資料源 -->
		<property name="dataSource" ref="dataSource"/>
		<!-- 指定 MyBatis mapper 映射檔案位置 -->
		<property name="mapperLocations" value="classpath:com/ssm/example/dao/*.xml"/>
		<!-- 指定 MyBatis 全局配置檔案的位置 -->
		<property name="configLocation" value="classpath:mybatis-config.xml"></property>
	</bean>
	
	<!-- 掃描 MyBatis 的 mapper 接口 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!--掃描所有 dao 接口,加入到 IOC 容器中 -->
		<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

檔案,配置相關的資料庫操作輔助資訊,具體代碼配置如下:

<?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>
		<!-- 列印SQL-->
		<setting name="logImpl" value="STDOUT_LOGGING" />
	</settings>
	
	<typeAliases>
		<!-- 指定一個包名,MyBatis會在包名下搜尋需要的JavaBean-->
		<package name="com.ssm.example.entity"/>
	</typeAliases>
	
</configuration>
           

八、快速配置 SpringMVC 注解掃描和視圖解析器

resources

springmvc.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: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">
	
	<!-- 啟用 SpringMVC 注解驅動 -->
	<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<Student> 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<Student> 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<Student> 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<Student> findAll();
}

           

快速建立 dao 接口代理檔案

StudentDAO.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.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"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<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>&nbsp;&nbsp;
									<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 伺服器,然後到浏覽器位址欄測試,結果如下:

項目源碼位址:點選這裡直接擷取源碼

掃描二維碼關注微信公衆号,了解更多

--------------------------------------![](https://user-gold-cdn.xitu.io/2018/5/12/16355071b0f00106?imageView2/0/w/1280/h/960/format/webp/ignore-error/1)