Prerequisites
Required developmant environment:
- IntelliJ IDEA
- MySQL 5.7.19
- Tomcat 9
- Maven 3.6
Required knowledge: Proficiency in MySQL, Spring, JavaWeb, and MyBatis, along with basic frontend skills.
Database Initialization
Create a schema for storing publication records:
CREATE DATABASE `library_db`;
USE `library_db`;
DROP TABLE IF EXISTS `publications`;
CREATE TABLE `publications` (
`pub_id` INT(10) NOT NULL AUTO_INCREMENT COMMENT 'Publication ID',
`title` VARCHAR(100) NOT NULL COMMENT 'Publication Title',
`stock` INT(11) NOT NULL COMMENT 'Available Stock',
`description` VARCHAR(200) NOT NULL COMMENT 'Description',
PRIMARY KEY (`pub_id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `publications`(`pub_id`, `title`, `stock`, `description`) VALUES
(1, 'Mastering Java', 1, 'From入门 to 放弃'),
(2, 'Advanced MySQL', 10, 'From 删库 to 跑路'),
(3, 'Linux Operations', 5, 'From 进门 to 进牢');
Project Structure Setup
Create a Maven project named library-ssm and enable Web Application support. Organize the packages as follows:
com.example.pojo(Entities)com.example.mapper(DAO)com.example.service(Business Logic)com.example.controller(Web Layer)
Dependency Configuration (pom.xml)
Import the necessary libraries for JUnit, MySQL, C3P0, Servlet/JSP, MyBatis, and Spring:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<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>
<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>
Resource Filtering
Ensure XML and properteis files in the source directories are copied to the output:
<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>
MyBatis Layer Implementation
1. Database connection properties (jdbc.properties):
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/library_db?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
2. MyBatis Configuration (mybatis-config.xml):
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<typeAliases>
<package name="com.example.pojo"/>
</typeAliases>
<mappers>
<mapper resource="com/example/mapper/PublicationMapper.xml"/>
</mappers>
</configuration>
3. Entity Class (Publication.java):
package com.example.pojo;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Publication {
private int pubId;
private String title;
private int stock;
private String description;
}
4. Mapper Interface (PublicationMapper.java):
package com.example.mapper;
import com.example.pojo.Publication;
import java.util.List;
public interface PublicationMapper {
int insertPublication(Publication publication);
int removePublicationById(int id);
int editPublication(Publication publication);
Publication findPublicationById(int id);
List<Publication> fetchAllPublications();
}
5. Mapper XML (PublicationMapper.xml):
<?xml version="1.0" encoding="UTF-8" ?>
<mapper namespace="com.example.mapper.PublicationMapper">
<insert id="insertPublication" parameterType="Publication">
INSERT INTO library_db.publications(title, stock, description)
VALUES (#{title}, #{stock}, #{description})
</insert>
<delete id="removePublicationById" parameterType="int">
DELETE FROM library_db.publications WHERE pub_id = #{pubId}
</delete>
<update id="editPublication" parameterType="Publication">
UPDATE library_db.publications
SET title = #{title}, stock = #{stock}, description = #{description}
WHERE pub_id = #{pubId}
</update>
<select id="findPublicationById" resultType="Publication">
SELECT * FROM library_db.publications WHERE pub_id = #{pubId}
</select>
<select id="fetchAllPublications" resultType="Publication">
SELECT * FROM library_db.publications
</select>
</mapper>
6. Service Interface (PublicationService.java):
package com.example.service;
import com.example.pojo.Publication;
import java.util.List;
public interface PublicationService {
int add(Publication publication);
int delete(int id);
int update(Publication publication);
Publication getById(int id);
List<Publication> getAll();
}
7. Service Implementation (PublicationServiceImpl.java):
package com.example.service;
import com.example.mapper.PublicationMapper;
import com.example.pojo.Publication;
import java.util.List;
public class PublicationServiceImpl implements PublicationService {
private PublicationMapper publicationMapper;
public void setPublicationMapper(PublicationMapper publicationMapper) {
this.publicationMapper = publicationMapper;
}
public int add(Publication publication) {
return publicationMapper.insertPublication(publication);
}
public int delete(int id) {
return publicationMapper.removePublicationById(id);
}
public int update(Publication publication) {
return publicationMapper.editPublication(publication);
}
public Publication getById(int id) {
return publicationMapper.findPublicationById(id);
}
public List<Publication> getAll() {
return publicationMapper.fetchAllPublications();
}
}
Spring Layer Configuration
1. Data Access Configuration (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">
<context:property-placeholder location="classpath:jdbc.properties"/>
<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}"/>
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<property name="autoCommitOnClose" value="false"/>
<property name="checkoutTimeout" value="10000"/>
<property name="acquireRetryAttempts" value="2"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.example.mapper"/>
</bean>
</beans>
2. Service Configuration (spring-service.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
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.example.service" />
<bean id="publicationServiceImpl" class="com.example.service.PublicationServiceImpl">
<property name="publicationMapper" ref="publicationMapper"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
Spring MVC Layer
1. Web Descriptor (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">
<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>
<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>
</web-app>
2. MVC Configuration (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">
<mvc:annotation-driven />
<mvc:default-servlet-handler/>
<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>
<context:component-scan base-package="com.example.controller" />
</beans>
3. Master Context (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>
Controller and Views
1. Controller Logic (PublicationController.java):
package com.example.controller;
import com.example.pojo.Publication;
import com.example.service.PublicationService;
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("/publication")
public class PublicationController {
@Autowired
@Qualifier("publicationServiceImpl")
private PublicationService publicationService;
@RequestMapping("/list")
public String listPublications(Model model) {
List<Publication> pubList = publicationService.getAll();
model.addAttribute("pubList", pubList);
return "publication-list";
}
@RequestMapping("/add")
public String addPublication(Publication publication) {
publicationService.add(publication);
return "redirect:/publication/list";
}
@RequestMapping("/toAddPage")
public String toAddPage() {
return "publication-add";
}
@RequestMapping("/delete/{id}")
public String deletePublication(@PathVariable("id") int id) {
publicationService.delete(id);
return "redirect:/publication/list";
}
@RequestMapping("/edit/{id}")
public String editPublication(@PathVariable("id") int id, Model model) {
Publication pub = publicationService.getById(id);
model.addAttribute("publication", pub);
return "publication-edit";
}
@RequestMapping("/update")
public String updatePublication(Publication publication) {
publicationService.update(publication);
return "redirect:/publication/list";
}
}
2. Index Page (index.jsp):
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Home</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: deepskyblue; border-radius: 4px; }
</style>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/publication/list">View Publications</a>
</h3>
</body>
</html>
3. List View (publication-list.jsp):
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Publication List</title>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h1><small>Publication Inventory</small></h1>
</div>
</div>
<div class="row">
<div class="col-md-4">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/publication/toAddPage">Add New</a>
</div>
</div>
<table class="table table-hover table-striped">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Stock</th>
<th>Description</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<c:forEach var="pub" items="${pubList}">
<tr>
<td>${pub.pubId}</td>
<td>${pub.title}</td>
<td>${pub.stock}</td>
<td>${pub.description}</td>
<td>
<a href="${pageContext.request.contextPath}/publication/edit/${pub.pubId}">Edit</a> |
<a href="${pageContext.request.contextPath}/publication/delete/${pub.pubId}">Delete</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</body>
</html>
4. Add Form (publication-add.jsp):
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Add Publication</title>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1><small>Add New Publication</small></h1>
<form action="${pageContext.request.contextPath}/publication/add" method="post">
Title: <input type="text" name="title"><br><br>
Stock: <input type="text" name="stock"><br><br>
Description: <input type="text" name="description"><br><br>
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
5. Edit Form (publication-edit.jsp):
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Edit Publication</title>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1><small>Edit Publication</small></h1>
<form action="${pageContext.request.contextPath}/publication/update" method="post">
<input type="hidden" name="pubId" value="${publication.pubId}">
Title: <input type="text" name="title" value="${publication.title}"><br><br>
Stock: <input type="text" name="stock" value="${publication.stock}"><br><br>
Description: <input type="text" name="description" value="${publication.description}"><br><br>
<input type="submit" value="Update">
</form>
</div>
</body>
</html>