快速搭建基于SSM框架的web应用(上)—前后端一体篇
前言
本文主要描述如何快速搭建SSM框架的web应用,主要为前后端一体化MVC框架,下一篇将更新前后端分离下后台SSM框架的搭建
适合读者:
有一点基础的JavaWeb知识明白filter,servlet,jsp,sql等知识的同学
学习了spring,springmvc,mybatis,不知道如何整合的同学
单纯想了解SSM框架的简单搭建流程
本机环境
win10,IDEA2020.3,JDK1.8,tomcat9.0.44,maven3.8.1
本文以书籍的CRUD的操作为例,根据实体及业务创建相关的实体业务并创建项目结构
注:本文主要参考狂神的教学视频,非常感谢狂神的指导
项目创建
创建一个空的Maven项目即可
添加依赖
以下为pom.xml的配置
其中包含了junit,mysql的数据库驱动,c3p0连接池,servlet,jsp,mybatis,mybatis-spring,spring,lombok等依赖
<?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>SSMProject1</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<!--依赖:junit,数据库驱动,连接池,servlet,jsp,mybatis,mybatis-spring,spring-->
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</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.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</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.3.10</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</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>
注:依赖内容为项目自动生成,默认即可,只需在文件后面拷贝依赖以及静态资源导出(build标签中的内容,当配置文件不在resources目录下时,也能读取到配置文件)
项目结构
java文件夹下的项目结构如下
向项目当中添加web框架支持
在WEB-INF文件夹下创建jsp文件夹
实体及业务创建
概要:
创建数据库结构
创建实体类
定义业务接口
定义服务层接口
实现服务层
通过mysql创建books表,sql语句如下
-- auto-generated definition
create table books
(
bookId int not null,
bookName varchar(50) not null,
bookCounts int not null,
detail varchar(200) null,
constraint books_bookId_uindex
unique (bookId)
);
alter table books
add primary key (bookId);
创建完成后结构如下:
注:不一定通过sql创建,也可以通过其他方式创建,注意设置主键bookId
如果为了方便,通过IDEA创建也可以
在pojo文件下创建book实体类 Book.java文件
package com.test.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {
private int bookId;
private String bookName;
private int bookCounts;
private String detail;
}
注:也可以不使用注解进行操作,但必须要有set,get,有参无参构造,toString等方法,注解只是通过lombok帮助生成相关的方法
注:mysql表中字段名一定要与实体类Book属性名相同
在dao下定义底层业务接口 BookMapper及相关的数据库操作BookMapper.java如下
package com.test.dao;
import com.test.pojo.Book;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookMapper {
//增加一本书
int addBook(Book book);
//删除一本书
int deleteBook(@Param("bookId") int id);
//更新一本书的信息
int updateBook(Book book);
//查询一本书
Book queryBookById(@Param("bookId") int id);
//查询全部的书
List<Book> queryAllBook();
//通过书籍名称查找对应的书籍信息
Book queryBookByName(String bookName);
}
根据接口定义的操作,写出对应sql语句操作,BookMapper.xml如下:
<?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.test.dao.BookMapper">
<insert id="addBook" parameterType="book">
insert into books (bookId,bookName,bookCounts,detail)
values (#{bookId},#{bookName},#{bookCounts},#{detail});
</insert>
<delete id="deleteBook" parameterType="int">
delete from books where bookId=#{bookId};
</delete>
<update id="updateBook" parameterType="book">
update books set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
where bookId = #{bookId};
</update>
<select id="queryBookById" resultType="book">
select * from books where bookId = #{bookId};
</select>
<select id="queryAllBook" resultType="book">
select * from books;
</select>
<select id="queryBookByName" resultType="book">
select * from books where bookName=#{bookName}
</select>
</mapper>
注: #{xxx} 中的内容对应id方法里面对应的属性,或者引用对应的属性名。接口与配置文件名一致,即BookMapper.java,BookMapper.xml
在service包下定义服务层接口BookService.java
可以根据具体情况做调整,调整BookService的业务,在底层BookMapper的基础上做扩展即可,该项目service层与底层定义一致,并未做其他操作
package com.test.service;
import com.test.pojo.Book;
import java.util.List;
public interface BookService {
int addBook(Book book);
int deleteBook(int id);
int updateBook(Book book);
Book queryBookById(int id);
List<Book> queryAllBook();
Book queryBookByName(String bookName);
}
实现BookService接口,做具体的业务操作
package com.test.service;
import com.test.dao.BookMapper;
import com.test.pojo.Book;
import java.util.List;
public class BookServiceImpl implements BookService{
//service调Dao层,组合Dao
private BookMapper bookMapper;
//bookMapper通过spring注入????????????
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
@Override
public int addBook(Book book) {
return bookMapper.addBook(book);
}
@Override
public int deleteBook(int id) {
return bookMapper.deleteBook(id);
}
@Override
public int updateBook(Book book) {
return bookMapper.updateBook(book);
}
@Override
public Book queryBookById(int id) {
return bookMapper.queryBookById(id);
}
@Override
public List<Book> queryAllBook() {
return bookMapper.queryAllBook();
}
@Override
public Book queryBookByName(String bookName) {
return bookMapper.queryBookByName(bookName);
}
}
实现控制层
配置文件
项目主要的配置文件全部放在resources目录下
配置文件主要包括database.properties,applicationContext.xml,mybatis-config.xml,spring-dao.xml,spring-mvc.xml,spring-service.xml
database.properties
主要包括驱动,url,登录名,密码等配置
driver=com.mysql.cj.jdbc.Driver
# Mysql8.0+ &serverTimezone=Asia/Shanghai
url=jdbc:mysql://localhost:3306/库名?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
uname=自己的用户名
password=对应的登录密码
其中driver驱动在不同版本中会有不同的选择,老版本建议使用以下位置
driver=com.mysql.jdbc.Driver
如果控制台输出关于Driver相关的警告,可以替换为以下配置
driver=com.mysql.cj.jdbc.Driver
注:uname与username,建议使用uname,username在不同的数据库连接池可能会出现用户读取出错的情况;Mysql8.0以上需要配置serverTimezone=Asia/Shanghai
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>
<typeAliases>
<!--默认别名就为该类名首字母小写,即user-->
<package name="com.test.pojo"/>
</typeAliases>
<!--绑定接口 .xml与.java名字一样-->
<mappers>
<mapper class="com.test.dao.BookMapper"/>
</mappers>
</configuration>
注:在引入spring之后,mybatis相关的环境配置,都交给spring进行配置,mybatis-config.xml中只需要绑定底层业务接口
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:database.properties"/>
<!--连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driver}"/>
<property name="jdbcUrl" value="${url}"/>
<property name="user" value="${uname}"/>
<property name="password" value="${password}"/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--筛定Mybatis的配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--配置dao接口扫描包,动态实现dao接口可以注入到spring-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--扫描dao包-->
<property name="basePackage" value="com.test.dao"/>
</bean>
</beans>
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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.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">
<!--扫描service下的包-->
<context:component-scan base-package="com.test.service"/>
<!--将所有业务类注入到Spring,可以通过配置,或者注解实现-->
<bean id="bookServiceImpl" class="com.test.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--声明式事务配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--aop事务支持-->
<!--结合aop实现事务切入-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.test.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
</beans>
注:在配置该文件当中,可能会出现以下情况
这是由于配置spring配置文件没有关联的缘故,只需在总的配置文件applicationContext.xml中配置关联即可
spring-mvc.xml
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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
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">
<!--注解驱动-->
<mvc:annotation-driven/>
<!--静态资源过滤-->
<mvc:default-servlet-handler/>
<!--扫描包 controller-->
<context:component-scan base-package="com.test.controller"/>
<!--添加视图解析器(添加前后缀):模板引擎:Thymeleaf Freemarker-->
<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
由此即可将所有的配置文件关联起来,交给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">
<!--整合多个spring配置文件,使得之间有关联-->
<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>
</beans>
创建完项目结构如下
配置web.xml
主要配置springmvc接管前端发来的请求,设置编码过滤器,防止乱码
<?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>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>
<!--和tomcat一起启动-->
<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>
这时除了controller层,所有的代码都已配置完毕,配置tomcat启动应用
tomcat配置
大致流程如下,都是熟悉的配方,需要注意的时在打成war包时,一定要导入lib依赖,不然会出现ClassNotFound等问题
添加war包
修改访问路径
导入项目依赖
配置controller层
这是前端访问的中介,所有请求都会发送到这一层,这里直接上代码,BookController.java
package com.test.controller;
import com.test.pojo.Book;
import com.test.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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping("/book")
public class BookController {
//controller调service
@Autowired
@Qualifier("bookServiceImpl")
private BookService bookService;
//查询全部的书籍,并且返回到一个书籍展示页面
@RequestMapping("/allBook")
public String list(Model model){
List<Book> books = bookService.queryAllBook();
model.addAttribute("books", books);
return "allBook";
}
//跳转到增加书籍页面
@RequestMapping("/toAddBook")
public String toAddBook(){
return "addBook";
}
//添加书籍的请求
@RequestMapping("/addBook")
public String addBook(Book book){
System.out.println("addBook-->>"+book);
bookService.addBook(book);
//重定向到allBook
return "redirect:/book/allBook";
}
//跳转到修改页面
@RequestMapping("/toUpdateBook")
public String toUpdateBook(int id,Model model){
System.out.println("toUpdateBook-->>" + id);
Book book = bookService.queryBookById(id);
System.out.println(book);
model.addAttribute("queryBook", book);
return "updateBook";
}
//修改书籍
@RequestMapping("/updateBook")
public String updateBook(Book book){
System.out.println("updateBook-->>" + book);
bookService.updateBook(book);
return "redirect:/book/allBook";
}
//删除书籍
@RequestMapping("/deleteBook/{bookId}")
public String deleteBook(@PathVariable("bookId") int id){
bookService.deleteBook(id);
return "redirect:/book/allBook";
}
//查询书籍
@RequestMapping("/queryBook")
public String queryBook(String queryBookName,Model model) {
Book book = bookService.queryBookByName(queryBookName);
List<Book> books = new ArrayList<>();
if(book==null){
books = bookService.queryAllBook();
}else{
books.add(book);
}
model.addAttribute("books", books);
return "allBook";
}
}
配置好controller之后,添加jsp文件进行测试
index.jsp
<%--
Created by IntelliJ IDEA.
User: as
Date: 2021/11/10
Time: 8:24
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<style>
a{
text-decoration: none;
color: black;
font-size: 18px;
}
h3 {
width: 180px;
height: 36px;
margin: 100px auto;
text-align: center;
line-height: 38px;
background: deepskyblue;
border-radius: 6px;
}
</style>
</head>
<body>
<h3>
<%--记得取绝对地址,使项目发布时依然能够正常运行--%>
<a href="${pageContext.request.contextPath}/book/allBook">Get All Books!</a>
</h3>
</body>
</html>
allBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: as
Date: 2021/11/10
Time: 8:51
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>AllBooks</title>
<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>书籍列表</small>
</h1>
</div>
</div>
<div class="row">
<div class="col-md-4 column">
<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 column"></div>
<div class="col-md-4 column">
<%--查询书籍--%>
<form action="${pageContext.request.contextPath}/book/queryBook" method="post" style="display: flex">
<input type="text" name="queryBookName" class="form-control" placeholder="Please Input Book Name">
<input type="submit" value="Search" class="btn btn-primary">
</form>
</div>
</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>
<th>操作</th>
</tr>
</thead>
<%--从list中遍历醋回来--%>
<tbody>
<c:forEach var="book" items="${books}">
<tr>
<td>${book.bookId}</td>
<td>${book.bookName}</td>
<td>${book.bookCounts}</td>
<td>${book.detail}</td>
<td>
<a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.bookId}">修改</a>
|
<a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookId}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</body>
</html>
后记
这个项目也就玩一玩,也用不了太长时间,实际中项目搭建流程就是这些,配置过程当中可能会遇到许多问题,我都会在博客更新,其中也有许多不足的地方,希望大家批评指正