当前位置:网站首页>SSM integration (simple library management system to integrate SSM)
SSM integration (simple library management system to integrate SSM)
2022-07-25 10:11:00 【Zero degrees Celsius】
Integrate SSM frame
1、 Database environment
- Create a database table to store book data
CREATE DATABASE ssmbuild;
USE ssmbuild;
CREATE TABLE `books`(
`bookID` INT NOT NULL AUTO_INCREMENT COMMENT ' book id',
`bookName` VARCHAR(100) NOT NULL COMMENT ' Title ',
`bookCounts` INT NOT NULL COMMENT ' Number ',
`detail` VARCHAR(200) NOT NULL COMMENT ' describe ',
KEY `bookID`(`bookID`)
)ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'Java',1,' From entry to abandonment '),
(2,'MySQL',10,' From delete to run away '),
(3,'Linux',5,' From the door to the prison ')
2、 Basic environment construction
- Create a new one Maven project ,ssmbuild, add to web Support for
- Import related pom Rely on and solve static resource export
<?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>
<dependencies>
<!-- junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- Database driven -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- Database connection pool -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.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>
<!-- servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!-- jsp-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<!-- jstl-->
<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>
<!-- mybatis-spring-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.2.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
</dependencies>
<!-- Solve the problem of static resource export -->
<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>
- Establish the basic structure and configuration framework
pojo layer
dao layer
service layer
controller layer
Configuration framework
- 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><?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> </configuration>
- 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 https://www.springframework.org/schema/beans/spring-beans.xsd"> </beans>
3、Mybatis Layer
- pojo layer
- Write entity classes according to the database
package com.qian.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;
}
- dao layer
- BookMapper
package com.qian.dao;
import com.qian.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookMapper {
// Add a Book
int addBook(Books books);
// Delete a Book
int deleteBookById(@Param("bookId") int id);
// Update a Book
int updateBook(Books books);
// Look up a Book
Books queryBookById(@Param("bookId") int id);
// Look up all the books
List<Books>queryAllBook();
}
- BookMapper.xml
<?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.qian.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.books set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
where bookID = #{bookID}
</update>
<select id="queryBookById" resultType="Books">
select * from ssmbuild.books where bookID=#{bookId}
</select>
<select id="queryAllBook" resultType="Books">
select * from ssmbuild.books
</select>
</mapper>
- Service layer
- BookService Interface
package com.qian.service;
import com.qian.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookService {
// Add a Book
int addBook(Books books);
// Delete a Book
int deleteBookById( int id);
// Update a Book
int updateBook(Books books);
// Look up a Book
Books queryBookById( int id);
// Look up all the books
List<Books> queryAllBook();
}
- Implementation class
package com.qian.service;
import com.qian.pojo.Books;
import com.qian.dao.BookMapper;
import java.util.List;
public class BookServiceImpl implements BookService{
//service Layer calls dao layer , Combine dao layer
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper){
this.bookMapper=bookMapper;
}
public int addBook(Books books) {
return bookMapper.addBook(books);
}
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
}
4、Spring Layer ( The configuration file )
- spring-dao Integrate 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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 1. Associate database profiles -->
<context:property-placeholder location="classpath:database.properties"/>
<!-- 2. Connection pool dbcp: Semi automatic operation , Can't automatically connect c3p0: Automation ( Automatic loading of configuration files , And can be automatically set to the object !) -->
<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 Private properties of connection pool -->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!-- Do not automatically close the connection commit-->
<property name="autoCommitOnClose" value="false"/>
<!-- Get connection timeout -->
<property name="checkoutTimeout" value="10000"/>
<!-- Number of retries when get connection failed -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!-- 3.sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- binding mybatis Configuration file for -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 4. To configure dao Interface scan package , Dynamic implementation dao Interface can be injected into Spring In the container -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- Inject sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- Scan what you want to scan dao package -->
<property name="basePackage" value="com.qian.dao"/>
</bean>
</beans>
- spring-service Integrate 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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 1. scanning service Bag under -->
<context:component-scan base-package="com.qian.service"/>
<!-- 2. All our business classes , Injection into spring, It can be implemented by configuration or annotation -->
<bean id="BookServiceImpl" class="com.qian.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!-- 3. Declarative transaction configuration -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- Inject data source -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 4.aop Transaction support -->
</beans>
- spring-mvc Integrate mvc
<?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: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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd" >
<!-- 1. Scanning package -->
<context:component-scan base-package="com.qian.controller"/>
<!-- 2. Static resource filtering -->
<mvc:default-servlet-handler/>
<!-- 3. Annotation driven -->
<mvc:annotation-driven/>
<!-- <!– json Garbled problem configuration –>-->
<!-- <mvc:annotation-driven>-->
<!-- <mvc:message-converters register-defaults="true">-->
<!-- <bean class="org.springframework.http.converter.StringHttpMessageConverter">-->
<!-- <constructor-arg value="UTF-8"/>-->
<!-- </bean>-->
<!-- <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">-->
<!-- <property name="objectMapper">-->
<!-- <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">-->
<!-- <property name="failOnEmptyBeans" value="false"/>-->
<!-- </bean>-->
<!-- </property>-->
<!-- </bean>-->
<!-- </mvc:message-converters>-->
<!-- </mvc:annotation-driven>-->
<!-- 4. view resolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="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 https://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:springmvc-servlet.xml"/>
</beans>
5、 Inquire about 、 Delete 、 modify 、 Add book function
- memories :
In the use of @Autowire When it comes to automatic injection , add @Qualifier(“test”) You can specify which object to inject ;
- Start with the front end , Analyze requirements
- Home page
<%--
Created by IntelliJ IDEA.
User: HUAWEI
Date: 2022/5/6
Time: 21:11
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> home page </title>
<style>
a{
text-decoration: none;
color: black;
font-size: 18px;
}
h3{
width: 180px;
height: 38px;
margin: 100px auto;
text-align: center;
line-height: 38px;
background-color: deepskyblue;
border-radius: 5px;
}
</style>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/book/allBook"> Go to the book page </a>
</h3>
</body>
</html>
- The first demand , Click to jump to all book pages
// Check all the books , And return to a book display page
@RequestMapping("/allBook")
public String list(Model model){
List<Books> books = bookService.queryAllBook();
model.addAttribute("list",books);
return "allBook";
}
- Write a book display page
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: HUAWEI
Date: 2022/5/7
Time: 14:50
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> Book display page </title>
<%-- BootStrap: Beautification interface --%>
<!-- new Bootstrap The core CSS file -->
<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> List of books ----> Show all books </small>
</h1>
</div>
</div>
<div class="row">
<div class="col-md-4 column">
<%-- Jump to the add book page addBooks.jsp--%>
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddPaper"> Add books </a>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-hover table-striped">
<thead>
<tr>
<th> Book number </th>
<th> Book name </th>
<th> Number of books </th>
<th> Book details </th>
<th> operation </th>
</tr>
</thead>
<%-- The books are retrieved from the database , From this list Traversal out of :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/toUpdatePaper?id=${book.bookID}"> modify </a>
|
<a href="${pageContext.request.contextPath}/book/toDeletePaper?id=${book.bookID}"> Delete </a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
- demand : Click to jump to add books
//to Jump to the add book page addBooks.jsp
@RequestMapping("/toAddPaper")
public String toAddPaper(){
return "addBooks";
}
- Add a Book page
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> Add books </title>
<%-- BootStrap: Beautification interface --%>
<!-- new Bootstrap The core CSS file -->
<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> Add books </small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/addBook" method="post">
<div class="form-group">
<label > Book name </label>
<input type="text" name="bookName" class="form-control" >
</div>
<div class="form-group">
<label > Number of books </label>
<input type="text" name="bookCounts" class="form-control" >
</div>
<div class="form-group">
<label > Book description </label>
<input type="text" name="detail" class="form-control" >
</div>
<div class="form-group">
<input type="submit" class="form-control" value=" add to " >
</div>
<%-- Write a request to add books --%>
</form>
</div>
</body>
</html>
- Click Add submit to complete the request to add books
// Submit and add books
@RequestMapping("/addBook")
public String addBooks(Books books){
System.out.println("addBook=>"+books);
bookService.addBook(books);
return "redirect:/book/allBook"; // Redirect to allbook This request
}
- This completes a function request , Other functions are implemented like this . First analyze from the front page , then controller Layer .
6、 Search book function
- Add a function of searching books by name , Develop from bottom to top , It should be from dao Layer begins to add functions , And then there was dao The implementation of the , then service, And then there was service The implementation of the
- BookMapper
// Search book
Books queryBookByName(@Param("bookName") String bookName);
- BookMapper.xml
<select id="queryBookByName" resultType="Books">
select * from ssmbuild.books where bookName = #{bookName}
</select>
- BookService
// Search books by name
Books queryBookByName( String bookName);
- BookServiceImpl
public Books queryBookByName(String bookName) {
return bookMapper.queryBookByName(bookName);
}
- Start from the front , Need to display all books on the page , Add a query form
- allBook.jsp
<div class="col-md-8 column ">
<%-- Query books --%>
<form action="${pageContext.request.contextPath}/book/queryBookName" style="float: right" method="post" class="form-inline">
<span style="color:red;font-weight: bold">${error}</span>
<input type="text" name="queryBookName" class="form-control" placeholder=" Please enter the name of the book you want to query ">
<input type="submit" value=" Inquire about " class="btn btn-primary">
</form>
</div>
- To realize that you can query the specified books after pressing query ,controller Implement this function
// Query books
@RequestMapping("/queryBookName")
public String queryBook(String queryBookName,Model model){
Books books = bookService.queryBookByName(queryBookName);
List<Books> list =new ArrayList<Books>();
list.add(books);
if (books==null){
list=bookService.queryAllBook();
model.addAttribute("error"," Not found ");
}
model.addAttribute("list",list);
return "allBook";
}
- Optimize : If the search is empty , There is a button to view all books again ( The front-end implementation )
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBook"> Show all books </a>
边栏推荐
- ¥ 1-2 example 2.2 put the union of two sets into the linear table
- TM1637带秒点四位LED显示器模块ARDUINO驱动程序
- [RNN] analyze the RNN from rnn- (simple|lstm) to sequence generation, and then to seq2seq framework (encoder decoder, or seq2seq)
- dp-851
- ADC介绍
- 一个可以返回前一页并自动刷新页面的ASP代码.
- 【建议收藏】靠着这些学习方法,我入职了世界五百强——互联网时代的“奇技淫巧”
- Record of deep learning segment error (segment core/ exit code 139)
- Yarn quick reference manual
- LOAM 融合 IMU 细节之 TransformToEnd 函数
猜你喜欢
![[recommended collection] with these learning methods, I joined the world's top 500 - the](/img/95/e34473a1628521d4b07e56877fcff1.png)
[recommended collection] with these learning methods, I joined the world's top 500 - the "fantastic skills and extravagance" in the Internet age

~3 CCF 2022-03-2 travel plan

CCF 201509-3 template generation system

Introduction to armv8 general timer

TM1638 LED数码显示模块ARDUINO驱动代码

Data viewing and parameter modification of multi-channel vibrating wire, temperature and analog sensing signal acquisition instrument

JDBC总结
![[nearly 10000 words dry goods] don't let your resume don't match your talent -- teach you to make the most suitable resume by hand](/img/2d/e3a326175f04826b9d9c96baedc3a5.png)
[nearly 10000 words dry goods] don't let your resume don't match your talent -- teach you to make the most suitable resume by hand

Temperature, humidity and light intensity acquisition based on smart cloud platform

多通道振弦、温度、模拟传感信号采集仪数据查看和参数修改
随机推荐
An ASP code that can return to the previous page and automatically refresh the page
[deployment of deep learning model] deploy the deep learning model using tensorflow serving + tornado
Eco introduction
SSM整合(简单的图书管理系统来整合SSM)
阿里MQTT物联网平台“云产品流转”实战——两片ESP32通过物联网平台实现远程互操作
C语言基础
Internal structure of SOC chip
【建议收藏】靠着这些学习方法,我入职了世界五百强——互联网时代的“奇技淫巧”
CCF 201512-3 drawing
Connection and data reading of hand-held vibrating wire vh501tc collector sensor
ECO简介
Mlx90640 infrared thermal imaging sensor temperature measurement module development notes (III)
GCD详解
Pnpm Brief
LOAM 融合 IMU 细节之 TransformToEnd 函数
See how a junior student of double non-2 (0 Internship) can get an offer from Alibaba and Tencent
【成长必备】我为什么推荐你写博客?愿你多年以后成为你想成为的样子。
JSP详解
Qt 6.2的下载和安装
Introduction to low power consumption and UPF