SSM框架综合应用
环境搭建
用到的软件 :Eclipse javaEE版本,jdk1.8,Tomcat8.5, mysql8.0.19
SSM框架的环境搭建过程有如下几个步骤:
准备jar包(共26个)
jar包的下载方法:spring、mybatis这些可以在官网上下载,其他一些零碎的可以在maven 仓库官网上下载。这里以Commons-logging-1.2.jar为例说明:
a. 百度maven repository,进入官网
b. 在搜索框输入jar包名称或关键字
c. 点击检索结果超链接
d. 点击对应版本号
e. 点击下载链接
jar包分为几个类型:
- spring相关的:
a. spring基础jar包
b. spring aop jar包
c. spring jdbc jar包
d. spring 事务 jar包
e. spring MVC jar包
- 数据库相关jar包:
mysql驱动包:
mybatis jar包:
c3p0数据源jar包:
- 其他辅助jar包
jsp标签库jar包:
分页工具 jar 包:
json jar 包
准备前端页面的css与js文件
前端采用bootstrap框架,版本为3.3.7。
a. 百度bootstrap,进入官网
b. 点击bootstrap3中文文档按钮
c. 点击下载
bootstrap框架还依赖于jquery框架,还需下载jQuery。此文件已发送到群里。
创建工程
- 工程类型为动态网页工程。此工程不再是普通的Java Project。而是一个动态网页工程(Dynamic Web Project)。
空白地方右击->New->Project…->
选择web下的Dynamic Web Project->Next
点击New Runtime…
选中Apache Tomcat v8.5,勾选上Create a new local server,点击Next
选择tomcat的安装路径,指定jre,选择jre1.8,点击Finish
填写工程名称work。
点击两次Next,进入到下面的页面,勾选上Generate web.xml那一项,点击Finish., - 修改tomcat服务器配置
双击下图的红框部分
进入下图界面
修改Server Locations。修改完成后,要按ctrl+s,保存一下。
下图中红框部分是tomcat的端口号,如果8080端口被占用,可以在这里修改。一般情况下不用修改。
启动tomcat,在浏览器中访问 localhost:8080,观察是否正常 - 添加测试jsp页面
添加方法如下图
测试页代码如下,切记要修改编码方法,修改为UTF-8
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>欢迎使用学生温度提交系统</h1>
</body>
</html>
- 修改web.xml
把多余的welcome-file删除,只保留一个index.jsp
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>work</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
- 测试:关闭tomcat,添加刚创建的工程,重新启动tomcat
创建数据库和数据表
- 在cmd中创建数据库
先开启mysql服务,后在cmd中切换目录到mysql安装路径下的bin文件,敲入登录mysql的命令,编写建表语句数据库名称任意
建库语句如下:
create database test01;
创建后显示:
show databases;
- 使用eclipse连接数据库
具体操作如链接所示:添加链接描述
在操作过程中注意参数要根据实际情况调整,特别是数据库名。 - 创建数据表
具体操作如链接所示:添加链接描述
数据表创建l语句是
create table tbl_student(
id int not null primary key AUTO_INCREMENT,
department varchar(30) not null,
class varchar(30) not null,
name varchar(30) not null,
tempretrue1 int not null,
tempretrue2 int not null,
tempretrue3 int not null
)AUTO_INCREMENT 20180101;
导入文件
- 将所有jar包导入到红框中的lib文件夹中
- 导入项目所需的css,js文件
在WebContent下创建static文件夹,用来存放前台所需的css和js文件。
其中,bootstrap-3.3.7-dist为下载bootstrap的zip文件解压缩后的文件目录,直接将它拷贝到static文件夹下。 - 修改index.jsp页面
在jsp页面中引入css和js文件,引入时要注意路径的写法,采用了相对路径。写路径的时候最好使用复制法,方法如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>测试页</title>
<script type="text/javascript" src="static/js/jquery-1.12.4.min.js"></script>
<link href="static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
<div class="page-header">
<h1>欢迎使用学生信息系统 <small>测试版</small></h1>
</div>
</body>
</html>
- 运行测试,启动tomcat,在浏览器中输入localhost:8080/work
编写SSM框架整合的配置文件
编写的配置文件较多,针对每一项配置要搞清楚它的作用是什么
修改web.xml文件
文件里要加入Tomcat启动时要加载类,这些类
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>SSM</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!--1、加载Spring的配置文件,启动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>
<!--2、加载SpringMVC的配置文件,启动SpringMVC的前端控制器 -->
<servlet>
<servlet-name>SpringMVC</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>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--3.1 配置字符过滤器,用于解决页面传到后台的参数是乱码的问题 -->
<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>forceResopnseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--3.2 配置隐藏HTTP方法过滤器,转换post方式为put和delete,用于处理restful风格的请求 -->
<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>
</web-app>
编写spring配置文件
在工程下创建一个类型为source floder的conf文件,将配置文件统一放置在conf目录下
<?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/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
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
">
<!--4、配置Spring -->
<!--4.1 配置注解扫描 -->
<context:component-scan base-package="com.edu.tjdz.geng">
<!--4.1.1 配置不扫描被Controller注解的类(被Controller注解的类由SpringMVC来扫描) -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--4.1.2 配置db.properties路径 -->
<context:property-placeholder location="classpath:db.properties"/>
<!--4.2 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--4.2.1 数据源四大属性放置在了db.properties文件中,使用${}来获取 -->
<!--驱动名称-->
<property name="driverClass" value="${jdbc.driverClass}" />
<!--数据库url-->
<property name="jdbcUrl" value="${jdbc.jdbcUrl}" />
<!--数据库用户名-->
<property name="user" value="${jdbc.user}" />
<!--数据库密码-->
<property name="password" value="${jdbc.password}" />
</bean>
<!--4.3 配置mybatis-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--指定mybatis配置文件路径-->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<!--指定数据源(数据源是对数据库的一个封装,操作起来性能更好)-->
<property name="dataSource" ref="dataSource"></property>
<!--指定mappers文件所在路径-->
<property name="mapperLocations" value="classpath:mappers/*.xml"></property>
</bean>
<!-- 配置mappers.xml对应的接口所在位置-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.edu.tjdz.geng.dao"></property>
</bean>
<!--5 配置事务管理 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--5.1 配置切入点和建议 -->
<aop:config>
<!--切入点通常为service层下的各个方法 -->
<aop:pointcut expression="execution(* com.edu.tjdz.geng.service..*(..))" id="txPoint"/>
<!--针对上面的切入点(pointcut-ref),指定一个处理方式(advice-ref)。 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
</aop:config>
<!--5.2 配置个性化的事务处理方式 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--service层中以get开头的函数使用何种事务管理方式 -->
<tx:method name="get*" read-only="true" />
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
</beans>
编写数据库相关配置文件
- db.propertis
注意jdbcUrl中数据库的名称(3306/和?之间的字符串)要写对了
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/test01?serverTimezone=Asia/Shanghai
jdbc.user=root
jdbc.password=123456
- 数据库日志配置文件
复制时,注意第二行在log4j.logger.和=DEBUG之间要填上你自己的包名。
log4j.rootLogger=ERROR,stdout
log4j.logger.com.edu.tjdz.geng=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
编写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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<!--6. 配置SpringMVC -->
<!--6.1. 指定要被扫描的包 -->
<context:component-scan base-package="com.edu.tjdz.geng" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--6.2 配置视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--6.3 配置SpringMVC注解 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!--6.4 允许返回js,css等 -->
<mvc:default-servlet-handler/>
</beans>
编写mybatis配置文件
<?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>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
创建mappers包
在conf下创建mappers包
启动Tomcat并测试
实现增删改查四大功能
增删改查是一个B/S架构的四大基本功能。下面分别对这四大功能的实现进行描述
项目结构如下:
实现查询功能
以普通形式实现
- 编写前台页面
修改index.jsp。在首页上加入了跳转到查询页面的请求,名为studentsList。点击这个链接,页面跳转到了展现所有学生信息的页面。页面中各个元素的样式都是仿照了bootstrap文档中某些元素的样式。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>测试页</title>
<script type="text/javascript" src="static/js/jquery-1.12.4.min.js"></script>
<link href="static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
<div class="page-header">
<h1>欢迎使用学生信息系统 <small>测试版</small></h1>
</div>
<div class="list-group">
<a href="studentsList" class="list-group-item list-group-item-success">查询学生</a>
<a href="#" class="list-group-item list-group-item-info">待补充</a>
<a href="#" class="list-group-item list-group-item-warning">待补充</a>
<a href="#" class="list-group-item list-group-item-danger">待补充</a>
</div>
</body>
</html>
界面如图所示:
2. 编写处理studentsList请求的方法
创建com.edu.tjdz.geng.controller包,在该包下创建StudentController类
package com.edu.tjdz.geng.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class StudentController {
@RequestMapping(value = "/studentsList", method = RequestMethod.GET)
public String showStudentListPage() {
return "studentsList";
}
}
- 编写studentsList.jsp
jsp页面使用了bootstrap的栅格布局方式,简单来讲,栅格布局就是将一个页面划分为若干行和列,可以在行和列中放置具体的html元素,可以类比于excel。具体的布局方式参考官方文档。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>学生管理系统</title>
<script type="text/javascript" src="static/js/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<link href="static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<!--1、放置标题 -->
<div class="row">
<div class="page-header">
<h1>学生列表</h1>
</div>
</div>
<!--2、放置全局性按钮或输入框 -->
<div class="row">
<div class="col-md-4 col-md-offset-10">
<button class="btn btn-info" id="stu_add_modal_btn">新增</button>
<button class="btn btn-danger">删除</button>
</div>
</div>
<div class="row" style="height: 10px"></div>
<!--3、放置学生列表table -->
<div class="row">
<div class="col-md-12">
<table class="table table-striped" id="stus_table">
<thead>
<tr>
<th>序号</th>
<th>学号</th>
<th>系部</th>
<th>班级</th>
<th>姓名</th>
<th>早温</th>
<th>午温</th>
<th>晚温</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<!--4、放置分页条 -->
<div class="row">
<div class="col-md-6" id="page_info_div"></div>
<div class="col-md-6" id="page_nav_div"></div>
</div>
</div>
</body>
</html>
当点击查询查询学生链接时,返回的结果如图所示:
当前页面还没有具体数据,因为我们的后台代码目前没有读取数据库,仅仅是做了一个简单的页面返回功能。
我们先手动构造一些数据
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>学生管理系统</title>
<script type="text/javascript" src="static/js/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<link href="static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<!--1、放置标题 -->
<div class="row">
<div class="page-header">
<h1>学生列表</h1>
</div>
</div>
<!--2、放置全局性按钮或输入框 -->
<div class="row">
<div class="col-md-4 col-md-offset-10">
<button class="btn btn-info" id="stu_add_modal_btn">新增</button>
<button class="btn btn-danger">删除</button>
</div>
</div>
<div class="row" style="height: 10px"></div>
<!--3、放置学生列表table -->
<div class="row">
<div class="col-md-12">
<table class="table table-striped" id="stus_table">
<thead>
<tr>
<th>序号</th>
<th>学号</th>
<th>系部</th>
<th>班级</th>
<th>姓名</th>
<th>早温</th>
<th>午温</th>
<th>晚温</th>
<th>操作</th>
</tr>
<tr>
<th>1</th>
<th>20180101</th>
<th>计算机与软件技术系</th>
<th>软件S18-1</th>
<th>AAA</th>
<th>36.1</th>
<th>36.8</th>
<th>36.3</th>
<th>
<button type="button" class="btn btn-primary btn-xs">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>更改
</button>
<button type="button" class="btn btn-danger btn-xs">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>删除
</button>
</th>
</tr>
<tr>
<th>2</th>
<th>20180102</th>
<th>计算机与软件技术系</th>
<th>软件S18-2</th>
<th>BBB</th>
<th>36.2</th>
<th>36.4</th>
<th>36.3</th>
<th>
<button type="button" class="btn btn-primary btn-xs">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>更改
</button>
<button type="button" class="btn btn-danger btn-xs">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>删除
</button>
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<!--4、放置分页条 -->
<div class="row">
<div class="col-md-6" id="page_info_div"></div>
<div class="col-md-6" id="page_nav_div"></div>
</div>
</div>
</body>
</html>
启动tomcat, 在浏览器输入地址,测试结果如下:
4. 编写其他层,从数据库中获取数据
model层:创建com.edu.tjdz.geng.model包,在包下创建Student类
package com.edu.tjdz.geng.model;
public class Student {
private int id;
private String department;
private String className;
private String name;
private int tempreture1;
private int tempreture2;
private int tempreture3;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getTempreture1() {
return tempreture1;
}
public void setTempreture1(int tempreture1) {
this.tempreture1 = tempreture1;
}
public int getTempreture2() {
return tempreture2;
}
public void setTempreture2(int tempreture2) {
this.tempreture2 = tempreture2;
}
public int getTempreture3() {
return tempreture3;
}
public void setTempreture3(int tempreture3) {
this.tempreture3 = tempreture3;
}
@Override
public String toString() {
return "Student [id=" + id + ", department=" + department + ", className=" + className + ", name=" + name
+ ", tempreture1=" + tempreture1 + ", tempreture2=" + tempreture2 + ", tempreture3=" + tempreture3
+ "]";
}
}
dao层:创建com.edu.tjdz.geng.dao包,在dao包下创建StudentDao接口
package com.edu.tjdz.geng.dao;
import java.util.List;
import com.edu.tjdz.geng.model.Student;
public interface StudentDao {
public List<Student> selectAllStus();
}
service层:
创建com.edu.tjdz.geng.service包
package com.edu.tjdz.geng.service;
import java.util.List;
public interface StudentService {
public List<Student> getAllStudents();
}
创建和com.edu.tjdz.geng.service.impl包
package com.edu.tjdz.geng.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.edu.tjdz.geng.dao.StudentDao;
import com.edu.tjdz.geng.model.Student;
import com.edu.tjdz.geng.service.StudentService;
@Service("studentService")
public class StudentServiceImpl implements StudentService {
@Autowired
StudentDao studentDao;
@Override
public List<Student> getAllStudents() {
return studentDao.selectAllStus();
}
}
- 修改controller类
package com.edu.tjdz.geng.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.edu.tjdz.geng.model.Student;
import com.edu.tjdz.geng.service.StudentService;
@Controller
public class StudentController {
@Autowired
StudentService studentService;
@RequestMapping(value = "/studentsList", method = RequestMethod.GET)
public ModelAndView showStudentListPage() {
//使用ModelAndView将查询结果返回到前台
ModelAndView modelAndView = new ModelAndView();
List<Student> stus = studentService.getAllStudents();
//使用ModelAndView将查询结果返回到前台
modelAndView.addObject("students",stus);
//设置返回到界面名称
modelAndView.setViewName("studentsList");
return modelAndView;
}
}
- 在mappers包下创建mapper文件,编写StudentMapper.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">
<!-- namespace命名空间 -->
<mapper namespace="com.edu.tjdz.geng.dao.StudentDao">
<select id="selectAllStus" resultType="com.edu.tjdz.geng.model.Student">
select id, department, class className, name,tempretrue1, tempretrue2,tempretrue3
from tbl_student
</select>
</mapper>
- 修改studentsList页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>学生管理系统</title>
<script type="text/javascript" src="static/js/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<link href="static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<!--1、放置标题 -->
<div class="row">
<div class="page-header">
<h1>学生列表</h1>
</div>
</div>
<!--2、放置全局性按钮或输入框 -->
<div class="row">
<div class="col-md-4 col-md-offset-10">
<button class="btn btn-info" id="stu_add_modal_btn">新增</button>
<button class="btn btn-danger">删除</button>
</div>
</div>
<div class="row" style="height: 10px"></div>
<!--3、放置学生列表table -->
<div class="row">
<div class="col-md-12">
<table class="table table-striped" id="stus_table">
<thead>
<tr>
<th>序号</th>
<th>学号</th>
<th>系部</th>
<th>班级</th>
<th>姓名</th>
<th>早温</th>
<th>午温</th>
<th>晚温</th>
<th>操作</th>
</tr>
<c:forEach items="${students}" var="stu" varStatus="status">
<tr>
<th>${status.index}</th>
<th>${stu.id}</th>
<th>${stu.department}</th>
<th>${stu.className}</th>
<th>${stu.tempretrue1}</th>
<th>${stu.tempretrue2}</th>
<th>${stu.tempretrue3}</th>
<th>
<button type="button" class="btn btn-primary btn-xs">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>更改
</button>
<button type="button" class="btn btn-danger btn-xs">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>删除
</button>
</th>
</tr>
</c:forEach>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<!--4、放置分页条 -->
<div class="row">
<div class="col-md-6" id="page_info_div"></div>
<div class="col-md-6" id="page_nav_div"></div>
</div>
</div>
</body>
</html>
- 运行测试
- 上述界面显示时,将所有结果返回到了界面上,这样做很不美观,需要进行分页处理
修改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>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="reasonable" value="true"/>
</plugin>
</plugins>
</configuration>
修改controller类
showStudentListPage函数里有一个参数,该参数用来接收前台页面传过来的当前页码数
package com.edu.tjdz.geng.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.edu.tjdz.geng.model.Student;
import com.edu.tjdz.geng.service.StudentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
@Controller
public class StudentController {
@Autowired
StudentService studentService;
/*
@RequestMapping(value = "/studentsList", method = RequestMethod.GET)
public ModelAndView showStudentListPage() {
ModelAndView modelAndView = new ModelAndView();
List<Student> stus = studentService.getAllStudents();
modelAndView.addObject("students",stus);
modelAndView.setViewName("studentsList");
return modelAndView;
}*/
@RequestMapping(value = "/studentsList", method = RequestMethod.GET)
public ModelAndView showStudentListPage(@RequestParam(value = "pn",defaultValue = "1")int pageNum) {
int pageListNum = 10;
int continuePages = 5;
ModelAndView modelAndView = new ModelAndView();
PageHelper.startPage(pageNum, pageListNum);
List<Student> stus = studentService.getAllStudents();
PageInfo page = new PageInfo(stus, continuePages);
modelAndView.addObject("pageInfo",page);
modelAndView.setViewName("studentsList");
return modelAndView;
}
}
修改studentsList.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>学生管理系统</title>
<script type="text/javascript" src="static/js/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<link href="static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<!--1、放置标题 -->
<div class="row">
<div class="page-header">
<h1>学生列表</h1>
</div>
</div>
<!--2、放置全局性按钮或输入框 -->
<div class="row">
<div class="col-md-4 col-md-offset-10">
<button class="btn btn-info" id="stu_add_modal_btn">新增</button>
<button class="btn btn-danger">删除</button>
</div>
</div>
<div class="row" style="height: 10px"></div>
<!--3、放置学生列表table -->
<div class="row">
<div class="col-md-12">
<table class="table table-striped" id="stus_table">
<thead>
<tr>
<th>序号</th>
<th>学号</th>
<th>系部</th>
<th>班级</th>
<th>姓名</th>
<th>早温</th>
<th>午温</th>
<th>晚温</th>
<th>操作</th>
</tr>
<c:forEach items="${pageInfo.list}" var="stu" varStatus="status">
<tr>
<th>${status.index+1}</th>
<th>${stu.id}</th>
<th>${stu.department}</th>
<th>${stu.className}</th>
<th>${stu.name}</th>
<th>${stu.tempretrue1}</th>
<th>${stu.tempretrue2}</th>
<th>${stu.tempretrue3}</th>
<th>
<button type="button" class="btn btn-primary btn-xs">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>更改
</button>
<button type="button" class="btn btn-danger btn-xs">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>删除
</button>
</th>
</tr>
</c:forEach>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<!--4、放置分页条 -->
<div class="row">
<div class="col-md-6" id="page_info_div">
当前${pageInfo.pageNum}页,总共${pageInfo.pages}页,总共${pageInfo.total}条数
</div>
<div class="col-md-6" id="page_nav_div">
<nav aria-label="Page navigation">
<ul class="pagination">
<li><a href="studentsList?pn=1">首页</a></li>
<c:if test="${pageInfo.hasPreviousPage}">
<li>
<a href="studentsList?pn=${pageInfo.pageNum - 1}" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<c:forEach items="${pageInfo.navigatepageNums}" var="page_Num">
<c:if test="${page_Num == pageInfo.pageNum}">
<li class="active"><a href="studentsList?pn=${page_Num}">${page_Num}</a></li>
</c:if>
<c:if test="${page_Num != pageInfo.pageNum}">
<li><a href="studentsList?pn=${page_Num}">${page_Num}</a></li>
</c:if>
</c:forEach>
<c:if test="${pageInfo.hasNextPage}">
<li>
<a href="studentsList?pn=${pageInfo.pageNum + 1}" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if>
<li><a href="studentsList?pn=${pageInfo.pages}">尾页</a></li>
</ul>
</nav>
</div>
</div>
</div>
</body>
</html>
- 运行并测试
以json形式实现
上面查询出来的数据使用modelAndView对象返回到了前台,现在采用ajax+json的手段返回查询结果。ajax用于发起请求,json是一个数据的格式,可暂时类比于java中的map去理解。
-
ajax简介
ajax技术用于在刷新网页的局部内容。ajax在本项目使用的时候通常以这种形式,
$.ajax({
url:“请求名”,
data:“要发给后台的参数名=”+对应的参数值,
type:“get或者post,二选一,这一项代表请求的方式”,
success:function(result){
//success是浏览器接收到对应请求的回应时,执行的函数。//console.log(result),用于测试,打印接收到后台传递回来的数据 console.log(result); //相关逻辑代码 } });
-
修改前台界面和controller类。
之前的方式是发送/studentsList请求,直接返回包含了查询结果的studentsList.jsp页面。现在采用异步的方式来修改页面代码。异步是指转向studentsList.jsp页面的请求不再包含查询数据的功能,而是采用ajax技术在studentsList.jsp加载时,再次发送只为查询数据的新请求。
修改index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>测试页</title>
<script type="text/javascript" src="static/js/jquery-1.12.4.min.js"></script>
<link href="static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
<div class="page-header">
<h1>欢迎使用学生信息系统 <small>测试版</small></h1>
</div>
<div class="list-group">
<!--请求名称已变,仅仅用来展现StudentsList页面-->
<a href="showStudentsListpage" class="list-group-item l ist-group-item-success">查询学生</a>
<a href="#" class="list-group-item list-group-item-info">待补充</a>
<a href="#" class="list-group-item list-group-item-warning">待补充</a>
<a href="#" class="list-group-item list-group-item-danger">待补充</a>
</div>
</body>
</html>
修改StudentController类
package com.edu.tjdz.geng.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.edu.tjdz.geng.model.Message;
import com.edu.tjdz.geng.model.Student;
import com.edu.tjdz.geng.service.StudentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
@Controller
public class StudentController {
@Autowired
StudentService studentService;
//用来接受前台showStudentsListpage请求
@RequestMapping(value = "/showStudentsListpage", method = RequestMethod.GET)
public String showStudentListPage() {
return "studentsList";
}
}
- 运行测试
现在还未发出获取学生信息的请求,所以页面没有数据 - 在studentsList页面中添加用ajax发起请求的代码
页面中部分元素使用了jquery方式动态添加,形式上为$("<元素名称></元素名称>").append
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>学生管理系统</title>
<script type="text/javascript" src="static/js/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<link href="static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<!--1、放置标题 -->
<div class="row">
<div class="page-header">
<h1>学生列表</h1>
</div>
</div>
<!--2、放置全局性按钮或输入框 -->
<div class="row">
<div class="col-md-4 col-md-offset-10">
<button class="btn btn-info" id="stu_add_modal_btn">新增</button>
<button class="btn btn-danger">删除</button>
</div>
</div>
<div class="row" style="height: 10px"></div>
<!--3、放置学生列表table -->
<div class="row">
<div class="col-md-12">
<table class="table table-striped" id="stus_table">
<thead>
<tr>
<th>序号</th>
<th>学号</th>
<th>系部</th>
<th>班级</th>
<th>姓名</th>
<th>早温</th>
<th>午温</th>
<th>晚温</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<!--4、放置分页条 -->
<div class="row">
<div class="col-md-6" id="page_info_div"></div>
<!--内部的html元素都采用js来动态的生成 -->
<div class="col-md-6" id="page_nav_div"></div>
</div>
<script type="text/javascript">
//1、页面加载完成但还未显示时后,发送ajax请求,查到分页数据
$(function() {
to_page(1);
});
function to_page(pageNum){
$.ajax({
url:"studentsList",//发送的请求名称
data:"pageNum="+pageNum,//发送的参数是页码
type:"get",//以get方式发送
success:function(result){
console.log(result);
//1.解析并显示员工数据
build_stus_table(result);
//2.解析并显示分页信息
build_page_info(result);
//3.解析并显示分页条
build_page_nav(result);
}
});
}
function build_stus_table(result){
$("#stus_table tbody").empty();
//最好使用console.log打印result,输出观察一下result内部结构,或者使用浏览器的调试工具
var stus = result.datas.stuPageInfo.list;
$.each(stus, function(index, item){
//一下这种形式是jquery创建html元素的语法,如果不理解,看一下jquery语法
var seq = $("<td></td>").append(index+1);
var stuId = $("<td></td>").append(item.id);
var stuDeptName = $("<td></td>").append(item.department);
var className = $("<td></td>").append(item.className);
var stuName = $("<td></td>").append(item.name);
var tempreture1 = $("<td></td>").append(item.tempretrue1);
var tempreture2 = $("<td></td>").append(item.tempretrue2);
var tempreture3 = $("<td></td>").append(item.tempretrue3);
var editBtn = $("<Button></Button>").addClass("btn btn-primary btn-xs").append($("<span></span>").addClass("glyphicon glyphicon-pencil")).append("编辑");
var deltBtn = $("<Button></Button>").addClass("btn btn-danger btn-xs").append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("删除");
var btnTd = $("<td></td>").append(editBtn).append(" ").append(deltBtn);
$("<tr></tr>").append(seq).append(stuId).append(stuDeptName).append(className).append(stuName).
append(tempreture1).append(tempreture2).append(tempreture3).
append(btnTd).appendTo("#stus_table tbody");
});
}
function build_page_info(result){
$("#page_info_div").empty();
$("#page_info_div").append("当前第" + result.datas.stuPageInfo.pageNum + "页,总共"
+ result.datas.stuPageInfo.pages + "页,共有"
+ result.datas.stuPageInfo.total + "条数据");
}
function build_page_nav(result){
$("#page_nav_div").empty();
var ul = $("<ul></ul>").addClass("pagination");
var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href","#"));
var prePageLi = $("<li></li>").append($("<a></a>").append("«"));
if(result.datas.stuPageInfo.hasPreviousPage == false){
firstPageLi.addClass("disabled");
prePageLi.addClass("disabled");
}else{
firstPageLi.click(function(){
to_page(1);
});
prePageLi.click(function(){
to_page(result.datas.stuPageInfo.pageNum - 1);
});
}
var nextPageLi = $("<li></li>").append($("<a></a>").append("»"));
var lastPageLi = $("<li></li>").append($("<a></a>").append("尾页").attr("href","#"));
if(result.datas.stuPageInfo.hasNextPage == false){
nextPageLi.addClass("disabled");
lastPageLi.addClass("disabled");
}else{
lastPageLi.click(function(){
to_page(result.datas.stuPageInfo.pages);
});
nextPageLi.click(function(){
to_page(result.datas.stuPageInfo.pageNum + 1);
});
}
ul.append(firstPageLi).append(prePageLi);
$.each(result.datas.stuPageInfo.navigatepageNums, function(index, item){
var pageNumLi = $("<li></li>").append($("<a></a>").append(item));
if(result.datas.stuPageInfo.pageNum == item){
pageNumLi.addClass("active");
}
pageNumLi.click(function(){
to_page(item);
});
ul.append(pageNumLi);
});
ul.append(nextPageLi).append(lastPageLi);
var nav = $("<nav></nav>").append(ul);
nav.appendTo("#page_nav_div")
}
</script>
</div>
</body>
</html>
- 修改controller类
package com.edu.tjdz.geng.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.edu.tjdz.geng.model.Message;
import com.edu.tjdz.geng.model.Student;
import com.edu.tjdz.geng.service.StudentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
@Controller
public class StudentController {
@Autowired
StudentService studentService;
@RequestMapping(value = "/showStudentsListpage", method = RequestMethod.GET)
public String showStudentListPage() {
return "studentsList";
}
//@ResponseBody会将返回结果自动转变成json格式
//本函数的返回结果是Message对象,这个对象是自己创建的一个用于封装返回结果的类
@RequestMapping(value = "/studentsList", method = RequestMethod.GET)
@ResponseBody
public Message getStudentsWithJson(@RequestParam(value = "pageNum", defaultValue = "1")int pageNum) {
int pageSize = 10;
int showPages = 5;
System.out.println("pageNum:" + pageNum);
PageHelper.startPage(pageNum, pageSize);
List<Student> stus = studentService.getAllStudents();
PageInfo<Student> stuPageInfo = new PageInfo<Student>(stus, showPages);
return Message.success().add("stuPageInfo", stuPageInfo);
}
}
在model包中添加Message类
package com.edu.tjdz.geng.model;
import java.util.HashMap;
import java.util.Map;
public class Message {
//100-成功,200-失败
private int code;
//返回一些相关信息
private String msg;
//核心属性,数据库查询出来的结果就放在datas中
private Map<String, Object> datas = new HashMap<String, Object>();
public static Message success() {
Message result = new Message();
result.setCode(100);
result.setMsg("处理成功");
return result;
}
public static Message fail() {
Message result = new Message();
result.setCode(200);
result.setMsg("处理失败");
return result;
}
//核心方法,调用它就可以网datas中放置任意数据。
public Message add(String key, Object value) {
this.getDatas().put(key, value);
return this;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Map<String, Object> getDatas() {
return datas;
}
public void setDatas(Map<String, Object> datas) {
this.datas = datas;
}
}
7.运行测试。
实现添加功能
- 修改前台页面
添加功能页面采用bootstrap里的模态框,关于模态框部分请参考:模态框
修改/SSM01/WebContent/WEB-INF/views/studentsList.jsp这个文件
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>学生管理系统</title>
<script type="text/javascript" src="static/js/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<link href="static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<!--1、放置标题 -->
<div class="row">
<div class="page-header">
<h1>学生列表</h1>
</div>
</div>
<!--2、放置全局性按钮或输入框 -->
<div class="row">
<div class="col-md-4 col-md-offset-10">
<button class="btn btn-info" id="stu_add_modal_btn">新增</button>
<button class="btn btn-danger">删除</button>
</div>
</div>
<div class="row" style="height: 10px"></div>
<!--3、放置学生列表table -->
<div class="row">
<div class="col-md-12">
<table class="table table-striped" id="stus_table">
<thead>
<tr>
<th>序号</th>
<th>学号</th>
<th>系部</th>
<th>班级</th>
<th>姓名</th>
<th>早温</th>
<th>午温</th>
<th>晚温</th>
<th>操作</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<!--4、放置分页条 -->
<div class="row">
<div class="col-md-6" id="page_info_div"></div>
<!--内部的html元素都采用js来动态的生成 -->
<div class="col-md-6" id="page_nav_div"></div>
</div>
<script type="text/javascript">
//1、页面加载完成但还未显示时后,发送ajax请求,查到分页数据
$(function() {
to_page(1);
});
function to_page(pageNum){
$.ajax({
url:"studentsList",//发送的请求名称
data:"pageNum="+pageNum,//发送的参数是页码
type:"get",//以get方式发送
success:function(result){
console.log(result);
//1.解析并显示员工数据
build_stus_table(result);
//2.解析并显示分页信息
build_page_info(result);
//3.解析并显示分页条
build_page_nav(result);
}
});
}
function build_stus_table(result){
$("#stus_table tbody").empty();
//最好使用console.log打印result,输出观察一下result内部结构,或者使用浏览器的调试工具
var stus = result.datas.stuPageInfo.list;
$.each(stus, function(index, item){
//一下这种形式是jquery创建html元素的语法,如果不理解,看一下jquery语法
var seq = $("<td></td>").append(index+1);
var stuId = $("<td></td>").append(item.id);
var stuDeptName = $("<td></td>").append(item.department);
var className = $("<td></td>").append(item.className);
var stuName = $("<td></td>").append(item.name);
var tempreture1 = $("<td></td>").append(item.tempretrue1);
var tempreture2 = $("<td></td>").append(item.tempretrue2);
var tempreture3 = $("<td></td>").append(item.tempretrue3);
var editBtn = $("<Button></Button>").addClass("btn btn-primary btn-xs").append($("<span></span>").addClass("glyphicon glyphicon-pencil")).append("编辑");
var deltBtn = $("<Button></Button>").addClass("btn btn-danger btn-xs").append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("删除");
var btnTd = $("<td></td>").append(editBtn).append(" ").append(deltBtn);
$("<tr></tr>").append(seq).append(stuId).append(stuDeptName).append(className).append(stuName).
append(tempreture1).append(tempreture2).append(tempreture3).
append(btnTd).appendTo("#stus_table tbody");
});
}
function build_page_info(result){
$("#page_info_div").empty();
$("#page_info_div").append("当前第" + result.datas.stuPageInfo.pageNum + "页,总共"
+ result.datas.stuPageInfo.pages + "页,共有"
+ result.datas.stuPageInfo.total + "条数据");
}
function build_page_nav(result){
$("#page_nav_div").empty();
var ul = $("<ul></ul>").addClass("pagination");
var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href","#"));
var prePageLi = $("<li></li>").append($("<a></a>").append("«"));
if(result.datas.stuPageInfo.hasPreviousPage == false){
firstPageLi.addClass("disabled");
prePageLi.addClass("disabled");
}else{
firstPageLi.click(function(){
to_page(1);
});
prePageLi.click(function(){
to_page(result.datas.stuPageInfo.pageNum - 1);
});
}
var nextPageLi = $("<li></li>").append($("<a></a>").append("»"));
var lastPageLi = $("<li></li>").append($("<a></a>").append("尾页").attr("href","#"));
if(result.datas.stuPageInfo.hasNextPage == false){
nextPageLi.addClass("disabled");
lastPageLi.addClass("disabled");
}else{
lastPageLi.click(function(){
to_page(result.datas.stuPageInfo.pages);
});
nextPageLi.click(function(){
to_page(result.datas.stuPageInfo.pageNum + 1);
});
}
ul.append(firstPageLi).append(prePageLi);
$.each(result.datas.stuPageInfo.navigatepageNums, function(index, item){
var pageNumLi = $("<li></li>").append($("<a></a>").append(item));
if(result.datas.stuPageInfo.pageNum == item){
pageNumLi.addClass("active");
}
pageNumLi.click(function(){
to_page(item);
});
ul.append(pageNumLi);
});
ul.append(nextPageLi).append(lastPageLi);
var nav = $("<nav></nav>").append(ul);
nav.appendTo("#page_nav_div")
}
</script>
<script type="text/javascript">
$("#stu_add_modal_btn").click(function(){
//点击新增按钮提弹出新增界面
$("#stuAddModal").modal({
backdrop:"static"
});
});
</script>
<!-- Modal -->
<div class="modal fade" id="stuAddModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" style="pointer-events:auto">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">增加学生</h4>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">系部</label>
<div class="col-sm-10">
<input type="text" name="department" class="form-control" id="input_department" placeholder="请输入系部名">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">班级</label>
<div class="col-sm-6">
<input type="text" name="className" class="form-control" id="input_className" placeholder="请输入班级名">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">姓名</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="name" id="input_name" placeholder="请输入姓名">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">早温</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="tempretrue1" id="input_tempretrue1" placeholder="请输入早温">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">午温</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="tempretrue2" id="input_tempretrue2" placeholder="请输入午温">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">晚温</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="tempretrue3" id="input_tempretrue3" placeholder="请输入午温">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
<button type="button" class="btn btn-primary" id="save_stu_btn">保存</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$("#save_stu_btn").click(function(){
//alert("Hello");
//发送ajax请求
$.ajax({
url:"studentsList",
type:"POSt",
data:$("#stuAddModal form").serialize(),
success:function(result){
alert(result.msg);
$("#stuAddModal").modal('hide');
to_page(9999);
}
});
});
</script>
</div>
</body>
</html>
效果如下:
2. 修改后台代码
在controller中加入添加的方法
package com.edu.tjdz.geng.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.edu.tjdz.geng.model.Message;
import com.edu.tjdz.geng.model.Student;
import com.edu.tjdz.geng.service.StudentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
@Controller
public class StudentController {
@Autowired
StudentService studentService;
//负责显示查询页面
@RequestMapping(value = "/showStudentsListpage", method = RequestMethod.GET)
public String showStudentListPage() {
return "studentsList";
}
//负责查询所有学生信息,并将学生信息封装到Message类中进行JSON格式的返回
@RequestMapping(value = "/studentsList", method = RequestMethod.GET)
@ResponseBody
public Message getStudentsWithJson(@RequestParam(value = "pageNum", defaultValue = "1")int pageNum) {
int pageSize = 10;
int showPages = 5;
System.out.println("pageNum:" + pageNum);
PageHelper.startPage(pageNum, pageSize);
List<Student> stus = studentService.getAllStudents();
PageInfo<Student> stuPageInfo = new PageInfo<Student>(stus, showPages);
return Message.success().add("stuPageInfo", stuPageInfo);
}
//负责新增信息
@RequestMapping(value="/studentsList", method = RequestMethod.POST)
@ResponseBody
public Message saveStudent(Student stu) {
studentService.saveStudent(stu);
return Message.success();
}
}
为service层添加相关代码
service接口
package com.edu.tjdz.geng.service;
import java.util.List;
import com.edu.tjdz.geng.model.Student;
public interface StudentService {
public List<Student> getAllStudents();
public void saveStudent(Student stu);
}
service的实现类
package com.edu.tjdz.geng.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.edu.tjdz.geng.dao.StudentDao;
import com.edu.tjdz.geng.model.Student;
import com.edu.tjdz.geng.service.StudentService;
@Service("studentService")
public class StudentServiceImpl implements StudentService {
@Autowired
StudentDao studentDao;
@Override
public List<Student> getAllStudents() {
return studentDao.selectAllStus();
}
@Override
public void saveStudent(Student stu) {
studentDao.insertStudent(stu);
}
}
dao层
package com.edu.tjdz.geng.dao;
import java.util.List;
import com.edu.tjdz.geng.model.Student;
public interface StudentDao {
public List<Student> selectAllStus();
public void insertStudent(Student stu);
}
mapper文件
<?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">
<!-- namespace命名空间 -->
<mapper namespace="com.edu.tjdz.geng.dao.StudentDao">
<select id="selectAllStus" resultType="com.edu.tjdz.geng.model.Student">
select id, department, class className, name,tempretrue1, tempretrue2,tempretrue3
from tbl_student
</select>
<insert id="insertStudent" parameterType="com.edu.tjdz.geng.model.Student" keyProperty="id" useGeneratedKeys="true">
insert into tbl_student(id, department, class, name, tempretrue1, tempretrue2,tempretrue3) values(#{id},#{department},#{className}, #{name}, #{tempretrue1}, #{tempretrue2}, #{tempretrue3})
</insert>
</mapper>
4.运行测试添加功能。