功能的实现:
从前端页面jsp页面发送请求到controller层
controller调用service业务层
service业务层调用dao持久层
dao持久层实现和数据库交互
最终都是通过spring来整合mybatis和springmvc
!!为了更好的理解和管理spring的整合
将applicationContext.xml拆分为三个配置文件分别管理
spring-dao.xml :Mybatis,dao
spring-service.xml :service
spring-mvc.xml :MVC
最终在applicationContext.xml配置文件中通过导入,使三个配置文件产生联系
使得三层架构更加明显清晰,容易理解。
spring主配置文件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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:spring-service.xml"></import>
<import resource="classpath:spring-dao.xml"></import>
<import resource="classpath:spring-mvc.xml"></import>
</beans>
1、创建了一个简单的数据库,对user表进行增删改查操作
create database test;
use test;
create table user(
username varchar(20),
password varchar(20));
版本锁定
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<spring.version>5.0.2.RELEASE</spring.version>
<mysql.version>5.1.6</mysql.version>
<mybatis.version>3.4.5</mybatis.version>
</properties>
引入坐标依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
User
public class User implements Serializable {
private String username;
private String password;
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserDao
public interface UserDao {
//查询用户
List<User> queryAllUser();
//增加用户
void addUser(User user);
//更具用户名查User
User queryUserByName(String username);
//修改用户
void updateUser(User user);
//删除用户
void deleteUser(String username);
}
完成
1、取别名
2、映射mapper映射文件
<!--mybatis config的约束-->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--配置mybatis日志-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--配置数据源,交给spring去做-->
<!--取别名-->
<typeAliases>
<package name="com.ama.domain"/>
</typeAliases>
<!--映射mapper的映射文件-->
<mappers>
<mapper class="com.ama.dao.UserDao"></mapper>
</mappers>
</configuration>
对UserDao接口中函数功能的实现
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ama.dao.UserDao">
<select id="queryAllUser" resultType="User">
select * from test.user ;
</select>
<insert id="addUser" parameterType="User">
insert into test.user(username, password) values (#{username},#{password});
</insert>
<select id="queryUserByName" parameterType="String" resultType="User">
select * from test.user where username = #{username};
</select>
<update id="updateUser" parameterType="User">
update test.user
set password=#{password}
where username=#{username};
</update>
<delete id="deleteUser" parameterType="String">
delete from test.user
where username = #{username}
</delete>
</mapper>
1、关联数据库配置文件:jdbc.properties
jdbc.driverManager = com.mysql.jdbc.Driver jdbc.url =jdbc:mysql://localhost:3306/test jdbc.username = root jdbc.password =123456
2、配置连接池
3、配置sqlSessionFactory
4、配置dao接口扫描包,动态的实现了dao接口可以注入到spring容器中
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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">
<!-- 整合mybatis层-->
<!--1、关联数据库配置文件-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!--2、连接池
dbcp:半自动化操作,不能自动连接
c3p0:自动化操作(自动化加载配置文件,并且可以自动设置到对象中)
druid:企业公司使用
-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverManager}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!--c3p0私有属性-->
<property name="maxPoolSize" value="30"></property>
<property name="minPoolSize" value="10"></property>
<property name="autoCommitOnClose" value="false"></property>
<property name="checkoutTimeout" value="10000"></property>
<property name="acquireRetryAttempts" value="2"></property>
</bean>
<!--3、sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!--绑定Mybatis的配置文件-->
<property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
</bean>
<!--4、配置dao接口扫描包,动态的实现了dao接口可以注入到spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<!--要扫描的包-->
<property name="basePackage" value="com.ama.dao"></property>
</bean>
</beans>
UserService
public interface UserService {
//查询用户
List<User> queryAllUser();
//增加用户
void addUser(User user);
//根据用户名查User
User queryUserByName(String username);
//修改用户
void updateUser(User user);
//删除用户
void deleteUser(String username);
}
UserServiceImpl
通过调用UserDao来实现业务
public class UserServiceImpl implements UserService {
private UserDao userDao;
//通过配置的方式实现注入
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public List<User> queryAllUser() {
return userDao.queryAllUser();
}
@Override
public void addUser(User user) {
userDao.addUser(user);
}
@Override
public User queryUserByName(String username) {
return userDao.queryUserByName(username);
}
@Override
public void updateUser(User user) {
System.out.println(user);
userDao.updateUser(user);
}
@Override
public void deleteUser(String username) {
userDao.deleteUser(username);
}
}
spring-service配置文件
<?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">
<!--1、扫描service下的包(注解)-->
<context:component-scan base-package="com.ama.service"></context:component-scan>
<!--2、将我们的所有业务类,注入到spring,可以通过配置,或者通过注解,一下是配置类型-->
<bean id="userService" class="com.ama.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<!--3、声明式事务配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--4、配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find" read-only="true"/>
<tx:method name="*" isolation="DEFAULT"></tx:method>
</tx:attributes>
</tx:advice>
<!--5、配置AOP增强-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.ama.service.impl.UserServiceImpl.*.*(..))"></aop:advisor>
</aop:config>
</beans>
1、 配置前端控制器DispatcherServlet,
2、初始化参数,在服务器启动时 加载spring的核心配置文件applicationContext.xml
3、配置中文乱码过滤器
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--DispatchServlet-->
<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:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 乱码过滤-->
<filter>
<filter-name>encodingFilter</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>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*
spring-mvc.xml
1、加载注解驱动
2、静态资源过滤
3、扫描包controller
4、视图解析器
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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">
<!--1、加载注解驱动-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--2、静态资源过滤-->
<mvc:default-servlet-handler></mvc:default-servlet-handler>
<!--3、扫描包controller-->
<context:component-scan base-package="com.ama.controller"></context:component-scan>
<!--4、视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
index.jsp首页通过超链接
查看所有用户
执行UserController 中的 queryAllUser(Model model)方法
调用service 实现查询功能 并且将得到的userList发送给
queryAllUser.jsp实现展示
queryAllUser.jsp页面中 实现了展示,查询,删除,新增等功能
Tomcat版本:8.5
1、index.jsp
2、queryAllUser.jsp
3、addUser.jsp
4、updateUser.jsp
index.jsp(首页)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>
<a href="/user/queryAllUser">查看所有用户</a>
</h3>
</body>
</html>
queryAllUser.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>用户展示</title>
<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>用户列表——————显示所有数据</small>
</h1>
</div>
</div>
<div class="row">
<div class="col-md-4-column">
<a class="btn btn-primary" href="/user/toAddUser">新增用户</a>
<a class="btn btn-primary" href="/user/queryAllUser">显示全部用户</a>
<%--查询书籍--%>
<form action="/user/queryUser" method="post" class="form-inline" style="float: right">
<span style="color: red;font-wight:bold">${error}</span>
<input type="text"| name="username" class="form-control" placeholder="请输入要查询的书籍名称">
<input type="submit" value="查询" class="btn btn-primary">
</form>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-hover table-striped">
<thead>
<tr>
<th>用户名称</th>
<th>用户密码</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="user" items="${userList}">
<tr>
<td>${user.username}</td>
<td>${user.password}</td>
<td>
<a href="/user/toUpdateUser?username=${user.username}">修改</a> |
<a href="/user/deleteUser?username=${user.username}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
addUser.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>用户展示</title>
<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-5 column">
<div class="page-header">
<h1>
<small>新增书籍</small>
</h1>
</div>
</div>
</div>
<form action="/book/addUser" method="post">
<div class="form-group">
<label >用户姓名</label>
<input type="text" name="username" class="form-control">
</div>
<div class="form-group">
<label >用户密码</label>
<input type="text" name="password" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="添加" class="form-control">
</div>
</form>
</div>
</body>
</html>
updateUser.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>用户修改</title>
<link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-5 column">
<div class="page-header">
<h1>
<small>修改书籍</small>
</h1>
</div>
</div>
</div>
<%--隐藏域<input type="hidden" value="${Book.bookID}">--%>
<form action="/user/updateUser" method="post">
<div class="form-group">
<label >用户姓名</label>
<input type="text" name="username" value="${User.username}" class="form-control">
</div>
<div class="form-group">
<label >用户密码</label>
<input type="text" name="password" value="${User.password}" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="修改" class="form-control">
</div>
</form>
</div>
</form>
</body>
</html>
UserController
@Controller
@RequestMapping("/user")
public class UserController {
//controller调用service
@Autowired
private UserService userService;
//查询所有用户,并且放回到展示页面
@RequestMapping("/queryAllUser")
public String queryAllUser(Model model){
List<User> users = userService.queryAllUser();
model.addAttribute("userList",users);
return "queryAllUser";
}
//跳转到增加用户页面
@RequestMapping("/toAddUser")
public String toAddUser(){
return "addUser";
}
//添加用户的请求
@RequestMapping("/addUser")
public String addUser(User user){
System.out.println("addUser=>"+user);
userService.addUser(user);
return "redirect:/user/queryAllUser"; //重定向到查群全部用户queryAllUser页面
}
//跳转到修改页面
@RequestMapping("/toUpdateUser")
public String toUpdateUser(String username , Model model){
System.out.println(username);
User user = userService.queryUserByName(username);
System.out.println(user+"调给updateUser");
model.addAttribute("User",user);
return "updateUser";
}
//修改用户的请求
@RequestMapping("/updateUser")
public String updateUser(User user){
System.out.println("addUser=>"+user);
userService.updateUser(user);
return "redirect:/user/queryAllUser"; //重定向到查群全部用户queryAllUser页面
}
//删除数据
@RequestMapping("/deleteUser")
public String deleteUser(String username){
userService.deleteUser(username);
return "redirect:/user/queryAllUser";
}
//查询用户
@RequestMapping("/queryUser")
public String queryUser(String username , Model model){
User user = userService.queryUserByName(username);
System.out.println(user);
List<User> users = new ArrayList<User>();
users.add(user);
if(user == null){
users = userService.queryAllUser();
model.addAttribute("error","未查到");
}
model.addAttribute("userList",users);
return "queryAllUser";
}
}
主页面超链接
展示页面
页面中的功能:新增用户,修改,删除,查询
均通过提交请求,表单可实现。
查询如果为空 显示全部内容并显示 未查到
java学习力推哔哩哔哩 up主!!:遇见狂神说
主页链接地址:https://space.bilibili.com/95256449/