Sprig框架集成(SSM框架) | Sping+SpringMVC+Mybatis

news/2024/11/28 22:43:23/

SSM框架

在这里插入图片描述

SSM是sping+springMVC+mybatis集成的框架:标准的MVC模式,整个系统划分为表现层,controller层,service层,DAO层四层

  • Spring(业务层)

    Spring就像是整个项目中装配bean的大工厂,在配置文件中可以指定使用特定的参数去调用实体类的构造方法来实例化对象。也可以称之为项目中的粘合剂。

    Spring的核心思想是IoC(控制反转),即不再需要程序员去显式地new一个对象,而是让Spring框架帮你来完成这一切。

  • SpringMVC(表示层)

    SpringMVC在项目中拦截用户请求,它的核心Servlet即DispatcherServlet承担中介或是前台这样的职责,将用户请求通过HandlerMapping去匹配Controller,Controller就是具体对应请求所执行的操作。SpringMVC相当于SSH框架中struts。

  • Mybatis(持久层)

    mybatis是对jdbc的封装,它让数据库底层操作变的透明。mybatis的操作都是围绕一个sqlSessionFactory实例展开的。mybatis通过配置文件关联到各实体类的Mapper文件,Mapper文件中配置了每个类对数据库所需进行的sql语句映射。在每次与数据库交互时,通过sqlSessionFactory拿到一个sqlSession,再执行sql命令。

    页面发送请求给控制器,控制器调用业务层处理逻辑,逻辑层向持久层发送请求,持久层与数据库交互,后将结果返回给业务层,业务层将处理逻辑发送给控制器,控制器再调用视图展现数据

项目结构

在这里插入图片描述

SSM整合

Mybatis层

配置

  • 数据库环境配置
CREATE DATABASE `SSMBuild`;USE `SSMBuild`;DROP TABLE IF EXISTS `books`;CREATE TABLE `books`
(`bookID`     INT(10)      NOT NULL AUTO_INCREMENT COMMENT '书id',`bookName`   VARCHAR(100) NOT NULL COMMENT '书名',`bookCounts` INT(11)      NOT NULL COMMENT '数量',`detail`     VARCHAR(200) NOT NULL COMMENT '描述',KEY `bookID` (`bookID`)
) ENGINE = INNODBDEFAULT CHARSET = utf8;INSERT INTO `books`(`bookID`, `bookName`, `bookCounts`, `detail`)
VALUES (1, 'Java', 1, '从入门到放弃'),(2, 'MySQL', 10, '从删库到跑路'),(3, 'Linux', 5, '从进门到进牢');
  • pom.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>SSMBuild</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><!--依赖导入--><dependencies><!--Junit--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><!--数据库驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.49</version></dependency><!--数据库连接池--><dependency><groupId>com.mchange</groupId><artifactId>c3p0</artifactId><version>0.9.5.2</version></dependency><!--Servlet - JSP --><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.2</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><!--Mybatis--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.2</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.0.2</version></dependency><!--Spring--><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.1.9.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.1.9.RELEASE</version></dependency><!--Lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version></dependency></dependencies><!--静态资源导出问题--><build><resources><resource><directory>src/main/java</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource><resource><directory>src/main/resources</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource></resources></build>
</project>

resources包

  • mybatis-config.xml(mybatis核心配置文件)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!--配置数据源,Spring操作--><!--typeAliases:它仅用于XML配置,意在降低冗余的全限定类名书写--><typeAliases><package name="com.wei.pojo"/></typeAliases><!-- 使用映射器接口实现类的完全限定类名 --><mappers><mapper class="com.wei.dao.BookMapper"/></mappers>
</configuration>
  • applicationContext.xml(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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"></beans>
  • database.properties(核心配置文件)
jdbc.driver=com.mysql.jdbc.Driver
# 如果使用MYSQL8.0+,需要增加时区配置;&serverTimezone=Asia/Shanghai
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root

java包

  • com.wei.pojo.Books(数据库对应的实体类 )
package com.wei.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {private int bookID;private String bookName;private int bookCounts;private String detail;}
  • com.wei.dao.BookMapper(编写Dao层的 Mapper接口)
package com.wei.dao;import com.wei.pojo.Books;
import org.apache.ibatis.annotations.Param;import java.util.List;public interface BookMapper {//增加一本书int addBook(Books books);//删除一本书,@Param注解给参数命名int deleteBookById(@Param("bookId") int id);//更新一本书int updateBook(Books books);//查询一本书Books queryBookById(@Param("bookId") int id);//查询全部书List<Books> queryAllBook();
}
  • com.wei.pojo.BooksMapper.xml(编写接口对应的 Mapper.xml 映射文件,导入MyBatis的包)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wei.dao.BookMapper"><insert id="addBook" parameterType="Books">insert into ssmbuild.books (bookName, bookCounts, detail)values (#{bookName},#{bookCounts},#{detail});</insert><delete id="deleteBookById" parameterType="int">delete from ssmbuild.books where bookID=#{bookId}</delete><update id="updateBook" parameterType="Books">update ssmbuild.booksset bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}where bookID=#{bookID};</update><select id="queryBookById" parameterType="int" resultType="Books">select * from ssmbuild.books where bookID=#{bookID};</select><select id="queryAllBook" resultType="Books">select * from ssmbuild.books;</select>
</mapper>
  • 编写Service层的接口
package com.wei.service;import com.wei.pojo.Books;
import org.apache.ibatis.annotations.Param;import java.util.List;public interface BookService {//增加一本书int addBook(Books books);//删除一本书,@Param注解给参数命名int deleteBookById(int id);//更新一本书int updateBook(Books books);//查询一本书Books queryBookById(int id);//查询全部书List<Books> queryAllBook();}
  • 编写Service层的实现类
package com.wei.service;import com.wei.dao.BookMapper;
import com.wei.pojo.Books;import java.util.List;public class BookServiceImpl implements BookService{//调用dao层的操作,设置一个set接口,方便Spring管理private BookMapper bookMapper;public void setBookMapper(BookMapper bookMapper) {this.bookMapper = bookMapper;}@Overridepublic int addBook(Books books) {return bookMapper.addBook(books);}@Overridepublic int deleteBookById(int id) {return bookMapper.deleteBookById(id);}@Overridepublic int updateBook(Books books) {return bookMapper.updateBook(books);}@Overridepublic Books queryBookById(int id) {return bookMapper.queryBookById(id);}@Overridepublic List<Books> queryAllBook() {return bookMapper.queryAllBook();}
}

Spring层

resource包

  • spring-dao.xml(spring整合dao层)
<?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"><!--关联数据库配置文件:Spring读取数据库配置文件--><context:property-placeholder location="classpath:database.properties"/><!--连接池:dbcp:半自动化操作,不能自动连接c3p0:自动化操作,自动化的加载配置文件,并且可以自动设置到对象中druid、hikari--><!--dbcp:<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8"/><property name="username" value="root"/><property name="password" value="root"/></bean>--><!--c3p0--><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}"/><!-- c3p0连接池的私有属性 --><property name="maxPoolSize" value="30"/><property name="minPoolSize" value="10"/><!-- 关闭连接后不自动commit --><property name="autoCommitOnClose" value="false"/><!-- 获取连接超时时间 --><property name="checkoutTimeout" value="10000"/><!-- 当获取连接失败重试次数 --><property name="acquireRetryAttempts" value="2"/></bean><!--配置SqlSessionFactory对象--><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 注入数据库连接池 --><property name="dataSource" ref="dataSource"/><!-- 配置MyBaties全局配置文件:mybatis-config.xml --><property name="configLocation" value="classpath:mybatis-config.xml"/></bean><!--配置dao接口扫描包:动态实现Dao接口注入Spring容器--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/><property name="sqlSessionTemplateBeanName" value="sqlSessionFactory"/><!--要扫描的包--><property name="basePackage" value="com.wei.dao"/></bean>
</beans>
  • spring-service.xml(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"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"><!--扫描service下的包--><context:component-scan base-package="com.wei.service"/><!--将所有业务类注入Spring,可以通过配置或者注解--><bean id="BookServiceImpl" class="com.wei.service.BookServiceImpl"><property name="bookMapper" ref="bookMapper"/></bean><!--声明式事务管理--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!--注入数据源--><property name="dataSource" ref="dataSource"/></bean></beans>

SpringMVC层

添加web支持

  • web.xml
<?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"><!--配置DispatcherServlet: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: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>/*</url-pattern></filter-mapping><!--Session过期时间--><session-config><session-timeout>15</session-timeout></session-config>
</web-app>
  • spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/cache/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><!--注解驱动--><mvc:annotation-driven/><!--静态资源--><mvc:default-servlet-handler/><!--扫描包:controller--><context:component-scan base-package="com.wei.controller"/><!--视图解析器--><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/jsp/"/><property name="suffix" value=".jsp"/></bean>
</beans>
  • 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-dao.xml"/><import resource="classpath:spring-service.xml"/><import resource="classpath:spring-mvc.xml"/></beans>

查询书籍功能

  • BookController.java
package com.wei.controller;import com.wei.dao.BookMapper;
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 java.util.List;@Controller
@RequestMapping("/book")
public class BookController {//controller 调 service 层@Autowired@Qualifier("BookServiceImpl")   //指定一个唯一的bean对象注入private BookService bookService;//查询全部数据,并且返回到一个书籍展示页面@RequestMapping("/allBook")public String list(Model model){List<Books> list = bookService.queryAllBook();model.addAttribute("list",list);return "allBook";}
}
  • 首页index.jsp
<%--Created by IntelliJ IDEA.User: ws199Date: 2022/11/28Time: 14:19To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>首页</title><style>a{text-decoration: none;color: black;font-size: 18px;}h1{width: 180px;height: 38px;margin: 100px auto;text-align: center;line-height: 38px;background: deeppink;border-radius: 5px;}</style>
</head>
<body><h1><a href="${pageContext.request.contextPath}/book/allBook">进入书籍页面</a>
</h1></body>
</html>
  • 书籍列表页面allBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--Created by IntelliJ IDEA.User: ws199Date: 2022/11/28Time: 15:15To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>书籍展示</title><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
</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><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><th>书籍详细</th></tr></thead><%--书籍从数据库中查询出来,从这个list中遍历出来:foreach--%><tbody><c:forEach var="book" items="${list}"><tr><td>${book.bookID}</td><td>${book.bookName}</td><td>${book.bookCounts}</td><td>${book.detail}</td></tr></c:forEach></tbody></table></div></div><script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script><script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
</div>
</body>
</html>

添加书籍功能

  • BookController.java
package com.wei.controller;import com.wei.dao.BookMapper;
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 java.util.List;@Controller
@RequestMapping("/book")
public class BookController {//controller 调 service 层@Autowired@Qualifier("BookServiceImpl")   //指定一个唯一的bean对象注入private BookService bookService;//查询全部数据,并且返回到一个书籍展示页面@RequestMapping("/allBook")public String list(Model model) {List<Books> list = bookService.queryAllBook();model.addAttribute("list", list);return "allBook";}//跳转到增加书籍页面@RequestMapping("/toAddBook")public String toAddPaper() {return "addBook";}//添加书籍的请求@RequestMapping("/addBook")public String addBook(Books books) {System.out.println("addBook:" + books);bookService.addBook(books);return "redirect:/book/allBook";       //重定向到@RequestMapping("/allBook")请求}
}
  • addBook.jsp添加书籍页面
<%--Created by IntelliJ IDEA.User: ws199Date: 2022/12/1Time: 14:34To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>添加书籍</title><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
</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><form action="${pageContext.request.contextPath}/book/addBook" method="post"><div class="form-group"><label>书籍名称:</label><input type="text" name="bookName" class="form-control" required></div><div class="form-group"><label>书籍数量:</label><input type="text" name="bookCounts" class="form-control" required></div><div class="form-group"><label>书籍描述:</label><input type="text" name="detail" class="form-control" required></div><div class="form-group"><button type="submit" class="btn btn-primary">添加</button></div></form></div><script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script><script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
</div>
</body>
</html>

修改书籍功能

  • BookController.java
package com.wei.controller;import com.wei.dao.BookMapper;
import com.wei.pojo.Books;
import com.wei.service.BookService;
import org.apache.ibatis.annotations.Param;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;import java.util.List;@Controller
@RequestMapping("/book")
public class BookController {//controller 调 service 层@Autowired@Qualifier("BookServiceImpl")   //指定一个唯一的bean对象注入private BookService bookService;//查询全部数据,并且返回到一个书籍展示页面@RequestMapping("/allBook")public String list(Model model) {List<Books> list = bookService.queryAllBook();model.addAttribute("list", list);return "allBook";}//跳转到增加书籍页面@RequestMapping("/toAddBook")public String toAddPaper() {return "addBook";}//添加书籍的请求@RequestMapping("/addBook")public String addBook(Books books) {System.out.println("addBook:" + books);bookService.addBook(books);return "redirect:/book/allBook";       //重定向到@RequestMapping("/allBook")请求}//跳转到修改页面@RequestMapping("/toUpdate")public String toUpdatePaper(int id, Model model){Books books = bookService.queryBookById(id);model.addAttribute("books",books);return "updateBook";}//修改书籍@RequestMapping("/updateBook")public String updateBook(Books books){System.out.println("updateBook=>"+books);int i = bookService.updateBook(books);if (i>0){System.out.println("添加Books成功"+books);}else {System.out.println("添加Books失败");}return "redirect:/book/allBook";}
}
  • updateBook.jsp修改书籍页面
<%--Created by IntelliJ IDEA.User: ws199Date: 2022/12/3Time: 14:19To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>修改书籍</title><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
</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><form action="${pageContext.request.contextPath}/book/updateBook" method="post"><%--前端隐藏域:页面无法看见,默认提交到后台--%><input type="hidden" name="bookID" value="${books.bookID}"><div class="form-group"><label>书籍名称:</label><input type="text" name="bookName" class="form-control" value="${books.bookName}" required></div><div class="form-group"><label>书籍数量:</label><input type="text" name="bookCounts" class="form-control" value="${books.bookCounts}" required></div><div class="form-group"><label>书籍描述:</label><input type="text" name="detail" class="form-control" value="${books.detail}" required></div><div class="form-group"><button type="submit" class="btn btn-primary">修改</button></div></form></div><script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script><script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
</div>
</body>
</html>

删除书籍功能

  • BookController.java
package com.wei.controller;import com.wei.dao.BookMapper;
import com.wei.pojo.Books;
import com.wei.service.BookService;
import org.apache.ibatis.annotations.Param;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;import java.util.List;@Controller
@RequestMapping("/book")
public class BookController {//controller 调 service 层@Autowired@Qualifier("BookServiceImpl")   //指定一个唯一的bean对象注入private BookService bookService;//查询全部数据,并且返回到一个书籍展示页面@RequestMapping("/allBook")public String list(Model model) {List<Books> list = bookService.queryAllBook();model.addAttribute("list", list);return "allBook";}//跳转到增加书籍页面@RequestMapping("/toAddBook")public String toAddPaper() {return "addBook";}//添加书籍的请求@RequestMapping("/addBook")public String addBook(Books books) {System.out.println("addBook:" + books);bookService.addBook(books);return "redirect:/book/allBook";       //重定向到@RequestMapping("/allBook")请求}//跳转到修改页面@RequestMapping("/toUpdate")public String toUpdatePaper(int id, Model model){Books books = bookService.queryBookById(id);model.addAttribute("books",books);return "updateBook";}//修改书籍@RequestMapping("/updateBook")public String updateBook(Books books){System.out.println("updateBook=>"+books);int i = bookService.updateBook(books);if (i>0){System.out.println("添加Books成功"+books);}else {System.out.println("添加Books失败");}return "redirect:/book/allBook";}//删除书籍@RequestMapping("/deleteBook/{bookID}")public String deleteBook(@PathVariable("bookID") int id){bookService.deleteBookById(id);return "redirect:/book/allBook";}
}

搜索功能

  • BookMapper.java
    //查询数据Books queryBooksByName(String bookName);
  • BookMapper.xml
<select id="queryBooksByName" parameterType="String" resultType="Books">select * from ssmbuild.books where bookName like '%${bookName}%';
</select>
  • BookService.java
//查询数据
Books queryBooksByName(String bookName);
  • BookServiceImpl.java
@Override
public Books queryBooksByName(String bookName) {return bookMapper.queryBooksByName(bookName);
}
  • BookController.java
//查询数据
@RequestMapping("/queryBooks")
public String queryBooks(String queryBookName, Model model) {Books books = bookService.queryBooksByName(queryBookName);System.err.println("Books:" + books);List<Books> list = new ArrayList<Books>();list.add(books);System.out.println("queryBookName:" + queryBookName);if (books == null || queryBookName == null) {list = bookService.queryAllBook();model.addAttribute("Error", "未查到书籍");}model.addAttribute("list", list);return "allBook";
}
  • allBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--Created by IntelliJ IDEA.User: ws199Date: 2022/11/28Time: 15:15To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>书籍展示</title><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
</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="col-md-8"><a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">增加书籍</a><a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBook">显示全部书籍</a></div><div class="col-md-4"><%--查询书籍--%><form action="${pageContext.request.contextPath}/book/queryBooks" method="post"><div class="input-group mb-3"><span style="color: red;font-weight: bold;line-height: 32px">${Error}</span><input type="text" name="queryBookName" class="form-control" placeholder="请输入查询书籍名称" required><div class="input-group-append"><button class="btn btn-primary" type="submit">查询</button></div></div></form></div></div><div class="row"><div class="col-md-12 column"><table class="table table-hover table-striped"><thead><tr><th>书籍编号</th><th>书籍名称</th><th>书籍数量</th><th>书籍详细</th><td>操作</td></tr></thead><%--书籍从数据库中查询出来,从这个list中遍历出来:foreach--%><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/toUpdate?id=${book.bookID}">修改</a>&nbsp; | &nbsp;<a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">删除</a></td></tr></c:forEach></tbody></table></div></div><script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script><script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
</div>
</body>
</html>

http://www.ppmy.cn/news/19011.html

相关文章

我的硕士前半生

本篇文章属于随笔类&#xff0c;它可能无法对你起到直接帮助&#xff0c;它只是我这个普通学生一年半以来的一些足迹与思考。本文首发于我的个人博客 Forever Young 我的本科像硕士&#xff0c;有实验室有工位&#xff0c;桌子超级大&#xff0c;有老师带有学长可以问。 我的硕…

mysql之存储过程

目录 1.概念 2.创建语法 3.调用 4.示例 5.删除 6.查看 1.概念 存储过程和函数类似java中的方法&#xff0c;能够提高代码的重用性&#xff0c;能够简化操作 一组预先编译好的SQL语句的集合&#xff0c;理解成批处理语句&#xff0c;减少了编译次数并且减少了和数据库服…

用户画像计算更新

3.1 用户画像计算更新 目标 目标 知道用户画像建立的流程应用 无 3.1.1 为什么要进行用户画像 要做精准推送同样可以使用多种推荐算法&#xff0c;例如&#xff1a;基于用户协同推荐、基于内容协同的推荐等其他的推荐方式&#xff0c;但是以上方式多是基于相似进行推荐。而构…

Exadata存储服务器(又称Exadata存储单元)

存储单元可以说是让Exadata如此大规模普及并且使用效果优异的核心要素。 I/O性能问题始终是Exadata存储或者存储服务器尽力去解决的问题。 Exadata存储服务器概述 Exadata数据库一体机通常预装了3类硬件&#xff1a; 数据库计算节点服务器存储服务器极速的InfiniBand存储交…

【论文翻译】Attention Is All You Need

【论文】Attention is All you Need (neurips.cc) 摘要 主要的序列转换模型是基于复杂的循环或卷积神经网络&#xff0c;其中包括一个编码器和一个解码器。表现最好的模型还通过注意机制连接编码器和解码器。我们提出了一个新的简单的网络架构&#xff0c;Transformer&#xf…

js unicode编码相关

ASCII码 在计算机种中&#xff0c;1 字节对应 8 位二进制数&#xff0c;而每位二进制数有 0、1 两种状态&#xff0c;因此 1 字节可以组合出 256 种状态。如果这 256 中状态每一个都对应一个符号&#xff0c;就能通过 1 字节的数据表示 256 个字符。ASCII就是用于描述英语中的…

Liunx相关服务无法启动,带你一步一步找出问题和解决问题

liunx服务无法开启的原因有各种各样&#xff0c;首先我们需要找到我们究竟是为什么不能能够开启这个服务&#xff0c;这里我们先要去考虑到的一个非常重要的问题就是我们的防火墙有没有启动&#xff0c;防火墙有没有把我们的要开启相关服务的端口给封禁掉。这个是无论如何都要第…

【Unity Shader 赛博小人01】UV准备 SD制作特效贴图

写在前面 Unity 卡通渲染 程序化天空盒提到了——“再整个uv1将云片平铺&#xff0c;将uv1对应到世界坐标x轴旋转角、y轴旋转角&#xff0c;消散信息放到顶点色。”&#xff0c;就是这句话&#xff01;我又遇到了几个问题&#xff08;本菜鸡不知道的东西太多太多了&#xff09…