最简单的SSM框架整合_maven版
笔者在做java web项目时,用 SSM+maven+easyui/bootstarp,接着上一个博文,我们记录的是SSM框架整合之java web普通版,而这篇博文中,我们做的是maven版本,使用maven来管理项目需要的jar包。不需要自己去下载了。万丈高楼平地起,这里是写的一个maven版的SSM整合。
在这里记录一下,希望有疑惑的人能找到答案。
项目总览
项目名称:SSM_Zh_Maven
数据库:booksystem
访问地址:http://localhost:8080/SSM_Zh_Maven/
源码地址:github
运行环境:eclipse+mysql+ssm+tomcat+bootstarp
新建maven工程
然后填写
组名:com.zout
项目名:SSM_Zh_Maven
然后完成。
最后如图:
记得修改项目的默认环境,配置成你自己的JDK版本啊,tomcat版本。
建book表语句如下:
CREATE TABLE `book` (
`book_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '图书ID',
`name` varchar(100) NOT NULL COMMENT '图书名称',
`number` int(11) NOT NULL COMMENT '图书数量',
`detail` varchar(200) NOT NULL COMMENT '图书描述',
PRIMARY KEY (`book_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='图书表'
记得准备数据,所以就先添加——在数据库的book表里面添加数据,可以手动也可以使用java代码完成。
一般的ssm流程:
数据库的准备
pom文件
jdbc.properties
mybatis-config.xml
spring-mybatis
log4j.properties
实体类User
Dao接口UserDao
service接口UserService
以及它的实现类UserServiceImpl
映射mybatis-user.xml
spring-mvc.xml
配置web.xml
jsp页面
建控制器 xxxController
第一步:pom.xml配置
添加Spring、Spring MVC、Mybatis的依赖文件
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.zoutgroupId>
<artifactId>SSM_Zh_MavenartifactId>
<packaging>warpackaging>
<version>0.0.1-SNAPSHOTversion>
<name>SSM_Zh_Maven Maven Webappname>
<url>http://maven.apache.orgurl>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-classicartifactId>
<version>1.1.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.37version>
<scope>runtimescope>
dependency>
<dependency>
<groupId>c3p0groupId>
<artifactId>c3p0artifactId>
<version>0.9.1.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.3.0version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.2.3version>
dependency>
<dependency>
<groupId>taglibsgroupId>
<artifactId>standardartifactId>
<version>1.1.2version>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.5.4version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>4.1.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>4.1.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>4.1.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>4.1.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>4.1.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>4.1.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>4.1.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>4.1.7.RELEASEversion>
dependency>
dependencies>
<build>
<finalName>SSM_Zh_MavenfinalName>
<plugins>
<plugin>
<groupId>org.apache.tomcat.mavengroupId>
<artifactId>maven-compiler-pluginartifactId>
<configuration>
<source>1.8source>
<target>1.8target>
configuration>
plugin>
plugins>
build>
project>
第二步:jdbc.properties配置
添加数据库配置文件
在resources目录下新建:数据库配置文件jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/booksystem?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
第三步:mybatis-config.xml配置
添加mybatis配置文件
在resources目录下新建文件:mybatis-config.xml
<configuration>
<settings>
<setting name="useGeneratedKeys" value="true" />
<setting name="useColumnLabel" value="true" />
<setting name="mapUnderscoreToCamelCase" value="true" />
settings>
configuration>
第四步:Spring.xml配置:
添加Spring配置文件
在resources目录下新建文件:(这里可以配置一个总的也可以分开配置)
│ └── spring
│ ├── spring-dao.xml
│ ├── spring-service.xml
│ └── spring-web.xml
1.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
http://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" />
<property name="typeAliasesPackage" value="com.zout.entity" />
<property name="mapperLocations" value="classpath:mapper/*.xml" />
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
<property name="basePackage" value="com.zout.dao" />
bean>
beans>
2.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"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.zout.service" />
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
bean>
<tx:annotation-driven transaction-manager="transactionManager" />
beans>
3.Spring-web.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: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
http://www.springframework.org/schema/mvc/spring-mvc-3.0.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.zout.web" />
beans>
第五步:logback日志配置文件(logback配置比log4j要简单点,功能类似)
添加日志配置文件
在resources目录下新建文件:
logback.xml
<configuration debug="true">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%npattern>
encoder>
appender>
<root level="debug">
<appender-ref ref="STDOUT" />
root>
configuration>
到这里SSM整合基本上配置xml文件都差不多了,接下来开始写跟业务有关的东西。
第六步:创建实体类entity
Javabean实体类
在java Resources 下新建com.xxx.xxx包,在新建java文件。
如下文件:
新建com.zout.entity
然后新建java文件:Book.java
package com.zout.entity;
/**
*@class_name:Book
*@param:book的javabean实体类
*@return:
*@author:Zoutao
*@createtime:2018年2月10日
*/
public class Book {
private long bookId; //书id
private String name; //书名
private int number; //数量
private String detail; //详情
public long getBookId() {
return bookId;
}
public void setBookId(long bookId) {
this.bookId = bookId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
@Override
public String toString() {
return "Book [bookId=" + bookId + ", name=" + name + ", number=" + number + ", detail=" + detail + "]";
}
}
第七步:创建DAO层
数据对象访问接口
新建com.zout.dao
然后新建java文件:BookDao.java(注意,这是一个接口文件)
package com.zout.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.zout.entity.Book;
/**
*@class_name:BookDao
*@param: book的dao层——数据访问对象
*@return:
*@author:Zoutao
*@createtime:2018年2月10日
*/
public interface BookDao {
Book queryById(long id);
//使用mybatis的注解设置参数
List<Book> queryAll(@Param("offset") int offset, @Param("limit") int limit);
int addBook(Book book);
int updateBook(Book book);
int deleteBookById(long id);
}
最后效果如图:
BookDao.java、Book.java
第八步:创建mybatis mapper文件
映射文件
在resources下新建一个mapper文件夹,然在旗下又创建xml:
resources/mapper/BookMapper.xml
在mapper文件中需要用到第六步的内容
<mapper namespace="com.zout.dao.BookDao">
<select id="queryById" resultType="Book" parameterType="long">
SELECT
book_id,
name,
number,
detail
FROM
book
WHERE
book_id = #{bookId}
select>
<select id="queryAll" resultType="Book">
SELECT
book_id,
name,
number,
detail
FROM
book
ORDER BY
book_id
LIMIT #{offset}, #{limit}
select>
<update id="updateBook" parameterType="Book">
UPDATE book
SET NAME = #{name},
NUMBER = #{number},
detail = #{detail}
WHERE
book_id = #{bookId}
AND number > 0
update>
<insert id="addBook">
INSERT INTO book(`book_id`, `name`, `number`,`detail`)
VALUES(#{bookId}, #{name}, #{number}, #{detail})
insert>
<delete id="deleteBookById">
DELETE FROM book WHERE book_id = #{bookId}
delete>
mapper>
第九步:创建service层
业务逻辑接口
在java Resources下新建service包,然后再建:
BookService.java(接口)
package com.zout.service;
import java.util.List;
import com.zout.entity.Book;
/**
*@class_name:BookService
*@param: 逻辑业务处理接口
*@return:
*@author:Zoutao
*@createtime:2018年2月10日
*/
public interface BookService {
Book getById(long bookId);
List<Book> getList(int start, int pageNum);
int addBook(Book book);
int updateBook(Book book);
int deleteBookById(long id);
}
第十步:创建service 实现类impl层
Service接口的实现类
在service包下,然后再建impl包,然后再建其实现类:
BookServiceImpl.java
package com.zout.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zout.dao.BookDao;
import com.zout.entity.Book;
import com.zout.service.BookService;
/**
*@class_name:BookServiceImpl
*@param:业务逻辑接口的实现类
*@return:
*@author:Zoutao
*@createtime:2018年2月10日
*/
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
@Override
public Book getById(long bookId) {
return bookDao.queryById(bookId);
}
@Override
public List<Book> getList(int start, int pageNum) {
return bookDao.queryAll(start, pageNum);
}
@Override
public int addBook(Book book) {
return bookDao.addBook(book);
}
@Override
public int updateBook(Book book) {
return bookDao.updateBook(book);
}
@Override
public int deleteBookById(long id) {
return bookDao.deleteBookById(id);
}
}
第十一步:创建controller层
业务控制类
(这里我建的包名为web了,实际上写controller更专业)
在java Resources下新建web包,然后再建
BookController.java
package com.zout.web;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zout.entity.Book;
import com.zout.service.BookService;
/**
* @class_name:BookController
* @param: 业务控制层-接收页面请求,处理,返回
* @return:
* @author:Zoutao
* @createtime:2018年2月10日
*/
@Controller
@RequestMapping("/book")
public class BookController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private BookService bookService;
@RequestMapping(value = "/list", method = RequestMethod.GET)
private String list(Model model) {
List<Book> list = bookService.getList(0, 1000);
model.addAttribute("list", list);
return "list";// WEB-INF/jsp/"list".jsp
}
@RequestMapping(value = "/detail/{bookId}", method = RequestMethod.GET)
private String detail(@PathVariable("bookId") Long bookId, Model model) {
Book book = bookService.getById(bookId);
model.addAttribute("book", book);
return "detail";
}
@RequestMapping(value = "/add", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
@ResponseBody
private String add(Book book) {
Book hasBook = bookService.getById(book.getBookId());
int i = -2;
if (hasBook == null) {
i = bookService.addBook(book);
}
return i > 0 ? "success" : "error";
}
@RequestMapping(value = "/del/{bookId}", method = RequestMethod.GET)
@ResponseBody
private String deleteBookById(@PathVariable("bookId") Long id) {
int i = bookService.deleteBookById(id);
return i > 0 ? "success" : "error";
}
}
第十二步:创建前端显示jsp页面
前端页面
在webapp下,新建index.jsp:
1.index.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<% String appPath = request.getContextPath(); %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>图书管理系统-首页title>
head>
<body>
<h2>SSM_BookSystem --- 整合示例h2>
简单的查询、删除等基础功能
<br /> 日期:2018-02-10 22:30:51
<br /> 作者:Zoutao
<br /> 博客:
<a href="http://blog.csdn.net/ITBigGod" target="_blank">柒晓白a>
<br />
<br />
<br />
<br /> 图书管理系统:
<a href="<%=appPath%>/book/list">点击前往a>
body>
html>
在这个SSM整合的maven版本里面,顺便提一下前端框架bootstarp,用来美化前端也就,在本文中顺带写一些。
引用bootstarp前端框架
这里用它官网的CDN服务器,远程引入,不需要下载bootstarp的源文件。
在WEB-INF下新建jsp文件夹,然后新建jsp页面:
2.list.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<% String appPath = request.getContextPath(); %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图书列表页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 clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
Zoutao <small>图书管理系统——ssm整合示例small>
h1>
div>
div>
div>
<div class="row clearfix">
<div class="col-md-12 column">
<ul class="nav nav-tabs">
<li class="active"><a href="<%=appPath%>/book/list">首页a>li>
<li><a href="<%=appPath%>/book/detail/1000">图书具体信息a>li>
<li><a href="<%=appPath%>/add.jsp">添加图书信息a>li>
<li class="disabled"><a href="#">信息a>li>
ul>
div>
div>
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
图书列表 <small>显示当前图书库存信息small>
h1>
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>
tr>
thead>
<tbody>
<c:forEach var="book" items="${requestScope.get('list')}"
varStatus="status">
<tr>
<td>${book.bookId}td>
<td>${book.name}td>
<td>${book.number}td>
<td><a href="<%=appPath%>/book/detail/${book.bookId}">详情a>
| <a href="<%=appPath%>/book/del/${book.bookId}">删除a>td>
tr>
c:forEach>
tbody>
table>
div>
div>
div>
<script src="https://code.jquery.com/jquery.js">script>
body>
html>
在建一个detail.jsp页面:
3.detail.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String appPath = request.getContextPath();
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>图书详情页title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery.js">script>
<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>
Zoutao <small>图书管理系统——ssm整合示例small>
h1>
div>
div>
div>
<div class="row clearfix">
<div class="col-md-12 column">
<ul class="nav nav-tabs">
<li><a href="<%=appPath%>/book/list">首页a>li>
<li class="active"><a href="<%=appPath%>/book/detail/1003">图书具体信息a>li>
<li class="disabled"><a href="#">信息a>li>
ul>
div>
div>
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
图书详情 <small>显示当前图书详细信息small>
h1>
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>
tr>
thead>
<tbody>
<tr>
<td>${requestScope.get('book').bookId}td>
<td>${requestScope.get('book').name}td>
<td>${requestScope.get('book').number}td>
tr>
tbody>
table>
div>
div>
<div class="row clearfix">
<div class="col-md-12 column">
<p>
<em>《${requestScope.get('book').name}》em>
${requestScope.get('book').detail}
p>
div>
div>
div>
body>
html>
第十三步:配置web.Xml文件
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0" metadata-complete="true">
<display-name>Archetype Created Web Applicationdisplay-name>
<servlet>
<servlet-name>seckill-dispatcherservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring/spring-*.xmlparam-value>
init-param>
servlet>
<servlet-mapping>
<servlet-name>seckill-dispatcherservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<description>字符集过滤器description>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<description>字符集编码description>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListenerlistener-class>
listener>
<session-config>
<session-timeout>60session-timeout>
session-config>
<welcome-file-list>
<welcome-file>index.jspwelcome-file>
welcome-file-list>
web-app>
总结:
1.(javabean)实体类的书写对应这数据库里面的表字段属性,最后生成setter+getter方法,还有重定向的.tostring方法;
以后的业务添加中,每多一张表就多一个实体类,多一个dao和mapper。
2. dao层是数据访问对象的接口,也就是数据接入的地方。
声明数据库的操作方法,增删查改的方法声明;
3. Service层是通过dao层接口来对业务逻辑的实现。
也是定义的声明数据库的操作方法,增删查改的方法声明;
4.impl层,这个是service的实现类,一般来说,dao层也会有一个实现类,写的是对service层方法的具体实现;
You got a dream, you gotta protect it.
如果你有梦想的话,就要去捍卫它 。 ——《当幸福来敲门》