一、要实现的页面
二、项目搭建
2.1 新建项目
-
新建Maven项目 -
点击File–点击Settings–点击Build,Execution,Deplovment–找到Maven修改Maven的安装路径:(Maven home directory)和settings.xml文件的路径(User settings file)在maven的conf目录下
2.2 导入依赖
- pom.xml导入依赖,build对xml文件页加载到target测试文件中
- spring-webmvc
- spring-jdbc
- spring-test
- spring-aspects
- javax.servlet-api
- jstl
- jsp-api
- mybatis
- mybatis-spring
- junit
- log4j
- common-logging
- mysql-connector-java
- jackson-databind
- druid连接池
- pagehelper分页插件
<?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>org.example</groupId>
<artifactId>springMVC08</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.3.16</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.16</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.16</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.16</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.9</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.54</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.10</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>*.xml</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
2.3 新建web.xml
-
main目录下新建webapp目录,webapp目录下新建WEB-INF目录 -
点击File-点击ProjectStructure 的 -
在弹出的窗口找到Modules–>点击Web–>点击+号–>添加web.xml–>路径改成刚刚新建的src/main/webapp/WEB-INF目录下
2.4 web.xml添加配置如下
- 前端控制器
- 处理乱码
- 启动spring工厂
<?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">
<servlet>
<servlet-name>mvc_xmq</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mvc_xmq</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>fileEncoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>fileEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:</param-value>
</context-param>
</web-app>
2.5 新建包
com.lyx.dao com.lyx.entity com.lyx. web com.lyx.service
2.5.1 entity
public class User {
private int id;
private String username;
private String password;
private int gender;
private Date registTime;
...
- Page类
public class Page {
private Integer pageNum;
private Integer pageSize = 5;
public Page(Integer pageNum, Integer pageSize) {
this.pageNum = pageNum;
this.pageSize = pageSize;
}
...
2.5.2 dao
package com.lyx.dao;
import com.lyx.entity.User;
import java.util.List;
public interface UserDao {
public List<User> queryUsers();
}
- namespace不能忘记
- resultMap的type属性要在spring的配置文件(applicationContext.xml)中定义缺省包路径
- colume是数据库的列名
- property是User类的属性名
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lyx.dao.UserDao">
<resultMap id="rest" type="User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<result column="gender" property="gender"/>
<result column="regist_time" property="registTime"/>
</resultMap>
<select id="queryUsers" resultMap="rest">
select * from t_user
</select>
</mapper>
2.5.3 service
- 这个PageInfo<>是分页插件中自带的page集合类,类似于List<>
- 对于查询所有用户,方法是不用给参数的
- 分页查询,也就是要做sql语句后面加上LIMIT 1,4;(从第1行开始查,查4行)
- 我们把这两个参数封装到上面定义的Page类里面
package com.lyx.service;
import com.github.pagehelper.PageInfo;
import com.lyx.entity.Page;
import com.lyx.entity.User;
import java.util.List;
public interface UserService {
public PageInfo<User> queryUsers(Page page);
}
- 在这里我们使用注解开发
- @Service 添加在实现类UserServiceImpl类上,相当于在配置文件中定义:
<bean id="userServiceImpl" class="com.lyx.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
-
@Autowired @Qualifier(“userDao”) private UserDao userDao; 相当于在实现类UserServiceImpl类里面定义set方法且在配置文件中添加上面bean标签里的property标签 -
注意这里如果你没有在web.xml文件中配置启动spring工厂会报错 -
@Transactional(propagation = Propagation.SUPPORTS) 这个是事务管理,相当于spring配置文件中的:<aop-config>标签 -
PageHelper.startPage(); 对其之后的第一个查询追加分页查询的方法
@Service
public class UserServiceImpl implements UserService {
@Autowired
@Qualifier("userDao")
private UserDao userDao;
@Override
@Transactional(propagation = Propagation.SUPPORTS)
public PageInfo<User> queryUsers(Page page) {
PageHelper.startPage(page.getPageNum(),page.getPageSize());
List<User> users = userDao.queryUsers();
return new PageInfo<User>(users);
}
}
2.5.4 web
也就是controller包
- Mode把数据放到request作用域里面
- @Autowired
@Qualifier(“userServiceImpl”) private UserService userService;
@Controller
public class UserController {
@Autowired
@Qualifier("userServiceImpl")
private UserService userService;
@GetMapping("/test")
public String queryUsers(Model model, Page page){
if(page.getPageNum()==null){
page.setPageNum(1);
}
PageInfo<User> users = userService.queryUsers(page);
model.addAttribute("users",users);
return "user";
}
}
2.6 新建mvc.xml
<?xml version="1.0" encoding="UTF8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
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:component-scan base-package="com.lyx" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<mvc:default-servlet-handler></mvc:default-servlet-handler>
</beans>
2.7 新建applicationContext.xml
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3308/mybatis_xmq?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456
jdbc.minIdle=2
jdbc.maxActive=20
jdbc.initialSize=2
<?xml version="1.0" encoding="UTF8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
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:database.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="minIdle" value="${jdbc.minIdle}"/>
<property name="initialSize" value="${jdbc.initialSize}"/>
<property name="maxActive" value="${jdbc.maxActive}"/>
<property name="minEvictableIdleTimeMillis" value="30000"/>
<property name="timeBetweenEvictionRunsMillis" value="50000"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations">
<list>
<value>classpath:com/lyx/dao/*.xml</value>
</list>
</property>
<property name="typeAliasesPackage" value="com.lyx.entity"/>
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<props>
<prop key="reasonable">true</prop>
</props>
</property>
</bean>
</array>
</property>
</bean>
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.lyx.dao">
</property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<context:component-scan base-package="com.lyx" use-default-filters="true">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<bean id="tx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:annotation-driven transaction-manager="tx"/>
</beans>
2.8 补齐web.xml文件的配置信息
- 把刚刚写的applicationContext.xml文件和mvc.xml文件配置到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">
<servlet>
<servlet-name>mvc_xmq</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mvc_xmq</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>fileEncoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>fileEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
</web-app>
2.8 web层
controller
package com.lyx.web;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lyx.entity.Page;
import com.lyx.entity.User;
import com.lyx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.List;
@Controller
public class UserController {
@Autowired
@Qualifier("userServiceImpl")
private UserService userService;
@GetMapping("/test")
public String queryUsers(Model model, Page page){
if(page.getPageNum()==null){
page.setPageNum(1);
}
PageInfo<User> users = userService.queryUsers(page);
model.addAttribute("users",users);
return "user";
}
}
2.9 user.jap
- 上面controll的handler返回值为user,跳转到user.jsp页面
- webapp下新建包static/js,添加jquery-3.5.1.js
- bootstrap上面直接复制了部分代码:Bootstrap中文文档
- 分页实现,也从bootstrap上面找一个复制下来改
- table表格的也是复制
- c:foreach的item是${requestScope.users.list},这个list是PageInfo的属性:当前页的数据
- 分页实现的代码:
- hasPreviousPage等属性都是PageInfo(分页插件pageHelper自带的类)中的属性
- contrller中的方法有Page形参,所有传递的参数是Page的属性就可以了这里a标签的href=/test?pageNum=xxx,实现第几页
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmg" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
</head>
<body>
<script src="https://fastly.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"
integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"
crossorigin="anonymous"></script>
<table border="1" class="table table-striped">
<thead>
<tr>
<th>id</th>
<th>username</th>
<th>password</th>
<th>gender</th>
<th>registTime</th>
</tr>
</thead>
<tbody>
<c:forEach items="${requestScope.users.list}" varStatus="i" var="u">
<tr>
<th>${u.id}</th>
<th>${u.username}</th>
<th>${u.password}</th>
<th>${u.gender}</th>
<th>
<fmg:formatDate value="${u.registTime}" pattern="yyyy-MM-dd"></fmg:formatDate>
</th>
</tr>
</c:forEach>
</tbody>
</table>
<nav aria-label="Page navigation">
<ul class="pagination">
<c:if test="${requestScope.users.hasPreviousPage}">
<li>
<a href="${pageContext.request.contextPath}/test?pageNum=${requestScope.users.prePage}"
aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<c:if test="${!requestScope.users.hasPreviousPage}">
<li>
<a href="#" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<c:forEach begin="1" end="${requestScope.users.pages}" var="iii">
<li><a href="${pageContext.request.contextPath}/test?pageNum=${iii}">${iii}</a></li>
</c:forEach>
<c:if test="${requestScope.users.hasNextPage}">
<li>
<a href="${pageContext.request.contextPath}/test?pageNum=${requestScope.users.nextPage}"
aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if>
<c:if test="${!requestScope.users.hasNextPage}">
<li>
<a href="#" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if>
</ul>
</nav>
</body>
</html>
2.10 Tomcat运行
访问路径为http://localhost:8080/test
|