使用SSM完成增删查改
前端使用到的技术:ajax,json,bootstrap等
完整项目地址:点这里GitHub
项目地址,可以在线访问
这一章节主要搭建SSM的环境。
SpringMVC
SpringMVC是Web层的框架,当浏览器发送请求,前端控制器(DispatcherServlet)接收到请求后,根据处理器映射器(HandlerMapping)查找url对应的Handler,之后再调用处理器适配器(HandlerAdapter)来执行对应的Handler,这时候Handler会返回一个带有逻辑视图以及模型数据的ModelAndView给HandlerAdpater并再次返回给DispatcherServlet,前端控制器调用视图解析器对ModelAndView进行视图渲染,并且向前端相应处理结果。
1.pom.xml添加依赖(依赖先添加这么多先,有需要用到在添加)
4.0.0
org.train
MySSM
1.0-SNAPSHOT
war
MySSM Maven Webapp
http://www.example.com
UTF-8
1.8
1.8
mysql
mysql-connector-java
5.1.46
c3p0
c3p0
0.9.1.2
org.mybatis
mybatis
3.4.5
jstl
jstl
1.2
org.apache.taglibs
taglibs-standard-impl
1.2.5
junit
junit
4.12
com.fasterxml.jackson.core
jackson-annotations
2.9.0
com.fasterxml.jackson.core
jackson-core
2.9.0
com.fasterxml.jackson.core
jackson-databind
2.9.9
org.mybatis
mybatis-spring
1.3.0
org.springframework
spring-webmvc
5.1.9.RELEASE
org.springframework
spring-web
5.1.9.RELEASE
org.springframework
spring-context
5.1.9.RELEASE
org.springframework
spring-test
5.0.6.RELEASE
org.springframework
spring-tx
5.0.6.RELEASE
org.springframework
spring-jdbc
5.0.6.RELEASE
log4j
log4j
1.2.17
com.github.pagehelper
pagehelper
5.1.2
2.在web.xml中配置前端控制器
Archetype Created Web Application
contextConfigLocation
classpath:applicationContext.xml
characterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceRequestEncoding
true
forceResponseEncoding
true
characterEncodingFilter
/*
org.springframework.web.context.ContextLoaderListener
DispatcherServlet
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:springmvc.xml
1
DispatcherServlet
/
3.在resources/springmvc.xml配置注解扫描和视图解析器
视图解析器的作用:
4.检测springmvc前端控制器是否生效,配置两个页面和一个controller类
4.1:index.jsp页面,服务器启动就会加载这个页面
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
Hello World!
<%--使用EL表达式pageContext获取当前项目名--%>
查询所有
添加书籍
4.2:list.jsp。看看视图解析器有没有生效,生效就会跳转到这个页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
永不放弃的心,将有贯穿黑暗的力量
4.3:controller类的编写
package org.train.ssm.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class BookController {
@RequestMapping("/findBook_All")
public String findBook_All(){
System.out.println("hahaha");
return "list";
}
}
springmvc搭建好了
5.创建数据库和表
CREATE TABLE books(
book_id INT(11) NOT NULL AUTO_INCREMENT,
book_name VARCHAR(255) NOT NULL,
book_author VARCHAR(255) NOT NULL,
book_price FLOAT(25) NOT NULL,
book_publisher VARCHAR(255) NOT NULL,
PRIMARY KEY(book_id)
)
INSERT INTO books(
book_name,
book_author,
book_price,
book_publisher
)VALUES(
'三国演义',
'罗贯中',
99.9,
'清华大学出版社'
),
(
'红楼梦',
'曹雪芹',
88.8,
'北京大学出版社'
),
(
'西游记',
'吴承恩',
77.7,
'上海交通大学出版社'
),
(
'水浒传',
'施耐庵',
66.6,
'四川大学出版社'
);
6.创建POJO实体类
package org.train.ssm.bean;
import java.io.Serializable;
public class Book implements Serializable {
private Integer bookId;
private String bookName;
private Float bookPrice;
private String bookPublisher;
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public Float getBookPrice() {
return bookPrice;
}
public void setBookPrice(Float bookPrice) {
this.bookPrice = bookPrice;
}
public String getBookPublisher() {
return bookPublisher;
}
public void setBookPublisher(String bookPublisher) {
this.bookPublisher = bookPublisher;
}
@Override
public String toString() {
return "Book{" +
"bookId=" + bookId +
", bookName='" + bookName + '\'' +
", bookPrice=" + bookPrice +
", bookPublisher='" + bookPublisher + '\'' +
'}';
}
}
7.Spring整合Mybatis
首先创建dao层的包(放置DAO数据交互层处理类),service层的包(放置代理对象)
8.在resources创建资源文件
8.1 mybatis的全局配置文件 (SqlMapConfig.xml)
8.2 Spring的资源配置文件(applicationContext.xml)
8.3 Mapper映射文件(sqlmap/Mapper.xml)
8.4 数据库连接文件(db.properties)
8.5 日志系统配置文件(log4j.properties)
9.编写Spring的配置文件
配置数据库连接信息
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/booksdb?useUnicode=true&characterEncoding=utf8
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=12345
加载数据库连接文件"db.properties"中的数据,建立数据源
配置spring的xml文件applicationContext.xml
10.编写mybatis的全局配置文件SqlMapConfig.xml
注意: 有了spring托管数据源,在mybatis的全局配置中,只需要注重性能化配置
11.编写Mapper映射文件
insert into books
(book_id,book_name,book_price,book_author,book_publisher)
values
(null,#{bookName},#{bookPrice},#{bookAuthor},#{bookPublisher})
12.配置日志文件
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=INFO, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=INFO, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
估计很多人都没有看过日志的属性,这里简单说一下日志文件的介绍
日志输出等级有5级,当有bug发生时,你控制台没有显示异常信息,那可能就是你日志等级太高了,可以调低,说不定可以很容易的看到bug产生的原因。
debug("调试");
info("信息");
warn("警告");
error("错误");
fatal("致命错误")
等级越往下越高
如果需要了解更多的信息,可以自行百度
13.编写dao层和service层
dao层
public interface BookMapper {
//查询所有书籍
List findBooks();
//添加书籍
Boolean addBook(Book book);
}
service层
@Service
public class BookService {
@Autowired
BookMapper bookMapper;
public List findBooks(){
return bookMapper.findBooks();
}
public Boolean addBook(Book book){
return bookMapper.addBook(book);
}
}
14.改进controller层
@Controller
public class BookController {
@Autowired
BookService bookService;
@RequestMapping("/findBook_All")
public String findBook_All() throws UnsupportedEncodingException {
List books = bookService.findBooks();
for (Book book:books){
System.out.println(book);
}
return "list";
}
@RequestMapping("/addBook")
public String addBook(){
Book book = new Book(null,"天龙八部",55.5f,"清华大学出版社","金庸");
bookService.addBook(book);
return "list";
}
}
查询方法和添加方法都没有问题,到这里SSM环境就搭建完成了。
当然还有很多的细节需要改动。
我的SSM的增删查改就先完成了一部分,接下来就是前端可以在我的GitHub上看。