SSM框架整合(Spring、SpringMVC、MyBatis) --- 实现商品管理系统
IDEA+SSM+Maven实现商品管理系统(超详细SSM整合项目)
Hello,大家好,本周博主为大家带来一个SSM整合的一个小项目,该项目是一个阶段性的跨越,从servlet过渡到SSM,内容详细,包教包会~
什么是SSM?
SSM(Spring+SpringMVC+MyBatis)框架集由Spring、MyBatis两个开源框架整合而成(SpringMVC是Spring中的部分内容)。常作为数据源较简单的web项目的框架。
Spring
Spring就像是整个项目中装配bean的大工厂,在配置文件中可以指定使用特定的参数去调用实体类的构造方法来实例化对象。也可以称之为项目中的粘合剂。
Spring的核心思想是IoC(控制反转),即不再需要程序员去显式地new
一个对象,而是让Spring框架帮你来完成这一切。
SpringMVC
SpringMVC在项目中拦截用户请求,它的核心Servlet即DispatcherServlet承担中介或是前台这样的职责,将用户请求通过HandlerMapping去匹配Controller,Controller就是具体对应请求所执行的操作。SpringMVC相当于SSH框架中struts。
mybatis
mybatis是对jdbc的封装,它让数据库底层操作变的透明。mybatis的操作都是围绕一个sqlSessionFactory实例展开的。mybatis通过配置文件关联到各实体类的Mapper文件,Mapper文件中配置了每个类对数据库所需进行的sql语句映射。在每次与数据库交互时,通过sqlSessionFactory拿到一个sqlSession,再执行sql命令。页面发送请求给控制器,控制器调用业务层处理逻辑,逻辑层向持久层发送请求,持久层与数据库交互,后将结果返回给业务层,业务层将处理逻辑发送给控制器,控制器再调用视图展现数据。 [1]
摘自百度百科
为什么要用SSM?
首先之前编写JavaWeb项目是基于servlet实现,编写过于繁琐,创建对象过于频繁,
使用SSM框架后,spring控制service层,利用spring容器托管对象,
springmvc用于控制器Controller层,主要用于调用service层,转发或重定向页面
mybatis基于mapper接口和xml文件来实现对数据的CRUD操作
用的人多,用的企业多!!!
使用SSM框架编写Web项目的优点
简化代码,统一风格,分工明确,大大提高了编写项目的效率,提高程序的可扩展性与可维护性,可复用
项目简介
商品管理系统
用户注册,登录,添加了防跳墙功能,即未登录不可访问商品列表
商品的增删改查,多条件,分页(采用前4后3形式)
技术栈
- 开发工具:IDEA
- Java环境:jdk1.8
- 服务器:Tomcat8.0
- 后端:JavaEE , Spring , SpringMVC, Mybatis
- 前端:bootstrap+jsp
- 日志输出:log4j
- 管理工具:Maven
数据表准备
user表
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户id',
`username` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '用户名',
`password` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '用户密码',
PRIMARY KEY (`id`)
)
goods表
CREATE TABLE `goods` (
`order_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '商品id',
`buyer_name` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '买家姓名',
`buy_count` int(11) DEFAULT NULL COMMENT '购买商品的数量',
`buyer_phone` varchar(11) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '买家电话',
`goods_name` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '商品名称',
`goods_price` decimal(6,2) DEFAULT NULL COMMENT '商品价格',
`sum_price` decimal(10,2) DEFAULT NULL COMMENT '总价',
`buyer_address` varchar(256) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '买家地址',
PRIMARY KEY (`order_id`)
)
效果图
项目结构
源代码结构
配置文件结构
前端结构
依赖pom
<?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>SSM-GoodsManagerSystem</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- 依赖: junit. 数据库驱动,连接池,servlet,jsp,mybatis,mybatis-spring,spring-->
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- 数据库连接池: c3p0连接池 -->
<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.4</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.4</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>
<!-- Lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<!--字符或数字验证-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<!-- log4j日志输出 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</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>
核心配置文件
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
log4j.properties
#//???????INFO?DEBUG? ????
log4j.rootLogger=infoA,errorA,stdout,DEBUGA
#???spring????????
log4j.category.org.springframework = WARN
#??????
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.Threshold = debug
log4j.appender.stdout.layout.ConversionPattern=%d %-5p %c{1}:%L - %m%n
#??error?????
log4j.logger.errorA=error
log4j.appender.errorA=org.apache.log4j.DailyRollingFileAppender
log4j.appender.errorA.layout=org.apache.log4j.PatternLayout
log4j.appender.errorA.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n
log4j.appender.errorA.datePattern=yyyy-MM-dd'.log'
log4j.appender.errorA.Threshold = error
log4j.appender.errorA.append=true
log4j.appender.error.File=d:/log/error.log
#??DEBUG???????
log4j.logger.DEBUGA=DEBUG
log4j.appender.DEBUGA=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DEBUGA.layout=org.apache.log4j.PatternLayout
log4j.appender.DEBUGA.layout.ConversionPattern=%d{yyyy-MM-dd-HH-mm} [%t] [%c] [%p] - %m%n
log4j.appender.DEBUGA.datePattern=yyyy-MM-dd'.log'
log4j.appender.DEBUGA.Threshold = DEBUG
log4j.appender.DEBUGA.append=true
log4j.appender.DEBUGA.File=d:/log/debug_log.log
#??sql??
log4j.logger.com.ibatis=DEBUG
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
mabatis-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>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<package name="com.wanshi.bean"/>
</typeAliases>
<mappers>
<mapper resource="com/wanshi/mapper/UserInfoMapper.xml"/>
<mapper resource="com/wanshi/mapper/GoodsMapper.xml"/>
</mappers>
</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">
<!-- 配置整合mybatis -->
<!-- 1.关联数据库文件 -->
<context:property-placeholder location="classpath:database.properties"/>
<context:property-placeholder location="classpath:log4j.properties"/>
<!-- 2.数据库连接池 -->
<!--数据库连接池
dbcp 半自动化操作 不能自动连接
c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面)
-->
<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连接池的私有属性 -->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!-- 关闭连接后不自动commit -->
<property name="autoCommitOnClose" value="false"/>
<!--获取连接超时时间 -->
<property name="checkoutTimeout" value="10000"/>
<!-- 当获取连接失败重试次数 -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!-- 3.配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
<!--解释 :https://www.cnblogs.com/jpfss/p/7799806.html-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.wanshi.mapper"/>
</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: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">
<!-- 扫描service相关的bean -->
<context:component-scan base-package="com.wanshi.service" />
<!--BookServiceImpl注入到IOC容器中-->
<bean id="UserInfoServiceImpl" class="com.wanshi.service.impl.UserInfoServiceImpl">
<property name="userInfoMapper" ref="userInfoMapper"/>
</bean>
<bean id="GoodsServiceImpl" class="com.wanshi.service.impl.GoodsServiceImpl">
<property name="goodsMapper" ref="goodsMapper"/>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
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: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
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 1.注解驱动-->
<mvc:annotation-driven/>
<!-- 2.静态资源过滤-->
<mvc:default-servlet-handler/>
<!-- 3.扫描包:controller-->
<context:component-scan base-package="com.wanshi.controller"/>
<!-- 4.视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean id="loginInterceptor" class="com.wanshi.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
</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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>
</beans>
核心源代码
UserController
package com.wanshi.controller;
import com.wanshi.bean.UserInfo;
import com.wanshi.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
@Qualifier("UserInfoServiceImpl")
private UserInfoService userInfoService;
@RequestMapping("/register")
public String register() {
return "register";
}
@RequestMapping("/registerPost")
public String registerPost(UserInfo userInfo){
userInfoService.save(userInfo);
return "login";
}
@RequestMapping("/loginPost")
public String loginPost(HttpSession session,UserInfo userInfo){
UserInfo u1 = userInfoService.get(userInfo);
session.setAttribute("user", u1);
if (u1 != null) {
return "redirect:/goods/list";
}
return "register";
}
}
GoodsController
package com.wanshi.controller;
import com.wanshi.bean.Goods;
import com.wanshi.bean.Page;
import com.wanshi.service.GoodsService;
import org.apache.commons.lang3.StringUtils;
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("/goods")
public class GoodsController {
@Autowired
@Qualifier("GoodsServiceImpl")
private GoodsService goodsService;
private static final Integer PAGE_SIZE = 2;
@RequestMapping("/list")
public String list(String pageNumb, String buyerName, Model model) {
Integer pageNum = 1;
if (pageNumb != null && !pageNumb.equals("")) {
pageNum = Integer.valueOf(pageNumb);
}
Page<Goods> pager = goodsService.list(pageNum, PAGE_SIZE, buyerName);
model.addAttribute("pager", pager);
model.addAttribute("buyerName", buyerName);
return "goods/list";
}
@RequestMapping("/add")
public String add(){
return "goods/add";
}
@RequestMapping("/addGoods")
public String addGoods(Goods goods){
goodsService.save(goods);
return "redirect:/goods/list";
}
@RequestMapping("/edit/{orderId}")
public String edit(@PathVariable("orderId") Integer orderId, Model model) {
Goods goods = goodsService.get(orderId);
model.addAttribute("goods", goods);
return "goods/edit";
}
@RequestMapping("/editPost")
public String editPost(Goods goods) {
goodsService.update(goods);
return "redirect:/goods/list";
}
@RequestMapping("/del/{orderId}")
public String del(@PathVariable("orderId") Integer orderId) {
goodsService.delete(orderId);
return "redirect:/goods/list";
}
}
LoginInterceptor
package com.wanshi.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//1.对登录,注册,风格直接放行
//获取请求的uri地址
String uri = request.getRequestURI();
if (uri.contains("login") || uri.contains("register")) {
return true;
}
//2.进行session验证
Object user = request.getSession().getAttribute("user");
if (user == null) {
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp")
.forward(request, response);
return false;
}
return true;
}
}
Page分页类
package com.wanshi.bean;
import java.util.ArrayList;
import java.util.List;
/**
* 该类的使用方法必须严格按照一下流程
* 1 计算得到 总记录数 rowCount
* 2 使用带参构造方法初始化,例如 Page page1 = new Page(3, 5, 57 );
* 3 设置当前页记录 page1.setList(list1 );
*
*
* @author Administrator
*
* @param <T>
*/
public class Page<T> {
/**
* 当前页码前的页码数
*/
private static final int BeforePageNumbCount = 4;
/**
* 当前页码后的页码数
*/
private static final int AfterPageNumbCount = 3;
/**
* 当前页码
*/
private int currPage;
/**
* 总记录数
*/
private int rowCount;
/**
* 每页记录数
* 该参数就是 limit arg1,arg2 中的第2个参数 arg2
*/
private int pageSize;
/**
* 总页数
*/
private int pageCount;
/**
* 前1页页码
*/
private int prevPageNumb;
/**
* 后一页页码
*/
private int nextPageNumb;
/**
* 当前页的第1个条记录的索引
* 该变量就是 limit arg1,arg2 的第一个参数 arg1
*/
private int currPageFirstRowIndex;
/**
* 当前页记录列表
*/
private List<T> list;
/**
* 页码列表 , 即可显示的页码
*/
private List<Integer> pageButtonNumbs ;
/**
* 初始化,不考虑 列表记录数
*
* @param _currPage
* @param rowCount
*/
public Page(int _currPage, int _pageSize, int _rowCount){
this.pageSize = _pageSize;
this.rowCount = _rowCount;
// 计算总页数
this.pageCount = this.rowCount / this.pageSize;
if(this.rowCount% this.pageSize !=0 || this.rowCount == 0){
this.pageCount ++ ;
}
// 修正当前页
this.currPage = _currPage ;
if(this.currPage< 1 ){
this.currPage = 1;
}
if(this.currPage > this.pageCount ){
this.currPage = this.pageCount;
}
// 计算当前页第一条记录的索引
this.currPageFirstRowIndex = (this.currPage-1)* this.pageSize ;
// 计算并修正 前一页 和 后一页
this.prevPageNumb = this.currPage - 1;
this.nextPageNumb = this.currPage + 1;
if(this.prevPageNumb<1){
this.prevPageNumb = 1;
}
if(this.prevPageNumb>1 && this.prevPageNumb >= this.pageCount){
this.prevPageNumb = this.pageCount-1;
}
if(this.nextPageNumb <= 1 ){
this.nextPageNumb = 2;
}
if(this.nextPageNumb >1 && this.nextPageNumb > this.pageCount){
this.nextPageNumb = this.pageCount;
}
// 计算 页码按钮 列表
this.pageButtonNumbs = new ArrayList();
for( int i = this.currPage -4 ; i <= this.currPage+3 ;i++){
if(i<1 || i> this.pageCount ){
continue;
}
this.pageButtonNumbs.add(i);
}
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public int getCurrPage() {
return currPage;
}
public int getRowCount() {
return rowCount;
}
public int getPageSize() {
return pageSize;
}
public int getPageCount() {
return pageCount;
}
public int getPrevPageNumb() {
return prevPageNumb;
}
public int getNextPageNumb() {
return nextPageNumb;
}
public List<Integer> getPageButtonNumbs() {
return pageButtonNumbs;
}
public int getCurrPageFirstRowIndex() {
return currPageFirstRowIndex;
}
}
结语
本项目采用SSM框架编写Web项目,是一个进阶,从servlet进阶至SSM,本SSM整合一定要熟记于心,
SSM的重要程度是不可言喻的,到这里,我们才算是真正的步入了后台开发的门,读者一定要把SSM整合啃透,因为SSM很重要,所以说必须学会并熟练使用,动手实践,实践出真理!!!
都看到这里了,确定不点赞么~
项目源码已上传,需要的小伙伴可以去下载
- 点赞
- 收藏
- 关注作者
评论(0)