目錄
- 1、整合的準備工作
- 1.匯入依賴
- 2.建立資料表
- 3.配置web.xml
- 4.配置springmvc配置
- 5.搭建MyBatis
- 6.建立屬性檔案
- 7.建立核心配置檔案
- 8.建立日誌
- 9.建立spring配置檔案
- 2、開始測試,要把相應的包建立完成
- 1.建立pojo
- 3.建立Mapper介面和對映檔案
- 3.建立service和實現類
- 4.Controller
1、整合的準備工作
1.匯入依賴
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.qcby.ssm</groupId>
<artifactId>ssmtest</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!--版本號-->
<spring.version>5.3.1</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<!--springmvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Mybatis核心 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!--mybatis和spring的整合包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- 連線池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<!-- junit測試 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- MySQL驅動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- log4j日誌 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>
<!-- 日誌 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- ServletAPI -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- Spring5和Thymeleaf整合包 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
</dependencies>
</project>
2.建立資料表
3.配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置Spring的編碼過濾器-->
<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>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置處理請求方式的過濾器-->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置SpringMVC的前端控制器DispatcherServlet-->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--設定SpringMVC配置檔案自定義的位置和名稱-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!--將DispatcherServlet的初始化時間提前到伺服器啟動時-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--配置Spring的監聽器,在伺服器啟動時載入Spring的配置檔案-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--設定Spring配置檔案自定義的位置和名稱-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
</web-app>
4.配置springmvc配置
<?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
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--掃描控制層元件-->
<context:component-scan base-package="com.qcby.ssm.controller"></context:component-scan>
<!-- 配置Thymeleaf檢視解析器 -->
<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="order" value="1"/>
<property name="characterEncoding" value="UTF-8"/>
<property name="templateEngine">
<bean class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver">
<bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
<!-- 檢視字首 -->
<property name="prefix" value="/WEB-INF/pages/"/>
<!-- 檢視字尾 -->
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8"/>
</bean>
</property>
</bean>
</property>
</bean>
<!--配置預設的servlet處理靜態資源-->
<mvc:default-servlet-handler/>
<!--開啟mvc的註解驅動-->
<mvc:annotation-driven/>
<!--配置檢視控制器-->
<mvc:view-controller path="/" view-name="index"></mvc:view-controller>
<!--配置檔案上傳解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
</beans>
5.搭建MyBatis
6.建立屬性檔案
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis_demo
jdbc.username=root
jdbc.password=root
7.建立核心配置檔案
<?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>
<!--
MyBatis核心配置檔案中,標籤的順序:
properties?,settings?,typeAliases?,typeHandlers?,
objectFactory?,objectWrapperFactory?,reflectorFactory?,
plugins?,environments?,databaseIdProvider?,mappers?
-->
<settings>
<!--將資料庫欄位名的下劃線對映為駝峰-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!--開啟延遲載入-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--按需載入-->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<plugins>
<!--配置分頁外掛-->
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
</configuration>
8.建立日誌
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="info" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>
9.建立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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--掃描元件(除控制層)-->
<context:component-scan base-package="com.qcby.ssm">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--引入jdbc.properties-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!--配置資料來源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--配置事務管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--
開啟事務的註解驅動
將使用註解@Transactional標識的方法或類中所有的方法進行事務管理
-->
<tx:annotation-driven transaction-manager="transactionManager" />
<!--配置SqlSessionFactoryBean,可以直接在Spring的IOC中獲取SqlSessionFactory-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<!--設定MyBatis的核心配置檔案的路徑-->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<!--設定資料來源-->
<property name="dataSource" ref="dataSource"></property>
<!--設定型別別名所對應的包-->
<property name="typeAliasesPackage" value="com.qcby.ssm.pojo"></property>
<!--設定對映檔案的路徑,只有對映檔案的包和mapper介面的包不一致時需要設定-->
<!--<property name="mapperLocations" value="classpath:mappers/*.xml"></property>-->
</bean>
<!--
配置mapper介面的掃描,可以將指定包下所有的mapper介面
透過SqlSession建立代理實現類物件,並將這些物件交給IOC容器管理
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.qcby.ssm.mapper"></property>
</bean>
</beans>
2、開始測試,要把相應的包建立完成
1.建立pojo
package com.qcby.ssm.pojo;
/**
* @Author che
* @Date 2024/6/19 21:25
* Description:TODO
* Version 1.0
*/
public class Employee {
private Integer empId;
private String empName;
private Integer age;
private String sex;
private String email;
public Employee() {
}
public Employee(Integer empId, String empName, Integer age, String sex, String email) {
this.empId = empId;
this.empName = empName;
this.age = age;
this.sex = sex;
this.email = email;
}
public Integer getEmpId() {
return empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Employee{" +
"empId=" + empId +
", empName='" + empName + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
", email='" + email + '\'' +
'}';
}
}
3.建立Mapper介面和對映檔案
package com.qcby.ssm.mapper;
import com.qcby.ssm.pojo.Employee;
import java.util.List;
/**
* @Author che
* @Date 2024/6/19 21:25
* Description:TODO
* Version 1.0
*/
public interface EmployeeMapper {
/**
* 查詢所有員工資訊
* @return
*/
List<Employee> getAllEmployee();
}
<?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.qcby.ssm.mapper.EmployeeMapper">
<select id="getAllEmployee" resultType="employee">
select * from emp
</select>
</mapper>
3.建立service和實現類
package com.qcby.ssm.service;
import com.github.pagehelper.PageInfo;
import com.qcby.ssm.pojo.Employee;
import java.util.List;
/**
* @Author che
* @Date 2024/6/19 21:29
* Description:TODO
* Version 1.0
*/
public interface EmployeeService {
/**
* 查詢所有員工
* @return
*/
List<Employee> getAllEmployee();
/**
* 獲取員工的分頁資訊
* @param pageNum
* @return
*/
PageInfo<Employee> getEmployeeByPage(Integer pageNum);
}
package com.qcby.ssm.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qcby.ssm.mapper.EmployeeMapper;
import com.qcby.ssm.pojo.Employee;
import com.qcby.ssm.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @Author che
* @Date 2024/6/19 21:31
* Description:TODO
* Version 1.0
*/
@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeMapper employeeMapper;
@Override
public List<Employee> getAllEmployee() {
//處理業務邏輯
return employeeMapper.getAllEmployee();
}
@Override
public PageInfo<Employee> getEmployeeByPage(Integer pageNum) {
//開啟分頁功能
PageHelper.startPage(pageNum,4);
//查詢所有員工資訊
List<Employee> employees = employeeMapper.getAllEmployee();
//獲取分頁相關資料
PageInfo<Employee> page = new PageInfo<>(employees,5);
return page;
}
}
4.Controller
package com.qcby.ssm.controller;
import com.github.pagehelper.PageInfo;
import com.qcby.ssm.pojo.Employee;
import com.qcby.ssm.service.EmployeeService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import javax.annotation.Resource;
import java.util.List;
/**
* @Author che
* @Date 2024/6/19 21:35
* Description:TODO
* Version 1.0
*/
@Controller
public class EmployeeController {
@Resource
private EmployeeService employeeService;
@GetMapping("/employee/page/{pageNum}")
public String getEmployeePage(@PathVariable("pageNum") Integer pageNum, Model model){
//獲取員工的分頁資訊
PageInfo<Employee> page = employeeService.getEmployeeByPage(pageNum);
//資訊在請求域中共享
model.addAttribute("page",page);
return "employee_list";
}
@GetMapping("/employee")
public String getEmployee(Model model){
//查詢
List<Employee> employees = employeeService.getAllEmployee();
//資訊在請求域中共享
model.addAttribute("employees",employees);
return "employee_list";
}
}
頁面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首頁</title>
</head>
<body>
<h1>index.html</h1>
<a th:href="@{/employee/page/1}">查詢員工的分頁資訊</a>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>員工列表</title>
<link rel="stylesheet" th:href="@{/static/css/index_work.css}">
</head>
<body>
<table>
<tr>
<th colspan="6">員工列表</th>
</tr>
<tr>
<th>流水號</th>
<th>員工姓名</th>
<th>年齡</th>
<th>性別</th>
<th>郵箱</th>
<th>操作</th>
</tr>
<tr th:each="employee,status : ${page.list}">
<td th:text="${status.count}"></td>
<td th:text="${employee.empName}"></td>
<td th:text="${employee.age}"></td>
<td th:text="${employee.sex}"></td>
<td th:text="${employee.email}"></td>
<td>
<a href="">刪除</a>
<a href="">修改</a>
</td>
</tr>
</table>
<div style="text-align: center;">
<a th:if="${page.hasPreviousPage}" th:href="@{/employee/page/1}">首頁</a>
<a th:if="${page.hasPreviousPage}" th:href="@{'/employee/page/'+${page.prePage}}">上一頁</a>
<span th:each="num : ${page.navigatepageNums}">
<a th:if="${page.pageNum == num}" style="color: red;" th:href="@{'/employee/page/'+${num}}" th:text="'['+${num}+']'"></a>
<a th:if="${page.pageNum != num}" th:href="@{'/employee/page/'+${num}}" th:text="${num}"></a>
</span>
<a th:if="${page.hasNextPage}" th:href="@{'/employee/page/'+${page.nextPage}}">下一頁</a>
<a th:if="${page.hasNextPage}" th:href="@{'/employee/page/'+${page.pages}}">末頁</a>
</div>
</body>
</html>