上一篇是一个对SpringMVC的一个测试级别的使用,也算是初级使用了,专栏至此,前面也学习了Spring框架和Mybatis框架,那这篇博客就来简单的搭建一下SSM框架。
SSM框架的搭建
环境:
JDK8,IDEA编译工具或Eclipse(用IDEA演示),Maven项目管理工具。
开发步骤:
前言:在搭建ssm框架时,要一步一步,先搭建Spring和Mybatis,然后再加上SpingMVC。我在第一次搭建ssm时费了很大的力气,就是因为对Spring框架的掌握不熟练,加上没有一个井然有序的步骤,相信你看到我写的ssm框架搭建过程你会很轻松的搭建起来。
1.新建一个带有Maven的JavaWeb项目(同上一篇博客步骤)
可以填唯一标识和组名
建成项目
2.导入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>ssm</groupId>
<artifactId>ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>ssm 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.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- 第一部分:Spring 配置-->
<!-- Spring core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.1.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.1.4.RELEASE</version>
</dependency>
<!-- Spring DAO -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.1.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
<!-- Spring mvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.4.RELEASE</version>
</dependency>
<!-- 第二部分:Servlet web -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
<!-- 第三部分:数据库和mybatis -->
<!-- 数据库 -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- MyBatis -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
<!-- mybatis-spring整合包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- 第四部分:日志 -->
<!-- 实现slf4j接口并整合 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.1</version>
</dependency>
<!--<dependency>-->
<!--<groupId>com.fasterxml.jackson.core</groupId>-->
<!--<artifactId>jackson-core</artifactId>-->
<!--<version>2.7.3</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>com.fasterxml.jackson.core</groupId>-->
<!--<artifactId>jackson-databind</artifactId>-->
<!--<version>2.7.3</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>com.fasterxml.jackson.core</groupId>-->
<!--<artifactId>jackson-annotations</artifactId>-->
<!--<version>2.7.3</version>-->
<!--</dependency>-->
</dependencies>
<build>
<finalName>ssm</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
3.建立MVC的目录结构如下
4.整合Spring和Mybatis
(1)新建数据库数据表
-- MySQL dump 10.13 Distrib 8.0.13, for Win64 (x86_64)
--
-- Host: 127.0.0.1 Database: mybatis
-- ------------------------------------------------------
-- Server version 8.0.13
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
SET NAMES utf8 ;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `user`
--
DROP TABLE IF EXISTS `user`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
SET character_set_client = utf8mb4 ;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL COMMENT '用户名称',
`birthday` date DEFAULT NULL COMMENT '生日',
`sex` char(1) DEFAULT NULL COMMENT '性别',
`address` varchar(256) DEFAULT NULL COMMENT '地址',
`uuid1` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=37 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `user`
--
LOCK TABLES `user` WRITE;
/*!40000 ALTER TABLE `user` DISABLE KEYS */;
INSERT INTO `user` VALUES (1,'王五',NULL,'2',NULL,NULL),(10,'张三','2014-07-10','1','北京市',NULL),(16,'张小明',NULL,'1','河南郑州',NULL),(24,'张三丰',NULL,'1','河南郑州',NULL),(25,'陈小明',NULL,'1','河南郑州',NULL),(26,'王五',NULL,NULL,NULL,NULL),(29,'张巅峰','1970-01-01','m','xxxx',NULL),(31,'张无极','1970-01-01','w','aaaaa',NULL),(32,'张无极','1970-01-01','w','aaaaa',NULL),(33,'张无极','1970-01-01','w','aaaaa',NULL),(34,'张无极','1970-01-01','w','aaaaa',NULL),(35,'张无极','1970-01-01','w','aaaaa',NULL),(36,'李太白','1970-01-01','m','aass','8dbcc2ce-2707-11e9-b029-54e1ada2cba5');
(2)配置数据库配置文件db.properties
jdbc.driverClass = com.mysql.cj.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/Mybatis?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true
jdbc.user = root
jdbc.password = wrial.qq.com
(3)配置日志打印
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
(4)配置Sping配置文件applicationContext.xml,并引入SpringMybatis的配置文件
<?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-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<!-- 使用annotation 自动注册bean,并保证@Required,@Autowired的属性被注入 -->
<context:component-scan base-package="com">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<import resource="SpringMybatis.xml"/>
</beans>
(5)配置Spring代理Mybatis配置文件SpringMybatis.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" >
<!--配置jdbc c3p0 -->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 结合Spring和Mybatis -->
<bean id = "sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--<property name="configLocation" value="SqlMapConfig.xml"/>-->
<property name="typeAliasesPackage" value="com.pojo"/>
<!-- 自动扫描mapping.xml文件 -->
<property name = "mapperLocations" value="classpath:mapper/*.xml" />
</bean>
<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name = "basePackage" value="com.dao" />
<property name = "sqlSessionFactoryBeanName" value = "sqlSessionFactory" />
</bean>
<!-- 定义事务 -->
<bean id = "transactionManager"
class = "org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name = "dataSource" ref = "dataSource" />
</bean>
<!-- 使用注解定义事务 -->
<tx:annotation-driven transaction-manager = "transactionManager" />
</beans>
(6)配置Mybatis核心配置文件SqlMapConfig,因为在Spring可以和mybatis很好的融合,所以SqlMapConfig在目前阶段可为空,但要有文件头.dtd
<?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>
</configuration>
4.自己写一个测试的pojo,dao,mapper或者用逆向工程生成(我测试使用的是Mybatis的数据表,没有新建)
pojo
package com.pojo;
import java.util.Date;
public class User {
private Integer id;
private String username;// 用户姓名
private String sex;// 性别
private Date birthday;// 生日
private String address;// 地址
private String uuid1;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address="
+ address + ", uuid1=" + uuid1 + "]";
}
public String getUuid1() {
return uuid1;
}
public void setUuid1(String uuid1) {
this.uuid1 = uuid1;
}
}
dao
package com.dao;
import com.pojo.User;
import java.util.List;
public interface UserMapper {
User getUserById(Integer id);
List<User> getUserByLikeIt(String word);
}
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">
<!--动态代理的开发规则-->
<!--1.namespace 必须是接口全路径名-->
<!--2.xml的id要和方法名一致-->
<!--3.入参一致和parameterType一致-->
<!--4.返回值一致和resultType一致-->
<mapper namespace="com.dao.UserMapper">
<select id="getUserById" parameterType="int" resultType="com.pojo.User">
select *
from mybatis.user
where id = #{id}
</select>
<!--#{} 传入参数-->
<!-- ${} 字符串拼接 如果入参是普通属性只能写value,pojo的话就写pojo-->
<select id="getUserByLikeIt" parameterType="String" resultType="com.pojo.User">
select username
from user
where username like '%${value}%'
</select>
</mapper>
service
package com.service;
import com.pojo.User;
import java.util.List;
public interface UserService {
User SelectUserById();
}
serviceImpl
package com.service;
import com.dao.UserMapper;
import com.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service(value = "userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User SelectUserById() {
User user = userMapper.getUserById(29);
return user;
}
}
5.整合SpringMVC到项目
(1)application-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:p="http://www.springframework.org/schema/p"
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-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!--设置包扫描-->
<context:component-scan base-package="com.controller"/>
<!--配置注解器驱动器,Spring为简化我们手动配置映射器和适配器,也支持json的数据响应-->
<mvc:annotation-driven/>
<!--配置视图解释器,省去写路径的步骤直接写jsp的视图名-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
(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 xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
<!-- Spring核心配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:Spring/applicationContext.xml</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>
<!-- 编码过滤器 -->
<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>
<!-- spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 防止spring内存溢出监听器,比如quartz -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- spring mvc servlet-->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--加载applicationContext-mvc-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:Spring/applicationContext-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!-- 此处也可以配置成 *.action 形式 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
<!-- session配置 -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
(3)编写controller
package com.controller;
import com.pojo.User;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import java.util.List;
@Controller("userController")
public class UserController {
@Resource(name = "userService")
private UserService userService;
@RequestMapping("findUser")
public ModelAndView userList() {
User user = userService.SelectUserById();
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("user1", user);
modelAndView.setViewName("findUser");
System.out.println("controller");
System.out.println(user.toString());
return modelAndView;
}
}
(5)编写index.jsp和WEB-INF/jsp/findUser.jsp
index.jsp
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
findUser.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/2/13
Time: 23:33
To change this template use File | Settings | File Templates.
--%>
<%@ page isELIgnored="false" contentType="text/html;charset=UTF-8" language="java" import="com.pojo.User" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>FindUser!</h1>
<tr>
<td>${user1.id }</td>
<td>${user1.username}</td>
<td>${user1.birthday}</td>
<%--<td><fmt:formatDate value="${user.birthday}" pattern="yyyy-MM-dd HH:mm:ss"/></td>--%>
<td>${user1.sex }</td>
<td>${user1.address}</td>
<td>${user1.toString()}</td>
</tr>
</body>
</html>
至此,就简单的搭建了ssm项目了
测试结果
看到成功的页面有没有很高兴呢,反正我弄出来的时候贼高兴,因为我搭建的时候出了好多bug,一个一个往过踩坑哈哈哈,这次就到这里吧,SpringMVC的详细配置下次再讲吧!
今天被狗咬伤了,好难过,但是这还是不能阻挡我的脚步哈哈!