优雅地搭建整合ssm项目
spring + spring mvc + mybatis 三大框架建议观看 黑马程序员出品的
Springmvc+Mybatis由浅入深全套视频教程
Spring框架2016版视频
观看顺序 ,我个人 推荐 mybatis --> spring mvc --> spring (因为个人做了很长一段时间 数据库开发,所以挑选 mybatis 上手较快,如果有 struts2 经验的也可以从 spring mvc 开始看起)
搭建完成整体效果图:
然后接下来就开始从0搭建一个完整的 ssm 项目了
项目构成及环境: 本项目采用 maven 构建 环境要求: IDEA Version: 2017.2.5 Tomcat Version: 8.5.x > 用到的技术 IOC 容器 spring, 前端web控制层 springmvc, 持久层: mybatis
下面开始 step by step:
一、 配置整合 spring 与 mybatis
1、 配置 项目对象管理文件
<?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>com.ghc</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> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!-- spring版本号 --> <spring.version>4.3.5.RELEASE</spring.version> <!-- mybatis版本号 --> <mybatis.version>3.4.1</mybatis.version> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <!-- java ee --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <!-- 单元测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!-- 实现slf4j接口并整合 --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.2</version> </dependency> <!-- JSON --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.7</version> </dependency> <!-- 数据库驱动包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.41</version> <scope>runtime</scope> </dependency> <!-- 数据库c3p0连接池 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring整合包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</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.0.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.7.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.20.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.0</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>
2、在 web.xml 文件中配置spring上下文环境以及springmvc 中央控制器 (这步骤中的 springmvc 中央控制器部分本应该放到 后文中的 springmvc 整合中去的,其实 springmvc 属于spring 的一部分,所以不需要 专门的整合包,浑然天成,这也是 spring 迷人的地方,几乎所有层都提供了对应的解决方案 springmvc 替换struts2 ,JdbcTemplate可以做持久层)。
其中监听器的配置,让 ServletContext 这个对象在 web 服务器(本项目采用tomcat)在启动时就读取监听所对应配置文件里的所有对象注入进来
<!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://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>Archetype Created Web Application</display-name> <context-param> <param-name>contextConfigLocation</param-name> <!--此处采用通配符读取spring与mybatis整合文件以及 springmvc 的配置文件--> <param-value>classpath:/config/spring-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--添加编码过滤器--> <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> <!--配置springmvc最重要的前端中央控制器 DispatcherServlet--> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--配置springmvc 需要加载的配置文件--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/config/springmvc/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!--此处的url模式可以是 *.do 我写成 / 是为了做 RESTful风格的url编写--> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
3、配置一下 spring mybatis 整合配置文件,数据源,数据库连接池,事务等
从此处开始,都展示正常项目开发过程使用方法,一般注解居多,在最后会附上配置文件方法,最好注解跟配置文件同时掌握,方便使用
配置db.properties 文件方便后期维护,注意这个 文件中的 数据库的密码 应该修改为自己数据库的密码,当然也可以切换数据库为其他的 Oracle , SQL Server 等
只是这时候得下载相应驱动了
jdbc.driver=com.mysql.jdbc.Driver #数据库地址 jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf8 #用户名 jdbc.username=root #密码 jdbc.password=Mede645 #最大连接数 c3p0.maxPoolSize=30 #最小连接数 c3p0.minPoolSize=10 #关闭连接后不自动commit c3p0.autoCommitOnClose=false #获取连接超时时间 c3p0.checkoutTimeout=10000 #当获取连接失败重试次数 c3p0.acquireRetryAttempts=2
下面文件里的 数据库连接池 c3p0 也可以使用 druid ,dbcp 等 第三方数据库连接池,具体配置方法,请另行搜索参考
<?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: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"> <!--为了方便配置把数据库驱动以及连接账号密码等信息都单独配置在db.properties 文件中便于修改--> <context:property-placeholder location="classpath:/config/db.properties"/> <!--本项目采用 c3p0 数据库连接池,也可以切换为druid,dbcp 等第三方数据库连接池--> <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="${c3p0.maxPoolSize}"/> <property name="minPoolSize" value="${c3p0.minPoolSize}"/> <property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/> <property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/> <property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/> </bean> <!-- 配置SqlSessionFactory对象 并做别名,以及dao层接口映射文件的配置--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="dataSource"/> <!-- 扫描model包 使用别名 --> <property name="typeAliasesPackage" value="com.ghc.model"/> <!-- 扫描sql配置文件:mapper需要的xml文件 --> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!-- 配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 注入sqlSessionFactory --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!-- 给出需要扫描Dao接口包 --> <property name="basePackage" value="com.ghc.dao"/> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="dataSource"/> </bean> <!--开启注解扫描,扫描service包里的注解--> <context:component-scan base-package="com.ghc.service"/> <!-- 配置基于注解的声明式事务 --> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
由于刚刚开始熟悉,所以建议每一层整合完进行一次单独测试
接下来要写一个简单的 dao 层接口 IUserDao (用 mybatis 的 Mapper 接口方法) 来测试一下整合是否没有问题了
1、 定义 pojo User 类
package com.ghc.model.pojo;
import java.util.Date;
public class User {
private int id;
private String email;
private String password;
private String userName;
private String role;
private int status;
private Date regTime;
private String regIp;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Date getRegTime() {
return regTime;
}
public void setRegTime(Date regTime) {
this.regTime = regTime;
}
public String getRegIp() {
return regIp;
}
public void setRegIp(String regIp) {
this.regIp = regIp;
}
}
2、 在 mapper 文件夹下 编写 User.Mapper.xml 了 (这个文件随着业务的完善,会进行一定程度的修改的), 这个 文件在 上面的 spring-mybatis.xml 中配置了 包扫描
<?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="com.ghc.dao.IUserDao"> <select id="selectUser" parameterType="int" resultType="user"> SELECT * FROM user WHERE id=#{id}; </select> </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="com.ghc.dao.IUserDao"> <!-- <select id="selectUser" parameterType="int" resultType="user"> SELECT * FROM user WHERE id=#{id}; </select>--> <select id="selectUser" parameterType="user" resultType="user"> SELECT * FROM user <include refid="where_username_password"/> </select> <sql id="where_username_password"> <choose> <when test="userName!=null and userName!=''and password!=null and password!=''"> <where> username=#{userName} and password=#{password} </where> </when> <otherwise> <where> 1=0 </where> </otherwise> </choose> </sql> </mapper>
3、 根据 mapper 文件来写一个 IUserDao 接口
package com.ghc.dao;
import com.ghc.model.pojo.User;
public interface IUserDao {
User selectUser(int id);
}
4、 编写junit 单元测试来测试 dao 层接口是否能用
package com.ghc.dao;
import com.ghc.model.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:config/spring-mybatis.xml"})
public class IUserDaoTest {
@Autowired
private SqlSessionFactory sqlSessionFactory;
@Test
public void testIUserDao(){
SqlSession sqlSession = sqlSessionFactory.openSession();
IUserDao iUserDao = sqlSession.getMapper(IUserDao.class);
User user = iUserDao.selectUser(2);
System.out.println("user name: "+user.getUserName());
}
}
至此: 项目整合 mybatis 完成 结构 与 测试结果 如下图:
二 、配置 整合 spring 与 spring mvc
我打算写个 登录验证来测试整合
先写一个 service 层 IUserService 接口
package com.ghc.service; import com.ghc.model.pojo.User; public interface IUserService { boolean invalidUser(User user); }
然后写这个接口的实现类
package com.ghc.service.impl; import com.ghc.dao.IUserDao; import com.ghc.model.pojo.User; import com.ghc.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service(value="userService") public class UserService implements IUserService { @Autowired private IUserDao iUserDao; @Override public boolean invalidUser(User user) { return iUserDao.selectUser(user)!=null; } }
controller 层
下面这两个,需要学习 springmvc 的 参数绑定,处理器映射才能理解使用
package com.ghc.controller; public class LoginCommand { private String userName; private String password; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } }
package com.ghc.controller; import com.ghc.model.pojo.User; import com.ghc.service.impl.UserService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.util.Date; @RestController public class LoginController{ @Autowired private UserService userService; @RequestMapping(value = "/index.html") public String loginPage(){ return "login"; } @RequestMapping(value = "/loginCheck.html") public ModelAndView loginCheck(HttpServletRequest request, LoginCommand loginCommand){ User user = new User(); user.setUserName(loginCommand.getUserName()); user.setPassword(loginCommand.getPassword()); boolean isValidUser = userService.invalidUser(user); if (!isValidUser) { return new ModelAndView("login", "error", "用户名或密码错误。"); } else { request.getSession().setAttribute("user", user); System.out.println("user name: "+user.getUserName()); return new ModelAndView("main"); } } }
jsp 页面 引用 springmvc 参数绑定和 JSTL 标签来获取值 ( 但估计以后的技术是前后端分离的技术),springmvc 提倡 jsp 页面仅做数据展示!!!!!!!
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head> <title>登录页面</title> </head> <body> <c:if test="${!empty error}"> <font color="red"><c:out value="${error}" /></font> </c:if> <form action="<c:url value="loginCheck.html"/>" method="post"> 用户名: <input type="text" name="userName"> <br> 密 码: <input type="password" name="password"> <br> <input type="submit" value="登录" /> <input type="reset" value="重置" /> </form> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>成功页面</title> </head> <body> ${user.userName},欢迎您进入; </body> </html>
最后配置一波 spring-mvc.xml 整合 spring-mvc 到 spring 里
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 扫描web包,应用Spring的注解 --> <context:component-scan base-package="com.ghc.controller"/> <!-- 配置视图解析器,将ModelAndView及字符串解析为具体的页面 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:viewClass="org.springframework.web.servlet.view.JstlView" p:prefix="/WEB-INF/views/" p:suffix=".jsp" /> </beans>
最后 部署工程到 tomcat 服务器上,采用 war 包
然后打开 浏览器,输入 url (http://localhost:8080/index.html)
正常访问
这个账号密码 均在 数据库的 用户表 user 表中
root
root
输入正确后进入成功页面:
否则在原页面跑出提示信息:
在此处提上 日志信息所需配置文件:
<?xml version="1.0" encoding="UTF-8"?> <configuration debug="true"> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <root level="debug"> <appender-ref ref="STDOUT"/> </root> </configuration>
use ssm; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户ID', `email` varchar(255) NOT NULL COMMENT '用户邮箱', `password` varchar(255) NOT NULL COMMENT '用户密码', `username` varchar(255) NOT NULL COMMENT '用户昵称', `role` varchar(255) NOT NULL COMMENT '用户身份', `status` int(1) NOT NULL COMMENT '用户状态', `regTime` datetime NOT NULL COMMENT '注册时间', `regIp` varchar(255) NOT NULL COMMENT '注册IP', PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; INSERT INTO `user` VALUES ('1', 'xxx', 'xxxxx', 'xxxxx', 'root', '0', '2017-03-28 09:40:31', '127.0.0.1'); SET FOREIGN_KEY_CHECKS=1; insert into ssm.user(email,password,username,role,status,regTime,regIp) values('demo@gmail.com','root','root','root',1,sysdate(),'192.168.0.1')
到此,spring mvc 与 spring 的整合已经通过一个 登录验证小功能 完成
至此, ssm 的最优雅的整合也算是告一段落了。个人认为可以作为以后搭建ssm 项目的模板了。
接下来的任务是花时间钻研 spring mvc 以及 Angular JS 这些表现层的东西了 (实话,这个地方是我的薄弱环节)
不求页面多好看,但求功能全部优雅实现,还能看的下去。。。。。。