Environmental requirements
-
- IDEA
-
- MySQL
-
- Tomcat 9
-
- Maven 3.6
Required knowledge: MySQL database, Spring, Javaweb, Mybatis and some simple front-end knowledge;
The MySQL database
- Create a database for your 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 'description'.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 deleting libraries to running away'),
(3.'Linux'.5.'From the door to the prison.');
Copy the code
Setting up the basic environment
- Create a new Maven project (I built ssmBuild) and add support for the Web framework
- Import the relevant POM dependencies
<! Dependencies: junit, database, database connection pool, servlet, JSP, mybatis, mybatis -- spring, spring-->
<dependencies>
<! --Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<! -- Database driver -->
<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>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<! --lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
</dependencies>
Copy the code
- Maven resource filtering problem
<! Static resource export filtering problem -->
<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>
Copy the code
- Create the appropriate frame package
- con.lyw.pojo
- com.lyw.dao
- com.lyw.service
- com.lyw.controller
resources
- Create mybatis – config. XML
<! DOCTYPEconfiguration
PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>
Copy the code
- Create the applicationContext. Xml3
<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>
Copy the code
Mybatis layer preparation
- MySQL > create database configuration file database.properties(resources)
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306? serverTimezone=GMT%2B8 jdbc.username=root jdbc.password=426457Copy the code
- IDEA Associated database
- Write the core configuration file of Mybatis
<! DOCTYPEconfiguration
PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.lyw.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.lyw.dao.BookMapper"/>
</mappers>
</configuration>
Copy the code
- Writing entity classes
- The Lombok plug-in is used
package com.lyw.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
public int bookID;
public String bookName;
public int bookCounts;
public String detail;
}
Copy the code
- Write the Mapper interface for the DAO layer
package com.lyw.dao;
import com.lyw.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);
// Query a book
Books QueryBookById(@Param("bookID")int id);
// Query all books
List<Books> QueryAllBook(a);
// query by title
Books queryBookByName(@Param("bookName") String bookName);
}
Copy the code
- Write the mapper.xml file
<! DOCTYPEmapper
PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lyw.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>
<select id="queryBookByName" resultType="Books">
select * from ssmbuild.books
where bookName=#{bookName};
</select>
</mapper>
Copy the code
- Write interfaces and implementation classes for the Service layer
- Interface:
package com.lyw.service;
import com.lyw.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);
// Query a book
Books QueryBookById(int id);
// Query all books
List<Books> QueryAllBook(a);
// query by title
Books queryBookByName(String bookName);
}
Copy the code
- Implementation class:
package com.lyw.service;
import com.lyw.dao.BookMapper;
import com.lyw.pojo.Books;
import java.util.List;
public class BookServiceImpl implements BookService{
//Service invokes THE DAO layer: combines the 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(a) {
return bookMapper.QueryAllBook();
}
public Books queryBookByName(String bookName) {
returnbookMapper.queryBookByName(bookName); }}Copy the code
Writing the Spring layer
- Configure Spring to integrate Mybatis (I’m using c3P0 connection pool)
- Write the Spring integration Mybatis configuration file: spring-dao.xml
<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. Associate database configuration file -->
<context:property-placeholder location="classpath:database.properties"/>
<! --2. Connection pool DBCP: semi-automated operation c3P0: automated operation (automatic loading of configuration files, and can be set to objects!) Druid: hikari -- >
<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 connection pool private property -->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<! -->
<property name="autoCommitOnClose" value="false"/>
<! Get connection timeout time -->
<property name="checkoutTimeout" value="10000"/>
<! Retry times -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<! --3.sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<! -- Bind mybatis config file -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<! The dao interface can be dynamically injected into the Spring container.
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<! - injection sqlSessionFactory -- -- >
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<! -- dao package to scan -->
<property name="basePackage" value="com.lyw.dao"/>
</bean>
</beans>
Copy the code
- Write the Spring integration service configuration file: spring-service.xml
<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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<! --1. Scan packets under service -->
<context:component-scan base-package="com.lyw.service"/>
<! 2. Inject all of our business classes into Spring, either through configuration or annotations -->
<bean id="BookServiceImpl" class="com.lyw.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>
<! Aop transaction support -->
<! -- Configure transaction notification -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<! -- Config transaction entry -->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.lyw.dao.*.*(..) )"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
</beans>
Copy the code
SpringMVC layer writing
- web.xml
<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>
<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>
<! -- Garbled filter -->
<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>
Copy the code
- Configuration file for SpringMVC: spring-mVC.xml
<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 https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<! --1. Register driver -->
<mvc:annotation-driven/>
<! --2. Static resource filtering -->
<mvc:default-servlet-handler/>
<! --3. Scan package: controller-->
<context:component-scan base-package="com.lyw.controller"/>
<! --4. 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>
</beans>
Copy the code
- Integration of Spring configuration: ApplicationContext.xml
<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-mvc.xml"/>
<import resource="classpath:spring-service.xml"/>
</beans>
Copy the code
Above is the basic framework and configuration file preparation content!! Need to memorize!!
Controller class and view layer writing
- BookController– Query all books
@Controller
@RequestMapping("/book")
public class BookController {
/ / controller tuning service
@Autowired
@Qualifier("BookServiceImpl")
BookService bookService;
// Query all books and return to a book display interface
@RequestMapping("/allBook")
public String list(Model model){
List<Books> booksList = bookService.QueryAllBook();
model.addAttribute("list",booksList);
return "allBook";
}
Copy the code
- Write the home page: index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<! DOCTYPEHTML>
<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 go to the list page</a>
</h3>
</body>
</html>
Copy the code
- Book list: 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">
<! -- Add Bootstrap to beautify the interface
<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>Book list - Displays 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">new</a>
<a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBook">All the books</a>
</div>
<div class="col-md-8 column"><%-- query book --%><form class="form-inline" action="${pageContext.request.contextPath}/book/queryBook" method="post" style="float: right">
<span style="color: red; font-weight: bold">${err}</span>
<input type="text" name="queryBookName" class="form-control" placeholder="Please enter the name of the book to be queried">
<input type="submit" value="Query" 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>Book number</th>
<th>Book name</th>
<th>The number of books</th>
<th>The 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()}">To change the</a> |
<a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}">delete</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
Copy the code
- BookController– Add books
// Add books
@RequestMapping("/toAddBook")
public String toAddPaper(a) {
return "addBook";
}
@RequestMapping("/addBook")
public String addPaper(Books books) {
System.out.println(books);
bookService.addBook(books);
return "redirect:/book/allBook";
}
Copy the code
- Add a book interface: 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>The new books</title>
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<! 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>The new books</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/addBook" method="post">Book Title:<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">
</form>
</div>
Copy the code
- BookController– Modify books
// Modify the 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";
}
Copy the code
- Modify the book interface: 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">
<! 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 Title:<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>
Copy the code
8 BookController– Delete books
// Delete books
@RequestMapping("/del/{bookId}")
public String deleteBook(@PathVariable("bookId") int id) {
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
Copy the code
9 BookController– Query books by title
// Query books
@RequestMapping("/queryBook")
public String queryBook(String queryBookName, Model model){
Books books = bookService.queryBookByName(queryBookName);
List<Books> booksList = new ArrayList<Books>();
booksList.add(books);
if (books==null) {
booksList=bookService.QueryAllBook();
model.addAttribute("err"."Not found.");
}
model.addAttribute("list",booksList);
return "allBook";
}
Copy the code
Configure Tomcat to run tests!
This is the first time for SSM framework integration, need more practice to become proficient!
Come on!