ssm整合
-
mybatis :持久层,连接数据库
-
spring: 是用来整合 j2ee各个层之间的中间层。是各个层次之间是独立的,提高层与层之间的松耦合。使各个层之间对立成为对立的模块
-
springMVC :
-
表示层:(jsp、html 主要就是界面的展示)
-
控制层:(Contoller、Action)控制界面跳转
-
业务层:(Service)调用DAO层,实现解耦合目的,虽然不要它也可以运行项目,但是会使项目后期的延展和维护变得困难
-
持久层:(DAO)也叫数据访问层,实现对数据库的访问
-
SpringMVC 中的常用注解
-
@Repository:标注数据访问层,可以告诉SpringMVC这是一个数据访问层,并将其申明为一个bean,例如UserDao接口的实现类UserDaoImpl,在类上加注解@Repository(“userDao”),bean的名称为userDao
-
@Service:标注业务层,例如UserService接口的实现类,在类上加@Service(“userService”),bean的名称为userService
-
@Controller:控制层,在控制层类上加@Controller即可,确认其是一个控制层类
-
@Component:当不确定是属于哪层是用这个注解
-
@RequestMapping(): 位于控制层是暴露给前端页面的接口,既可以接受POST,又可以接受 GET,如果分开的话可以换成@PostMapping()
-
@ResponseBody 加入这个注解controller层的方法,返回的就不是对应的页面了。而是对应的字符串,可以通过Ajax或axios等技术获取数据,实现前后端分离
mybatis的整合
在ssm整合中我们就不用mybatis所给的XML配置文件所提供的数据源来连接数据库,而是交给spring的XML来做。映射数据库的XML映射文件可以继续用mybatis.xml来做,也可以完全用spring来代替mybatis.xml.
1. mybatis.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>
<!--别名-->
<typeAliases>
<package name="com.wei.pojo"/>
</typeAliases>
<!--映射对应的mapper文件-->
<mappers>
<mapper resource="com/wei/dao/BookMapper.xml"></mapper>
</mappers>
</configuration>
2.建立实体类
创建pojo层,对应数据库字段Books.java
package com.wei.pojo;
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
public Books() {
}
public Books(int bookID, String bookName, int bookCounts, String detail) {
this.bookID = bookID;
this.bookName = bookName;
this.bookCounts = bookCounts;
this.detail = detail;
}
public int getBookID() {
return bookID;
}
public void setBookID(int bookID) {
this.bookID = bookID;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getBookCounts() {
return bookCounts;
}
public void setBookCounts(int bookCounts) {
this.bookCounts = bookCounts;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
@Override
public String toString() {
return "Books{" +
"bookID=" + bookID +
", bookName='" + bookName + '\'' +
", bookCounts=" + bookCounts +
", detail='" + detail + '\'' +
'}';
}
}
3.建立对应的dao层
package com.wei.dao;
import com.wei.pojo.Books;
import java.util.List;
public interface Bookdao {
// 增加
int addBook(Books books);
// 删除
int deleteBookById(int id);
// 更新
int updateBook(Books books);
// 查询
Books queryBooksById(int id);
// 查询一本书
List<Books> queryAllBook();
}
4.创建连接数据库的Mapper文件
一定要对应自己的dao层
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wei.dao.Bookdao">
<!--增加-->
<insert id="addBook" parameterType="Books">
insert into books(bookName,bookCounts,detail)
values (#{bookName},#{bookCounts},#{detail});
</insert>
<!-- 删除功能-->
<delete id="deleteBookById" parameterType="int">
delete from books where bookID=#{id}
</delete>
<!-- 更新-->
<update id="updateBook" parameterType="Books">
update books set
bookName=#{bookName},
bookCounts=#{bookCounts},
detail=#{detail}
where bookID=#{bookID}
</update>
<!-- 查询-->
<select id="queryBooksById" resultType="Books">
select * from books where bookID = #{id}
</select>
<!-- 查询全部-->
<select id="queryAllBook" resultType="Books">
select * from books
</select>
</mapper>
Spring的整合
Spring与spring-mvc的配置文件允许多人开发,最后整合为一个Xml中,可以分为spring-dao、spring-service、spring-MVC
- 创建业务层service
-
service层的方法与dao层的方法是一样的,他代表具体的业务
-
service接口
package com.wei.service;
import com.wei.pojo.Books;
import java.util.List;
public interface Bookservice {
// 增加
int addBook(Books books);
// 删除
int deleteBookById(int id);
// 更新
int updateBook(Books books);
// 查询
Books queryBooksById(int id);
// 查询一本书
List<Books> queryAllBook();
}
-
创建service层的实现类(serviceImpl)
// service层调dao层
package com.wei.service;
import com.wei.dao.Bookdao;
import com.wei.pojo.Books;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookserviceImpl implements Bookservice {
// service层调dao层
@Autowired
private Bookdao bookdao;
public void setBookdao(Bookdao bookdao) {
this.bookdao = bookdao;
}
@Override
public int addBook(Books books) {
return bookdao.addBook(books);
}
@Override
public int deleteBookById(int id) {
return bookdao.deleteBookById(id);
}
@Override
public int updateBook(Books books) {
return bookdao.updateBook(books);
}
@Override
public Books queryBooksById(int id) {
return bookdao.queryBooksById(id);
}
@Override
public List<Books> queryAllBook() {
return bookdao.queryAllBook();
}
}
3.配置spring-dao.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--1.关联数据库配置文件-->
<context:property-placeholder location="classpath:database.properties"/>
<!--2.连接池
dbcp:半自动操作,不能自动连接
c3p0:子动画的操作
druid
-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${user}"/>
<property name="password" value="${password}"/>
</bean>
<!-- 3、sqlsessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 绑定mybatis的配置文件-->
<property name="configLocation" value="classpath:mybatis.xml"/>
</bean>
<!-- 配置到接口扫描包,动态的实现类Dao接口可以注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入-sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 要扫描的dao包-->
<property name="basePackage" value="com.wei.dao"/>
</bean>
</beans>
- database.properties文件
driver=com.mysql.jdbc.Driver
#在和mysql传递数据的过程中,使用unicode编码格式,并且字符集设置为utf-8
url=jdbc:mysql://127.0.0.1:3306/ssmbuild?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
user=root
password=root
-
配置spring-service.xml文件
- 在spring-service中注入所有的业务类到这个文件里,或者注解实现他们的配置,可以在service层配置声明式事务,或者AOP的的切面
<?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
https://www.springframework.org/schema/context/spring-context.xsd">
<import resource="classpath:spring-dao.xml"/>
<!-- 1.扫描service中的包 -->
<context:component-scan base-package="com.wei.service"/>
<!-- 2.将我们的所有的业务类,注入到spring中,可以通过配置,或者注解实现-->
<bean id="BookServiceImpl" class="com.wei.service.BookserviceImpl">
<property name="bookdao" ref="bookdao"/>
</bean>
<!--3.声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 4.AOP横切事务-->
</beans>
SpringMVC层的整合
- 一个要配置Spring-MVC的xml文件
- 驱动注解
- controller包的扫描
- 静态资源的过滤
- 视图解析器的创建【注】
<?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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--注解驱动-->
<mvc:annotation-driven/>
<!-- 2.静态资源过滤-->
<mvc:default-servlet-handler/>
<!-- 扫描包-->
<context:component-scan base-package="com.wei.controller"/>
<!-- 视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
- 在webapp中的web.xml配置service
- 配置
org.springframework.web.servlet.DispatcherServlet
的service以及service-mapping - 进行spring提供的乱码配置
- session的保存时间 计数单位是min
- 配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 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:beans.xml</param-value>
</init-param>
<!-- 启动的级别 1代表服务器一开就立马启动-->
<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>/*</url-pattern>
</filter-mapping>
<!-- session-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
- 创建controller控制层
Controller 调 service 层
- 创建BookController类
package com.wei.controller;
import com.wei.pojo.Books;
import com.wei.service.Bookservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping("/book")
public class BookController {
// Controller 调 service 层
@Autowired
@Qualifier("BookServiceImpl")
private Bookservice bookservice;
// 查询全部的书籍,并且返回到一个书籍展示页面
// @RequestMapping("/allbook")
// public @ResponseBody
// List<Books> list(Model model){
List<Books> list = bookservice.queryAllBook();
for (Books book : books) {
System.out.println(book);
}
展示到前段
// model.addAttribute("list",books);
//
// return books ;
// }
@RequestMapping("/all")
public String test(Model model){
List<Books> list = bookservice.queryAllBook();
// 展示到前段
model.addAttribute("list",list);
for (Books books : list) {
System.out.println(books);
}
return "allBook";
}
// 调转到增加书籍页面
@RequestMapping("/toAddBook")
public String toAddPaper(){
return "addBook";
}
// 添加书籍的请求
@RequestMapping("/add")
public String addBook(Books books){
System.out.println("addBooks===>"+books);
bookservice.addBook(books);
return "redirect:/book/all";//重定向
}
//调转到更新页面
@RequestMapping("/update")
public String updateBook(int id, Model model){
Books books = bookservice.queryBooksById(id);
model.addAttribute("Qbooks",books);
return "update";
}
// 调转到修改
@RequestMapping("/updateBook")
public String updateBook(Books books){
System.out.println("updateBook===>"+books);
int i = bookservice.updateBook(books);
if(i>0){
System.out.println("添加成功");
}else {
System.out.println("添加失败");
}
return "redirect:/book/all";//重定向
}
// 删除书籍操作
@RequestMapping("/deleteBook")
public String deleteBook(int id){
bookservice.deleteBookById(id);
return "redirect:/book/all";//重定向
}
}
==========================================================================================================================
至此整合完毕
==========================================================================================================================
创建对应的jsp文件
jsp的文件路径一定要个web.xml中配置的路径一致
1.创建index.jsp文件
<%--
Created by IntelliJ IDEA.
User: 17923
Date: 2020/11/3
Time: 17:13
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/book/all">进入书籍展示界面</a>
</body>
</html>
-
创建全部查询的allBook.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>全部</title> </head> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script> // $(function () { // $.ajax({ // method:'post', // url:'http://localhost:8080/book/allbook', // success:function(res){ // console.log(res); // }, // error:function(err){ // console.error(err); // } // }) // }); </script> <body> <h1>查询全部书籍</h1> <a href="${pageContext.request.contextPath}/book/toAddBook">新增书籍</a> <table> <thead> <tr> <th>书籍编号</th> <th>书籍名称</th> <th>书籍数量</th> <th>书籍详情</th> </tr> </thead> <%-- 结果查询--%> <tbody> <c:forEach var="book" items="${list}"> <tr> <td>${book.bookID}</td> <td>${book.bookName}</td> <td>${book.bookCounts}</td> <td>${book.detail}</td> <td> <a href="${pageContext.request.contextPath}/book/deleteBook?id=${book.bookID}">删除</a> | <a href="${pageContext.request.contextPath}/book/update?id=${book.bookID}">修改</a> </td> </tr> </c:forEach> </tbody> </table> </body> </html>
-
创建更新的update.jsp
<%--
Created by IntelliJ IDEA.
User: 17923
Date: 2020/11/4
Time: 9:12
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改页面</title>
</head>
<body>
<h1>修改书籍</h1>
<form action="${pageContext.request.contextPath}/book/updateBook" method="post">
<input value="${Qbooks.bookID}" name="bookID" hidden/>
书籍名称:<input type="text" name="bookName" value="${Qbooks.bookName}"/>
书籍数量:<input type="text" name="bookCounts" value="${Qbooks.bookCounts}"/>
书籍详情:<input type="text" name="detail" value="${Qbooks.detail}"/>
<input type="submit" value="修改">
</form>
</body>
</html>
- 创建添加的addBook.jsp
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>添加书籍</title>
</head>
<body>
<h1>新增书籍</h1>
<form action="${pageContext.request.contextPath}/book/add" method="post">
书籍名称:<input type="text" name="bookName"/>
书籍数量:<input type="text" name="bookCounts"/>
书籍详情:<input type="text" name="detail"/>
<input type="submit" value="提交">
</form>
</body>
</html>
测试结果