1、创建Web项目
2、导入jar包
3、配置文件
Web.xml
<?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>spring-springmvc-mybatis</display-name>
<!-- 全局的参数配置,配Spring的配置文件路径,监听器可读取到 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/applicationcontext.xml</param-value>
</context-param>
<!-- 配置Spring的启动,配一个监听器,项目启动时就自动加载IOC容器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置SpringMVC框架的启动,也就是配置前端控制器 ,SpringMVC框架的启动是配置一个Servlet -->
<servlet>
<!-- 如果配置文件在默认的路径下,则配置文件的命名name-servlet.xml -->
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 当SpringMVC的配置文件不在默认的目录中时(webinfo),添加如下配置文件的路径 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/springMVC-servlet.xml</param-value>
</init-param>
<!-- Serlvet的启动机制是第一次访问时才运行,但是SpringMVC在项目启动时就需要配置,如何解决?配置此Serlvet在程序启动时就执行 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<!-- Struts2的用法: *.do *.action SpringMVC则用:/,表示过滤所有的请求。 错误的用法是:/* -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- springMVC自带字符编码过滤 -->
<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>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
applicationcontext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
">
<!-- 启用注解 -->
<context:annotation-config />
<!-- 扫描指定包中的所有的对象 -->
<context:component-scan base-package="com.min.services.impl" />
<!-- 这个Bean用于读取数据库连接相关的属性文件 -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:config/jdbc.properties" />
</bean>
<!-- 数据源 及 连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<!-- ${driver}取属性文件中: driver键的值 -->
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<!-- <property name="initialSize" value="${initialSize}" /> -->
<!-- <property name="maxActive" value="${maxActive}" /> -->
<!-- <property name="maxIdle" value="${maxIdle}" /> -->
<!-- <property name="minIdle" value="${minIdle}" /> -->
</bean>
<!-- 根据数据源 配置Mybatis访问数据库 加载映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据源对象 -->
<property name="dataSource" ref="dataSource" />
<!-- 加载所有的映射文件 *表示通配符 -->
<property name="mapperLocations" value="classpath:com/min/mapper/*.xml" />
<!-- 如果有MyBatis的主配置文件,则加载主配置文件,否则就要加载实体类的别名 -->
<property name="configLocation" value="classpath:config/mybatis-config.xml" />
<!-- 扫描entity层中所有的实体,给实体对象取别名 -->
<!-- <property name="typeAliasesPackage" value="com.min.bean"/> -->
</bean>
<!--========== 使用注解启用事务 ============= -->
<!-- 启用事务注解 transaction-manager="transactionManager"引用事务管理Bean -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- 配置事务管理Bean -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 事务处理需要依赖数据源对象 -->
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/myschool?characterEncoding\=utf-8
username=root
password=root
#initialSize=10
#maxActive=100
#maxIdle=20
#minIdle=5
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>
<!--MyBatis整合Spring框架时,通常 Settings配置且留下,其它的都可以移动到Spring的配置文件中进行配置 -->
<!-- 并不一定需要<settings> 此节点用于延迟加载。 -->
<!-- <settings> -->
<!-- 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置fetchType属性来覆盖该项的开关状态。 -->
<!-- <setting name="lazyLoadingEnabled" value="true" /> -->
<!-- 当开启时,任何方法的调用都会加载该对象的所有属性。否则,每个属性会按需加载(参考lazyLoadTriggerMethods). -->
<!-- <setting name="aggressiveLazyLoading" value="false" /> -->
<!-- </settings> -->
<!-- 为实体类指定一个别名,为了简化映射时使用类的全限定名称,通常情况下,建议别名与类名一致 -->
<typeAliases>
<!--只需要写一次 package 表示把这个包中所有的实体类取别名,命名规则:别名与类名一致 -->
<package name="com.min.bean" />
</typeAliases>
</configuration>
springMVC-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
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-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 因为采用了注解配置,要启用注解配置 -->
<mvc:annotation-driven />
<!-- 把程序中的所有控制器类扫描SpringMVC的框架中 -->
<context:component-scan base-package="com.min.controller" />
<!-- 视图分解器的配置,前缀与后缀用于拼接控制器类中的方法返回的视图名称。最终得到视图的具体路径.. -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀:/表示项目的根据目录 -->
<property name="prefix" value="/" />
<!-- 后缀,控制器中只需要返回视图的名称,则框架会根据视图名称加上前缀与后缀,得到最终视图路径 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
4、Src
Bean
package com.min.bean;
public class Grade {
private int gradeId;
private String gradeName;
public Grade() {
super();
}
public Grade(int gradeId, String gradeName) {
super();
this.gradeId = gradeId;
this.gradeName = gradeName;
}
public int getGradeId() {
return gradeId;
}
public void setGradeId(int gradeId) {
this.gradeId = gradeId;
}
public String getGradeName() {
return gradeName;
}
public void setGradeName(String gradeName) {
this.gradeName = gradeName;
}
@Override
public String toString() {
return "Grade [gradeId=" + gradeId + ", gradeName=" + gradeName + "]";
}
}
Dao、
package com.min.dao;
import java.util.List;
import com.min.bean.Grade;
/**
* MyBatis与映射文件进行关联
* @author Administrator
*
*/
public interface GradeDao {
/**
* 查询全部
* @return
*/
public List<Grade> listAll();
/**
* 通过id查询对象
* @param gradeId
* @return
*/
public Grade selectByGradeId(int gradeId);
/**
* 加入对象
* @param grade
* @return
*/
public int insert(Grade grade);
/**
* 修改信息
* @param grade
* @return
*/
public int update(Grade grade);
/**
* 删除对象
* @param gradeId
* @return
*/
public int delete(int gradeId);
}
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.min.dao.GradeDao">
<!-- 当实体对象的属性名与表中的字段名不一致情况下,则采用resultMap进行属性与字段的映射 -->
<resultMap type="Grade" id="grade">
<!-- 主键用id 非主键、外键用result -->
<!-- column代表数据库字段名,property代表实体类属性 -->
<id column="gradeId" property="gradeId" />
<result column="gradeName" property="gradeName" />
</resultMap>
<!-- 定义一个冗余的SQL语句,其它的指令可以用include指令导入,反复引用,减少了重复代码量 -->
<sql id="gradeSelect">
select * from grade
</sql>
<!-- 查找 -->
<select id="listAll" resultMap="grade">
<include refid="gradeSelect" />
</select>
<!-- 通过gradeId查找 -->
<select id="selectByGradeId" resultMap="grade" parameterType="int">
<include refid="gradeSelect" />
where gradeId=#{gradeId};
</select>
<insert id="insert" parameterType="Grade" >
insert into grade values(null,#{gradeName})
</insert>
<update id="update" parameterType="Grade" >
update grade set gradeName=#{gradeName} where gradeId=#{gradeId}
</update>
<delete id="delete" parameterType="int">
delete from grade where gradeId=#{gradeId}
</delete>
</mapper>
services、
package com.min.services;
import java.util.List;
import com.min.bean.Grade;
public interface GradeServices {
/**
* 查询全部
* @return
*/
public List<Grade> listAll();
/**
* 通过id查询对象
* @param id
* @return
*/
public Grade selectByGradeId(int gradeId);
/**
* 加入对象
* @param grade
* @return
*/
public int insert(Grade grade);
/**
* 修改信息
* @param grade
* @return
*/
public int update(Grade grade);
/**
* 删除对象
* @param gradeId
* @return
*/
public int delete(int gradeId);
}
package com.min.services.impl;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.min.bean.Grade;
import com.min.dao.GradeDao;
import com.min.services.GradeServices;
//注解的作用是让IOC自动扫描成对象。
@Service
public class GradeServicesImpl implements GradeServices {
// 从IOC容器中取出SqlSessionFactory工厂
@Autowired
SqlSessionFactory factory;
@Override
public List<Grade> listAll() {
// 操作数据,SqlSession对象,此对象SqlSessionFactory对象中创建 。
SqlSession sqlSession = null;
List<Grade> list = null;
try {
// 根据SqlSessionFactory工厂获取SqlSession对象,此对象操作数据
sqlSession = factory.openSession();
// 获取数据访问接口的动态代理对象
GradeDao dao = sqlSession.getMapper(GradeDao.class);
list = dao.listAll();
return list;
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
sqlSession.close();
}
return null;
}
@Override
public Grade selectByGradeId(int gradeId) {
SqlSession sqlSession = null;
Grade grade = null;
try {
sqlSession = factory.openSession();
GradeDao dao = sqlSession.getMapper(GradeDao.class);
grade = dao.selectByGradeId(gradeId);
return grade;
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
sqlSession.close();
}
return null;
}
@Override
public int insert(Grade grade) {
SqlSession sqlSession = null;
try {
sqlSession = factory.openSession();
GradeDao dao = sqlSession.getMapper(GradeDao.class);
int result = dao.insert(grade);
return result;
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
sqlSession.close();
}
return 0;
}
@Override
public int update(Grade grade) {
SqlSession sqlSession = null;
try {
sqlSession = factory.openSession();
GradeDao dao = sqlSession.getMapper(GradeDao.class);
int result = dao.update(grade);
return result;
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
sqlSession.close();
}
return 0;
}
@Override
public int delete(int gradeId) {
SqlSession sqlSession = null;
try {
sqlSession = factory.openSession();
GradeDao dao = sqlSession.getMapper(GradeDao.class);
int result = dao.delete(gradeId);
return result;
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
sqlSession.close();
}
return 0;
}
}
Junit、
package com.min.junittest;
import static org.junit.jupiter.api.Assertions.*;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.min.bean.Grade;
import com.min.services.impl.GradeServicesImpl;
class GradeServicesImplTest {
ApplicationContext cxt = new ClassPathXmlApplicationContext("config/applicationcontext.xml");
GradeServicesImpl gs = cxt.getBean(GradeServicesImpl.class);
@Test
void testListAll() {
List<Grade> list=gs.listAll();
for (Grade grade : list) {
System.out.println("grade:"+grade);
}
}
@Test
void testSelectByGradeId() {
Grade g=gs.selectByGradeId(5);
System.out.println(g);
}
@Test
void testInsert() {
Grade g=new Grade(1,"十年级");
gs.insert(g);
}
@Test
void testUpdate() {
Grade g=new Grade(1,"十年级");
gs.update(g);
}
@Test
void testDelete() {
gs.delete(14);
}
}
controller、
package com.min.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.servlet.ModelAndView;
import com.min.bean.Grade;
import com.min.services.impl.GradeServicesImpl;
@Controller
@RequestMapping("/Grade")
public class GradeController {
// 自动装配GradeService对象
@Autowired
GradeServicesImpl gradeServicesImpl;
@RequestMapping("/all")
public ModelAndView selectAll() {
List<Grade> list = gradeServicesImpl.listAll();
return new ModelAndView("gradeall", "gradelist", list);
}
@RequestMapping("/save")
public ModelAndView save(Grade grade) {
if (grade.getGradeId() > 0) { // 表示修改
gradeServicesImpl.update(grade);
} else { // 表示添加
gradeServicesImpl.insert(grade);
}
return new ModelAndView("redirect:/Grade/all");
}
@RequestMapping("/edit")
public ModelAndView edit(int id) {
Grade grade = gradeServicesImpl.selectByGradeId(id);
return new ModelAndView("gradeupdate", "grade", grade);
}
@RequestMapping("/delete")
public ModelAndView delete(int id) {
int num = gradeServicesImpl.delete(id);
if (num == 1) {
return new ModelAndView("redirect:/Grade/all");
}
return null;
}
}
Jsp、
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>年级信息入口</title>
</head>
<body>
<p><a href="Grade/all"/>年级列表 </p>
</body>
</html>
gradeall.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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>年级信息主界面</title>
</head>
<body>
<h2>年级信息列表管理</h2>
<div>
<a href="<%=request.getContextPath()%>/gradeupdate.jsp">添加年级</a>
</div>
<table border="1" width="360">
<tr>
<th>年级编号</th>
<th>年级名称</th>
<th>操作</th>
</tr>
<c:forEach items="${gradelist }" var="g">
<tr>
<td>${g.gradeId }</td>
<td>${g.gradeName }</td>
<td>
<a
href="<%=request.getContextPath()%>/Grade/edit?id=${g.gradeId }">编辑</a>
<a href="<%=request.getContextPath()%>/Grade/delete?id=${g.gradeId}"
onclick="return confirm('你确定要删除 ${g.gradeName} 吗?')">删除</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
gradeupdate.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>编辑年级信息</h2>
<form action="<%=request.getContextPath()%>/Grade/save" method="post">
<!--grade!=null?grade.gradeId:0 三目运算符 三元运算符 -->
<input type="hidden" name="gradeId"
value="${grade!=null?grade.gradeId:0 }">
<p>
年级名称:<input type="text" name="gradeName" value="${grade.gradeName}">
</p>
<p>
<input type="submit" value="提 交">
</p>
</form>
</body>
</html>
href="<%=request.getContextPath()%>/Grade/edit?id=${g.gradeId }">编辑</a>
<a href="<%=request.getContextPath()%>/Grade/delete?id=${g.gradeId}"
onclick="return confirm('你确定要删除 ${g.gradeName} 吗?')">删除</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
SQL、
/*
SQLyog Ultimate v12.4.1 (64 bit)
MySQL - 5.6.38-log
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
create table `grade` (
`gradeId` int (11),
`gradeName` varchar (30)
);
insert into `grade` (`gradeId`, `gradeName`) values('1','一年级');
insert into `grade` (`gradeId`, `gradeName`) values('2','二年级');
insert into `grade` (`gradeId`, `gradeName`) values('3','三年级');
insert into `grade` (`gradeId`, `gradeName`) values('4','四年级');
insert into `grade` (`gradeId`, `gradeName`) values('5','五年级');
insert into `grade` (`gradeId`, `gradeName`) values('6','六年级');
insert into `grade` (`gradeId`, `gradeName`) values('8','七年级');
insert into `grade` (`gradeId`, `gradeName`) values('11','初中一年级');
insert into `grade` (`gradeId`, `gradeName`) values('12','初中二年级');