使用 Spring 去整合另外两个框架,选择XML + 注解的方式
Outline:
Spring 接管 service 层
Mybatis 接管 Dao 层 和 Bean 层
SpringMVC 接管 Controller 层
项目包含学生信息的增删改查功能以及分页功能,最终效果如下图所示:
main 文件夹下建立 java 和 src 文件夹,并分别设置为 Source root 和 Resources root
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.8maven.compiler.source>
<maven.compiler.target>1.8maven.compiler.target>
<spring.version>5.0.2.RELEASEspring.version>
<slf4j.version>1.6.6slf4j.version>
<log4j.version>1.2.12log4j.version>
<mysql.version>5.1.6mysql.version>
<mybatis.version>3.4.5mybatis.version>
properties>
<dependencies>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.6.8version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>compilescope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${mysql.version}version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>${log4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.0version>
dependency>
<dependency>
<groupId>c3p0groupId>
<artifactId>c3p0artifactId>
<version>0.9.1.2version>
<type>jartype>
<scope>compilescope>
dependency>
dependencies>
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`student_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`age` int(11) NOT NULL,
`sex` varchar(255) NOT NULL,
`birthday` date DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `student_id` (`student_id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;
Bean (数据库相关(Bean/Dao 都交给Mybatis管理))
public class Student {
private int id;
private int student_id;
private String name;
private int age;
private String sex;
private Date birthday;
public Student() {
}
public Student(int id, int student_id, String name, int age, String sex, Date birthday) {
this.id = id;
this.student_id = student_id;
this.name = name;
this.age = age;
this.sex = sex;
this.birthday = birthday;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getStudent_id() {
return student_id;
}
public void setStudent_id(int student_id) {
this.student_id = student_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
Dao层无须实现接口,交给Mabatis来做
@Repository
public interface StudentDao {
/**
* 获取学生总数
* @return
*/
int getTotal();
/**
* 添加一个学生
* @param student
*/
void addStudent(Student student);
/**
* 根据 id 删除一个人学生
* @param id
*/
void deleteStudent(int id);
/**
* 修改一个学生信息
* @param student
*/
void updateStudent(Student student);
/**
* 根据 id 获取一个学生信息
* @param id
* @return
*/
Student getStudent(int id);
/**
* 查询从start位置开始的count条数据
*/
List<Student> list(int start, int count);
}
⭐ Service 需要实现接口(Service 层由 Spring 管理),在 Service 中注入 Dao 对象
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
StudentDao studentDao;
@Override
public int getTotal() {
return studentDao.getTotal();
}
@Override
public void addStudent(Student student) {
studentDao.addStudent(student);
}
@Override
public void deleteStudent(int id) {
studentDao.deleteStudent(id);
}
@Override
public void updateStudent(Student student) {
studentDao.updateStudent(student);
}
@Override
public Student getStudent(int id) {
return studentDao.getStudent(id);
}
@Override
public List<Student> list(int start, int count) {
return studentDao.list(start, count);
}
}
Controller(交给 SpringMVC 管理)
@Controller
public class StudentController {
}
在resources文件夹下新建 spring-mybatis.xml
文件(我们将 mybatis 的配置也写在该文件中,此处我们只列出 Spring 所需要的配置)
<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
http://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.smallbeef.service"/>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<filter>
<filter-name>characterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceRequestEncodingparam-name>
<param-value>trueparam-value>
init-param>
<init-param>
<param-name>forceResponseEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring-mybatis.xmlparam-value>
context-param>
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/listStudent.jspurl-pattern>
servlet-mapping>
<welcome-file-list>
<welcome-file>listStudent.jspwelcome-file>
welcome-file-list>
web-app>
SpringMVC 的默认启动页是 WEB-INF 文件夹下的 index.jsp 文件,此处我们修改默认启动页为 resources 文件夹下的 listStudent.jsp 文件,需要在 web.xml 中添加配置:
<servlet-mapping> <servlet-name>dispatcherServletservlet-name> <url-pattern>/listStudent.jspurl-pattern> servlet-mapping> <welcome-file-list> <welcome-file>listStudent.jspwelcome-file> welcome-file-list>
在 resources 文件夹下新建 springmvc.xml
文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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-3.0.xsd">
<context:component-scan base-package="com.smallbeef.controller"/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
bean>
beans>
⭐ 在 Controller 中注入 Service 对象
@Controller
public class StudentController {
@Autowired
private StudentService studentService;
/**
* 增加一个学生信息
* @param request
* @param response
* @return
*/
@RequestMapping("/addStudent")
public String addStudent(HttpServletRequest request, HttpServletResponse response){
Student student = new Student();
// 获取前端传值
int studentId = Integer.parseInt(request.getParameter("student_id"));
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
String sex = request.getParameter("sex");
Date birthday = null;
// 将 String 类型的日期按照 yyyy-MM-dd 的格式转换为 java.util.Date 类
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
birthday = simpleDateFormat.parse(request.getParameter("birthday"));
} catch (ParseException e) {
e.printStackTrace();
}
student.setStudent_id(studentId);
student.setName(name);
student.setAge(age);
student.setSex(sex);
student.setBirthday(birthday);
studentService.addStudent(student);
return "redirect:listStudent";
}
/**
* 根据 id 删除一个学生信息
* @param id
* @return
*/
@RequestMapping("/deleteStudent")
public String deleteStudent(int id){
studentService.deleteStudent(id);
return "redirect:listStudent";
}
/**
* 修改一个学生信息,进入修改界面editStudent后再调用
* @param request
* @param response
* @return
*/
@RequestMapping("/updateStudent")
public String updateStudent(HttpServletRequest request, HttpServletResponse response){
Student student = new Student();
// 获取前端传值
int studentId = Integer.parseInt(request.getParameter("student_id"));
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
String sex = request.getParameter("sex");
Date birthday = null;
// 将 String 类型的日期按照 yyyy-MM-dd 的格式转换为 java.util.Date 类
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
birthday = simpleDateFormat.parse(request.getParameter("birthday"));
} catch (ParseException e) {
e.printStackTrace();
}
student.setStudent_id(studentId);
student.setName(name);
student.setAge(age);
student.setSex(sex);
student.setBirthday(birthday);
studentService.updateStudent(student);
return "redirect:listStudent";
}
/**
* 分页显示学生信息
*/
@RequestMapping("/listStudent")
public String listStudent(HttpServletRequest request, HttpServletResponse response) {
// 获取分页参数
int start = 0;
int count = 6;
try {
start = Integer.parseInt(request.getParameter("page.start"));
count = Integer.parseInt(request.getParameter("page.count"));
} catch (Exception e) {
}
// 创建分页模型
Page page = new Page(start, count);
// 按照页码查询学生信息
List<Student> students = studentService.list(page.getStart(), page.getCount());
int total = studentService.getTotal();
page.setTotal(total);
// 将查询出来的学生信息放在域中
request.setAttribute("students", students);
request.setAttribute("page", page);
return "listStudent";
}
/**
* 用于修改学生信息界面的信息回显
* @param id
* @return
*/
@RequestMapping("/editStudent")
public ModelAndView editStudent(int id){
// 创建一个模型视图对象
ModelAndView mv = new ModelAndView();
// 查询学生信息
Student student = studentService.getStudent(id);
// 将数据放置到 ModelAndView 对象视图中
mv.addObject("student",student);
// 放入 jsp 界面
mv.setViewName("editStudent");
return mv;
}
}
在 util 包中 新建文件 Page.java
public class Page {
int start; // 开始数据
int count; // 每一页的数量
int total; // 总共的数据量
public Page() {
}
public Page(int start, int count, int total) {
this.start = start;
this.count = count;
this.total = total;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public Page(int start, int count) {
super();
this.start = start;
this.count = count;
}
// 是否有上一页
public boolean isHasPreviouse(){
if(start==0)
return false;
return true;
}
//是否有下一页
public boolean isHasNext(){
if(start==getLast())
return false;
return true;
}
//获取总页数
public int getTotalPage(){
int totalPage;
// 假设总数是50,是能够被5整除的,那么就有10页
if (0 == total % count)
totalPage = total /count;
// 假设总数是51,不能够被5整除的,那么就有11页
else
totalPage = total / count + 1;
if(0==totalPage)
totalPage = 1;
return totalPage;
}
//获取最后一页页数
public int getLast(){
int last;
// 假设总数是50,是能够被5整除的,那么最后一页的开始就是40
if (0 == total % count)
last = total - count;
// 假设总数是51,不能够被5整除的,那么最后一页的开始就是50
else
last = total - total % count;
last = last<0?0:last;
return last;
}
}
listStudent.jsp:学生信息显示 + 增加学生 界面
<%@ page contentType="text/html;charset=UTF-8" language="java"
pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%-- 引入JQ和Bootstrap --%>
学生管理页面 - 首页
editStudent.jsp:修改学生信息界面
修改学生信息界面 和 增加学生信息 基本如出一辙,只不过修改学生界面多了信息回显的功能。在 input
框中我们通过 EL 表达式进行信息回显, 比如:
value="${student.age}"
我们在 controller 的方法 editStudent
中 将通过 id 查询到的 student 对象放入 ModelAndView 中,此处我们通过 EL 表达式取出其具体的值
详细代码如下:
<%@ page contentType="text/html;charset=UTF-8" language="java"
pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%-- 引入JQ和Bootstrap --%>
学生管理页面 - 编辑页面
修改学生
对于 Mybatis 的配置,我们将其与 Spring 的配置放在一个文件中:spring-mybatis.xml
,Spring 接管 MyBatis 的 Session 工厂
<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
http://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.smallbeef.service"/>
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
<property name="minPoolSize" value="${c3p0.minPoolSize}"/>
<property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
<property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
<property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.smallbeef.bean"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.smallbeef.dao"/>
bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
beans>
在 resources 文件夹下新建 jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
#数据库地址
jdbc.url=jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf8
#用户名
jdbc.username=root
#密码
jdbc.password=root
#最大连接数
c3p0.maxPoolSize=30
#最小连接数
c3p0.minPoolSize=10
#关闭连接后不自动commit
c3p0.autoCommitOnClose=false
#获取连接超时时间
c3p0.checkoutTimeout=10000
#当获取连接失败重试次数
c3p0.acquireRetryAttempts=2
在 resources 文件夹下新建 mapper.studentDao.xml 文件:
<mapper namespace="com.smallbeef.dao.StudentDao">
<select id="getTotal" resultType="int">
SELECT COUNT(*) FROM student
select>
<insert id="addStudent" parameterType="Student">
INSERT INTO student VALUES(NULL, #{student_id}, #{name}, #{age}, #{sex}, #{birthday})
insert>
<delete id="deleteStudent" parameterType="int">
DELETE FROM student WHERE id = #{id}
delete>
<update id="updateStudent" parameterType="Student">
UPDATE student SET student_id = #{student_id}, name = #{name},
age = #{age}, sex = #{sex}, birthday = #{birthday} WHERE id = #{id}
update>
<select id="getStudent" resultMap="student" parameterType="int">
SELECT * FROM student WHERE id = #{id}
select>
<resultMap id="student" type="student">
<id column="id" property="id"/>
<result column="student_id" property="student_id"/>
<result column="name" property="name"/>
<result column="age" property="age"/>
<result column="sex" property="sex"/>
<result column="birthday" property="birthday" javaType="java.sql.Date"/>
resultMap>
<select id="list" resultMap="student">
SELECT * FROM student ORDER BY student_id asc limit #{param1}, #{param2}
select>
mapper>
视频 - SpringMVC_黑马
课程配套百度网盘资源:
链接:https://pan.baidu.com/s/1bH-d1yBugAr0DjGzx7DGIA
提取码:nsct
学生管理系统(SSM简易版)总结