当前位置:网站首页>Integrate SSM to realize search of addition, deletion, modification and query
Integrate SSM to realize search of addition, deletion, modification and query
2022-07-28 03:33:00 【Mighty CRUD】
Integrate SSM Add, delete, modify, search
Realization effect

Project structure chart


Environmental Science
Environmental Science :
IDEA
MySQL 5.7.19
Tomcat 9
Maven 3.6
requirement :
- Need to master MySQL database ,Spring,JavaWeb And MyBatis knowledge , Simple front-end knowledge ;
Database environment
Create a database table to store book data
CREATE DATABASE `ssmbuild`;
USE `ssmbuild`;
DROP TABLE IF EXISTS `books`;
CREATE TABLE `books` (
`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT ' book id',
`bookName` VARCHAR(100) NOT NULL COMMENT ' Title ',
`bookCounts` INT(11) 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 ');
Basic environment construction
1、 New one Maven project !ssmbuild , add to web Support for
2、 Import related pom rely on !
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</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>
<!--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>
</dependencies>
3、Maven Resource filtering settings
<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>
4、 Establish the basic structure and configuration framework !
- pojo
- dao
- service
- controller
- 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>
</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 http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
Mybatis Layer
1、 Database configuration file database.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=111111
2、IDEA Associated database
3、 To write MyBatis Core profile for
<?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.syj.pojo"/>
</typeAliases>
<mappers>
<mapper resource="com/syj/dao/BookMapper.xml"/>
</mappers>
</configuration>
4、 Write the entity class corresponding to the database
package com.syj.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;
}
5、 To write Dao Layer of Mapper Interface !
package com.syj.dao;
import com.kuang.pojo.Books;
import java.util.List;
public interface BookMapper {
// Add one more Book
int addBook(Books book);
// according to id Delete one Book
int deleteBookById(int id);
// to update Book
int updateBook(Books books);
// according to id Inquire about , Return to one Book
Books queryBookById(int id);
// Query all Book, return list aggregate
List<Books> queryAllBook();
}
6、 Write the interface corresponding to Mapper.xml file . Import required MyBatis My bag ;
<?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">
<mapper namespace="com.syj.dao.BookMapper">
<!-- Add one more Book-->
<insert id="addBook" parameterType="Books">
insert into ssmbuild.books(bookName,bookCounts,detail)
values (#{bookName}, #{bookCounts}, #{detail})
</insert>
<!-- according to id Delete one Book-->
<delete id="deleteBookById" parameterType="int">
delete from ssmbuild.books where bookID=#{bookID}
</delete>
<!-- to update Book-->
<update id="updateBook" parameterType="Books">
update ssmbuild.books
set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
where bookID = #{bookID}
</update>
<!-- according to id Inquire about , Return to one Book-->
<select id="queryBookById" resultType="Books">
select * from ssmbuild.books
where bookID = #{bookID}
</select>
<!-- Query all Book-->
<select id="queryAllBook" resultType="Books">
SELECT * from ssmbuild.books
</select>
</mapper>
7、 To write Service Layer interface and implementation class
Interface :
package com.syj.service;
import com.kuang.pojo.Books;
import java.util.List;
//BookService: The following needs to be realized , call dao layer
public interface BookService {
// Add one more Book
int addBook(Books book);
// according to id Delete one Book
int deleteBookById(int id);
// to update Book
int updateBook(Books books);
// according to id Inquire about , Return to one Book
Books queryBookById(int id);
// Query all Book, return list aggregate
List<Books> queryAllBook();
}
Implementation class :
package com.syj.service;
import com.kuang.dao.BookMapper;
import com.kuang.pojo.Books;
import java.util.List;
public class BookServiceImpl implements BookService {
// call dao The operation of the layer , Set up a set Interface , convenient Spring management
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public int addBook(Books book) {
return bookMapper.addBook(book);
}
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();
}
}
Spring layer
1、 To configure Spring Integrate MyBatis, We use the data source here c3p0 Connection pool ;
2、 Let's write Spring Integrate Mybatis Related configuration files of ;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">
<!-- Configuration integration mybatis -->
<!-- 1. Associate database file -->
<context:property-placeholder location="classpath:database.properties"/>
<!-- 2. Database connection pool -->
<!-- Database connection pool
dbcp Semi automatic operation Can't automatically connect
c3p0 Automation ( Automatically load the configuration file And set it in the object )
-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- Configure connection pool properties -->
<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. To configure SqlSessionFactory object -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- Inject the database connection pool -->
<property name="dataSource" ref="dataSource"/>
<!-- To configure MyBaties Global profile :mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 4. Configure scan Dao Interface package , Dynamic implementation Dao Interface injection to spring In the container -->
<!-- explain :https://www.cnblogs.com/jpfss/p/7799806.html-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- Inject sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- Give need to scan Dao Interface package -->
<property name="basePackage" value="com.kuang.dao"/>
</bean>
</beans>
3、Spring Integrate service layer
<?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">
<!-- scanning service dependent bean -->
<context:component-scan base-package="com.syj.service" />
<!--BookServiceImpl Injection into IOC In the container -->
<bean id="BookServiceImpl" class="com.kuang.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!-- Configure transaction manager -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- Inject the database connection pool -->
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
Spring Layer is done ! Understand again ,Spring It's a hodgepodge , A container ! Right !
SpringMVC layer
1、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-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- Be sure to pay attention to : What we're loading here is the general configuration file , Before I was trapped here !-->
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--encodingFilter-->
<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 Expiration time -->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
2、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: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 http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- To configure SpringMVC -->
<!-- 1. Turn on SpringMVC Annotation driven -->
<mvc:annotation-driven />
<!-- 2. Static resource default servlet To configure -->
<mvc:default-servlet-handler/>
<!-- 3. To configure jsp Show ViewResolver view resolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 4. scanning web dependent bean -->
<context:component-scan base-package="com.kuang.controller" />
</beans>
3、Spring Configuration integration file ,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="spring-dao.xml"/>
<import resource="spring-service.xml"/>
<import resource="spring-mvc.xml"/>
</beans>
The configuration file , For the time being !Controller and View layer writing
1、BookController Class writing , Method 1 : Search all books
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
@RequestMapping("/allBook")
public String list(Model model) {
List<Books> list = bookService.queryAllBook();
model.addAttribute("list", list);
return "allBook";
}
}
2、 Write the home page index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE HTML>
<html>
<head>
<title> home page </title>
<style type="text/css">
a {
text-decoration: none;
color: black;
font-size: 18px;
}
h3 {
width: 180px;
height: 38px;
margin: 100px auto;
text-align: center;
line-height: 38px;
background: deepskyblue;
border-radius: 4px;
}
</style>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/book/allBook"> Click to enter the list page </a>
</h3>
</body>
</html>
3、 Book list page allbook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> List of books </title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- introduce Bootstrap -->
<link href="https://cdn.bootcss.com/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>
<div class="row">
<div class="col-md-4 column">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook"> newly added </a>
</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> The name of the book </th>
<th> Number of books </th>
<th> Book details </th>
<th> operation </th>
</tr>
</thead>
<tbody>
<c:forEach var="book" items="${requestScope.get('list')}">
<tr>
<td>${book.getBookID()}</td>
<td>${book.getBookName()}</td>
<td>${book.getBookCounts()}</td>
<td>${book.getDetail()}</td>
<td>
<a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}"> change </a> |
<a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}"> Delete </a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
4、BookController Class writing , Method 2 : Add books
@RequestMapping("/toAddBook")
public String toAddPaper() {
return "addBook";
}
@RequestMapping("/addBook")
public String addPaper(Books books) {
System.out.println(books);
bookService.addBook(books);
return "redirect:/book/allBook";
}
5、 Add a Book page :addBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> New books </title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- introduce Bootstrap -->
<link href="https://cdn.bootcss.com/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> New books </small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/addBook" method="post">
Book name :<input type="text" name="bookName"><br><br><br>
Number of books :<input type="text" name="bookCounts"><br><br><br>
Book details :<input type="text" name="detail"><br><br><br>
<input type="submit" value=" add to ">
</form>
</div>
6、BookController Class writing , Method 3 : Revise a book
@RequestMapping("/toUpdateBook")
public String toUpdateBook(Model model, int id) {
Books books = bookService.queryBookById(id);
System.out.println(books);
model.addAttribute("book",books );
return "updateBook";
}
@RequestMapping("/updateBook")
public String updateBook(Model model, Books book) {
System.out.println(book);
bookService.updateBook(book);
Books books = bookService.queryBookById(book.getBookID());
model.addAttribute("books", books);
return "redirect:/book/allBook";
}
7、 Modify the book page updateBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> Modify the information </title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- introduce Bootstrap -->
<link href="https://cdn.bootcss.com/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> Modify the information </small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/updateBook" method="post">
<input type="hidden" name="bookID" value="${book.getBookID()}"/>
Book name :<input type="text" name="bookName" value="${book.getBookName()}"/>
Number of books :<input type="text" name="bookCounts" value="${book.getBookCounts()}"/>
Book details :<input type="text" name="detail" value="${book.getDetail() }"/>
<input type="submit" value=" Submit "/>
</form>
</div>
8、BookController Class writing , Method four : Delete books
@RequestMapping("/del/{bookId}")
public String deleteBook(@PathVariable("bookId") int id) {
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
To configure Tomcat, Run !
up to now , This SSM Project integration is complete OK 了 , It can be run directly for testing !
边栏推荐
猜你喜欢

max_pool2d(): argument ‘input‘ (position 1) must be Tensor, not NoneType

MySQL stored procedures use cursors to synchronize data between two tables

bp svm的缺陷检测 树叶缺陷 叶片缺陷检测的系统设计

Practice of online problem feedback module (16): realize the function of checking details

How does win11 display fixed applications?

MySQL事务的ACID特性及并发问题实例分析

Unity背包系统

What are the fragments of MySQL

Engineering Geology Practice - engineering geology problem set

如何卸载干净zabbix服务?(超详细)
随机推荐
Unity简单实现对话功能
bp svm的缺陷检测 树叶缺陷 叶片缺陷检测的系统设计
STM32 RT-Thread虚拟文件系统挂载操作
Digital twin technology drives smart factory to reduce burden and enhance operation and maintenance benefits
Detailed tutorial of one click reinstallation of win7 system
203.移除链表元素
Shell:一键部署pxe
最新版宝塔安装zip扩展,php -m 不显示的处理方法
Shell编写规范和变量
GNU General Public License v2.0 GNU General Public License
如何卸载干净zabbix服务?(超详细)
203. Remove linked list elements
20220726 at command test of Bluetooth module hc-05 of Huicheng Technology
Acid characteristics of MySQL transactions and example analysis of concurrency problems
53. Maximum subarray maximum subarray sum
IronOCR for .NET 2022.8
How to uninstall clean ZABBIX service? (super detailed)
自定义注解的使用
Summary of concurrent programming interview questions
When QML uses layout layout, a large number of < unknown file >: QML qquicklayoutattached: binding loop detected for property circular binding warnings appear