使用SSM搭建一个简单的crud项目
使用SSM完成增删查改
前端使用到的技术:ajax,json,bootstrap等
完整项目地址:点这里GitHub
这一章节主要搭建SSM的环境。
SpringMVC
SpringMVC是Web层的框架,当浏览器发送请求,前端控制器(DispatcherServlet)接收到请求后,根据处理器映射器(HandlerMapping)查找url对应的Handler,之后再调用处理器适配器(HandlerAdapter)来执行对应的Handler,这时候Handler会返回一个带有逻辑视图以及模型数据的ModelAndView给HandlerAdpater并再次返回给DispatcherServlet,前端控制器调用视图解析器对ModelAndView进行视图渲染,并且向前端相应处理结果。
1.pom.xml添加依赖(依赖先添加这么多先,有需要用到在添加)
<?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.train</groupId>
<artifactId>MySSM</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>MySSM Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<!-- 设置项目编码编码 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<!--数据库连接池-->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- JSTL实现包 -->
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-impl</artifactId>
<version>1.2.5</version>
</dependency>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- JSON -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
<!-- mybatis/spring整合包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</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-web</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<!-- 日志包-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- 分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
</dependencies>
</project>
2.在web.xml中配置前端控制器
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--启动spring容器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--字符编码过滤器-->
<filter>
<filter-name>characterEncodingFilter</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>
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- ContextLoaderListener监听器的作用就是启动Web容器时,自动装配ApplicationContext的配置信息-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- contextConfigLocation配置springmvc加载的配置文件(配置处理映射器、适配器等等)
如果不配置contextConfigLocation 默认加载的是/WEB-INF/servlet名称-servlet.xml(springmvc-servlet.xml
-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!--标记容器是否在启动的时候就加载这个servlet。-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<!-- / 表示对所有请求进行解析-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3.在resources/springmvc.xml配置注解扫描和视图解析器
视图解析器的作用:
<!--开启注解扫描, 只扫描controller注解-->
<context:component-scan base-package="org.train" use-default-filters="false">
<!--只扫描控制器-->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--配置视图解析器-->
<bean id="InternalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!--将springmvc不能处理的请求交给tomcat-->
<mvc:default-servlet-handler/>
<!--开启springmvc注解的支持
该注解会自动注册RequestMappingHandlerMapping与RquestMappingHandlerAdapter两个Bean
是@Controllers注解分发请求所必需的
-->
<mvc:annotation-driven/>
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" %>
<html>
<body>
<h2>Hello World!</h2>
<%--使用EL表达式pageContext获取当前项目名--%>
<a href="${pageContext.request.contextPath}/findBook_All">查询所有</a>
<a href="${pageContext.request.contextPath}/addBook">添加书籍</a>
<form action="" method="post">
<input type="hidden" name="_method" value="findbook">
</form>
</body>
</html>
4.2:list.jsp。看看视图解析器有没有生效,生效就会跳转到这个页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>永不放弃的心,将有贯穿黑暗的力量</h3>
</body>
</html>
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
<?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:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 扫描所有的包注解,但不包含Controller注解-->
<context:component-scan base-package="org.train">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 加载db.properties配置文件-->
<context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
<!-- 配置数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--配置和mybatis的整合
设置sqlSessionFactory的bean实现类为mybatis与spring整合jar包中的
SqlSessionFactoryBean类,在其中需要注入两个参数,一个是mybatis的
全局配置文件,一个是上面的配置的数据源bean
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载mybatis配置文件-->
<property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
<!-- 加载数据源-->
<property name="dataSource" ref="dataSource"></property>
<!-- 加载mybatis的映射文件-->
<property name="mapperLocations" value="classpath:sqlmap/*xml"></property>
</bean>
<!-- 扫描配置器,将mybatis的接口实现加入到ioc容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="org.train.ssm.dao"></property>
</bean>
</beans>
10.编写mybatis的全局配置文件SqlMapConfig.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="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!-- 配置别名
每一个在package org.train.ssm.bean中的Java Bean,在没有注解的情况下,会
使用Bean的首字母小写的非限定类名来作为他的别名
-->
<typeAliases>
<package name="org.train.ssm.bean"/>
</typeAliases>
</configuration>
注意: 有了spring托管数据源,在mybatis的全局配置中,只需要注重性能化配置
11.编写Mapper映射文件
<?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="org.train.ssm.dao.BookMapper">
<!-- resultType本应该使用Book的全类名,但是我们已经在
mybatis的全局配置文件中使用了别名
id为接口的方法名字-->
<select id="findBooks" resultType="book">
select * from books
</select>
<insert id="addBook" useGeneratedKeys="true" keyProperty="book_id">
insert into books
(book_id,book_name,book_price,book_author,book_publisher)
values
(null,#{bookName},#{bookPrice},#{bookAuthor},#{bookPublisher})
</insert>
</mapper>
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<Book> findBooks();
//添加书籍
Boolean addBook(Book book);
}
service层
@Service
public class BookService {
@Autowired
BookMapper bookMapper;
public List<Book> 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<Book> 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上看。