基于Maven的SSM框架搭建
Maven + Spring + Spring MVC + Mybatis + MySQL整合SSM框架
1.数据库准备
本文主要想实现SSM框架的搭建,并基于该框架实现简单的登录功能,那么先新建一张user_t表:
DROP TABLE IF EXISTS `user_t`; CREATE TABLE `user_t` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `user_name` VARCHAR(40) NOT NULL, `password` VARCHAR(255) NOT NULL, `age` INT(4) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
然后再插入一条数据:
INSERT INTO `user_t`(`id`,`user_name`,`password`,`age`) VALUES (1,'测试','sfasgfaf',24);
为了简单起见,密码暂时先用明文,后面框架搭建成功后在改为MD5加密。
那么查看下user_login表的内容:
mysql> select * from user_t; +----+-----------+----------+-----+ | id | user_name | password | age | +----+-----------+----------+-----+ | 1 | 测试 | sfasgfaf | 24 | +----+-----------+----------+-----+ 1 row in set (0.00 sec)
2.Maven Web项目创建
新建一个Maven Project,然后输入Group Id和Artifact Id,点击Finish就完成了。
3.开始整合Spring Spring MVC Mybatis
用过Maven的都知道,有了Maven就没必要去网上下载一对jar文件然后自己去管理,直接在pom.xml中添加依赖就可以:
<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.0</modelVersion> <groupId>20171117</groupId> <artifactId>SSM</artifactId> <version>0.0.1-SNAPSHOT</version> <name>SSM Maven Webapp</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.2.RELEASE</version> <relativePath></relativePath> </parent> <properties> <!-- spring版本号 --> <spring.version>4.0.2.RELEASE</spring.version> <!-- mybatis版本号 --> <mybatis.version>3.2.6</mybatis.version> <!-- log4j日志文件管理包版本 --> <slf4j.version>1.7.7</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging --> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <!-- 表示开发的时候引入,发布的时候不会加载此包 --> <scope>test</scope> </dependency> <!-- spring核心包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</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-oxm</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-jdbc</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-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</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.2.2</version> </dependency> <!-- 导入java ee jar 包 --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <!-- 导入Mysql数据库链接jar包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.30</version> </dependency> <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <!-- JSTL标签类 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- 日志文件管理包 --> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <!-- 格式化对象,方便输出日志 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <!-- 映入JSON --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- 上传组件包 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> </dependencies> <build> <finalName>Test</finalName> </build> </project>
3.1Spring和Mybatis的整合
3.1.1创建数据库属性文件jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://10.0.20.252:3306/mybatis
username=root
password=Free-Wi11
initialSize=0
maxActive=20
maxIdle=20
minIdle=1
maxWait=60000
3.1.2创建spring-mybatis配置文件
这个文件就是用来完成spring和mybatis的整合的。这里面也没有多少行配置,主要就是自动扫描,自动注入,配置数据库,详细配置如下:
spring-mybatis.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-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="com.cn.hnust" /> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:com/cn/hnust/mapping/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.cn.hnust.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans>
3.1.3日志的输出配置
为了方便调试,一般都会使用日志来输出信息,Log4j是Apache的一个开放源代码项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台,文件,GUI组件,甚至是套接口服务器,NT的事件记录器,UNIX Syslog守护进程等;我们也可以控制每一条日志的输出格式;通过定义每一条日志信息的级别,我们能够更加细致的控制日志的生成过程。
Log4j的配置很简单,而且也是通用的,下面给出一个基本的配置,换到其他项目中也无需做多大的调整。
下面给出配置文件目录:
log4j.properties
log4j.rootLogger=INFO,Console,File
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
log4j.appender.File = org.apache.log4j.RollingFileAppender
log4j.appender.File.File = logs/ssm.log
log4j.appender.File.MaxFileSize = 10MB
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
3.1.4JUnit测试
经过以上步骤,我们已经完成了Spring和Mybatis的整合,这样就可以编写一段测试代码来检验Spring和Mybatis是否整合成功了。
3.1.4.1创建实体类User
User.java
package com.cn.hnust.pojo; public class User { private int id; private String user_name; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUser_name() { return user_name; } public void setUser_name(String user_name) { this.user_name = user_name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
3.1.4.2创建Dao接口,UserDao
UserDao.java
package com.cn.hnust.dao; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository; import com.cn.hnust.pojo.User; @Repository public interface UserDao { // @Select("select * from user_t where id=#{userId}") public User selectByPrimaryKey(int userId); }
3.1.4.3User类与数据库user_t表的映射文件UserMapper.xml
UserMapper.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.cn.hnust.dao.UserDao"> <resultMap type="com.cn.hnust.pojo.User" id="UserResult"> <result property="id" column="id"/> <result property="user_name" column="user_ame"/> <result property="password" column="password"/> </resultMap> <select id="selectByPrimaryKey" parameterType="Integer" resultMap="UserResult"> select * from user_t where id=#{userId} </select> </mapper>
3.1.4.4建立Service接口IUserService
IUserService.java
package com.cn.hnust.service; import com.cn.hnust.pojo.User; public interface IUserService { public User getUserById(int userId); }
3.1.4.5建立IUserService接口的实现类UserServiceImpl
UserServiceImpl.java
package com.cn.hnust.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.cn.hnust.dao.UserDao; import com.cn.hnust.pojo.User; import com.cn.hnust.service.IUserService; @Service("userService") public class UserServiceImpl implements IUserService { @Resource private UserDao userDao; public User getUserById(int userId) { // TODO Auto-generated method stub return this.userDao.selectByPrimaryKey(userId); } }
3.1.4.6建立测试类
测试类在src/test/java中建立,如果使用了Spring那么就可以使用注解的方式来引入配置文件和类,然后将service接口对象注入,就可以进行测试了。
如果测试成功,表示Spring和Mybatis已经整合成功了。输出信息使用的是Log4j打印到控制台。
TestMyBatis.java
package org.zsl.testmybatis; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.alibaba.fastjson.JSON; import com.cn.hnust.pojo.User; import com.cn.hnust.service.IUserService; @RunWith(SpringJUnit4ClassRunner.class) //表示继承了SpringJUnit4ClassRunner类 @ContextConfiguration(locations = {"classpath:spring-mybatis.xml"}) public class TestMyBatis { private static Logger logger = Logger.getLogger(TestMyBatis.class); // private ApplicationContext ac = null; @Resource private IUserService userService = null; // @Before // public void before() { // ac = new ClassPathXmlApplicationContext("applicationContext.xml"); // userService = (IUserService) ac.getBean("userService"); // } @Test public void test1() { User user = userService.getUserById(1); // System.out.println(user.getUserName()); // logger.info("值:"+user.getUserName()); // System.out.println(user.getUser_name()); logger.info(user.getId() + ".................." + user.getUser_name() + "........." + user.getPassword()); } }
Run As -> JUnit Test
运行结果:
至此,完成了Spring和Mybatis这两大框架的整合,下面将继续进行SpringMVC整合进项目中。
3.2整合Spring MVC
3.2.1配置spring-mvc.xml
配置里面的注释很详细,在此就补多少了,主要是自动扫描控制器,视图模式,注解的启动着三个。
spring-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-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --> <context:component-scan base-package="com.cn.hnust.controller" /> <!--避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 --> </list> </property> </bean> <!-- 定义跳转的文件的前后缀 ,视图模式配置--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 --> <property name="prefix" value="/WEB-INF/pages/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean> </beans>
3.2.2配置web.xml文件
这里面对spring-mybatis.xml的引入以及配置的spring-mvc的Servlet就是为了完成SSM整合,之前Spring和Mybatis整合不需要再此处进行任何配置。配置一样有详细的注释。
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>Archetype Created Web Application</display-name> <!-- Spring和mybatis的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <!-- 编码过滤器 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <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内存溢出监听器 --> <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> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath: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> <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 --> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app>
3.3测试
至此已经完成了SSM三大框架的整合了,接下来测试一下。
3.3.1新建jsp页面
success.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Success</title> </head> <body> <p>login success</p> </body> </html>
fail.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>fail</title> </head> <body> <p>login fail</p> </body> </html>
3.3.2建立UserController类
UserController.java 控制器
package com.cn.hnust.controller; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.cn.hnust.pojo.User; import com.cn.hnust.service.IUserService; @Controller @RequestMapping("/user") public class UserController { @Resource private IUserService userService; @RequestMapping("/showUser") @ResponseBody public String toIndex(HttpServletRequest request,Model model){ int userId = Integer.parseInt(request.getParameter("id")); User user = this.userService.getUserById(userId); model.addAttribute("user", user); System.out.println(user.getPassword()); if ( user.getPassword().equals("12345") ) { return "success" + user.getPassword(); } else { return "fail" + user.getPassword(); } // return "success"; } }
这个控制器写的比较简单,就是从浏览器访问/user/showUser?id=1,然后去数据库中取出id为1的用户的信息,判断该用户的密码和“12345”是否相同,如果相同则返回success字符串 + 该用户的密码,否则返回fail字符串 + 该用户的密码,由之前我们存到数据库中的id=1的用户的密码来看,其显然应该返回fail + 该用户的密码:
3.3.3部署项目
Run As -> Run On Server
在浏览器中输入http://localhost:8080/Test/user/showUser?id=1,运行的结果为:
至此,SSM三大框架的整合就完成了,在此基础上可以再太你家啊其他功能。
也可以对UserController进行修改:
package com.cn.hnust.controller; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.cn.hnust.pojo.User; import com.cn.hnust.service.IUserService; @Controller @RequestMapping("/user") public class UserController { @Resource private IUserService userService; @RequestMapping("/showUser") // @ResponseBody public String toIndex(HttpServletRequest request,Model model){ int userId = Integer.parseInt(request.getParameter("id")); User user = this.userService.getUserById(userId); model.addAttribute("user", user); System.out.println(user.getPassword()); if ( user.getPassword().equals("12345") ) { // return "success" + user.getPassword(); return "success"; } else { // return "fail" + user.getPassword(); } // return "success"; return "fail"; } }
验证id=1的用户的密码是否是“12345”,如果是则返回success.jsp页面,否则返回fail.jsp页面,注意去掉了@ResponseBody的注解,返回的就是页面
运行结果: