Maven+Spring+Spring MVC+MyBatis+MySQL整合SSM框架

进入公司开发已经3个多月了,项目用的是Maven+Spring+Spring MVC+MyBatis+MySQL,趁这个周末有空,仔细研读一下公司项目的基本框架,学习一下这个环境是怎么搭建起来的,经过自己的研究终于是成功地试验出来。自己亲手做的才算是自己学到的,决定将其记录下来,以便日后查询,源码同时也欢迎大家拍砖。

一、数据库的准备

这次整合试验想着做个简单的,就决定做一个普通的用户登陆,就一张表吧

我新建的数据库名字是test,然后新建了一张表

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `username` varchar(40) NOT NULL,
  `password` varchar(40) NOT NULL,
  PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
二、Maven WEB项目的创建

这个在这里就不重复了,我这次的项目是基于上次的新建的maven web项目的,如果需要,请参考我之前的博客:http://blog.csdn.net/donggua3694857/article/details/51638598

三、开始整合之旅

用过maven的都知道,有了他我们就没必要去网上下载一堆的jar文件然后自己去管理(虽然我也挺习惯这个方式),下面列出的是我的pom文件,里面列出了哪些jar包都是干什么用的。

<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>com.gray4java</groupId>
  <artifactId>maven</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>maven Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
	<!-- spring核心包 -->  
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-test</artifactId>
		<version>3.2.0.RELEASE</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>3.2.0.RELEASE</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-core</artifactId>
		<version>3.2.0.RELEASE</version>
	</dependency>
	<dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-aop</artifactId>
   		<version>3.2.0.RELEASE</version>
	</dependency>
	<dependency>
		<groupId>aspectj</groupId>
		<artifactId>aspectjweaver</artifactId>
		<version>1.5.4</version>
	</dependency>
	<dependency>
		<groupId>aspectj</groupId>
		<artifactId>aspectjrt</artifactId>
		<version>1.5.4</version>
	</dependency>
	<dependency>
		<groupId>org.codehaus.jackson</groupId>
		<artifactId>jackson-mapper-asl</artifactId>
		<version>1.9.11</version>
	</dependency>
	<!--mybatis核心包-->
	<dependency>
		<groupId>org.mybatis</groupId>
		<artifactId>mybatis</artifactId>
		<version>3.1.1</version>
	</dependency>
	<dependency>
		<groupId>org.mybatis</groupId>
		<artifactId>mybatis-spring</artifactId>
		<version>1.1.1</version>
	</dependency>
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.21</version>
	</dependency>
	<dependency>
		<groupId>c3p0</groupId>
		<artifactId>c3p0</artifactId>
		<version>0.9.1.2</version>
		<type>jar</type>
	</dependency>
	<!--打印日志-->
	<dependency>
		<groupId>org.slf4j</groupId>
		<artifactId>slf4j-api</artifactId>
		<version>1.7.5</version>
	</dependency>
	<dependency>
		<groupId>org.slf4j</groupId>
		<artifactId>slf4j-log4j12</artifactId>
		<version>1.7.5</version>
	</dependency>
	<dependency>
		<groupId>log4j</groupId>
		<artifactId>log4j</artifactId>
		<version>1.2.17</version>
	</dependency>
	<dependency>
		<groupId>jstl</groupId>
		<artifactId>jstl</artifactId>
		<version>1.2</version>
	</dependency>
	<dependency>
       	<groupId>org.springframework</groupId>
       	<artifactId>spring-context-support</artifactId>
       	<version>3.1.2.RELEASE</version>
       	<type>jar</type>
       	<scope>compile</scope>
	</dependency>
  </dependencies>
  <build>
    <finalName>maven</finalName>
    <plugins>
     <plugin>
            <groupId>org.apache.tomcat.maven</groupId> 
            <artifactId>tomcat6-maven-plugin</artifactId> 
            <version>2.1</version>
            <configuration>
            <url>http://localhost:9090/manager</url>
            <server>Tomcat6</server> 
            <port>9090</port>
            <path>/</path>
          </configuration> 
        </plugin>
    </plugins>
  </build>
</project>
maven配置好后就等它把jar包下载完,在下载的过程中 最有可能遇到的问题就是Missing artifact XXXXXX,然后 解决的办法就是,原则是找到本地的仓库,然后删除那个对应的,文件后面有lastUpate的再重新下载。

3.1 Spring和mybatis的整合

3.1.1 创建数据库属性文件jdbc.properties

<span style="font-size:14px;">db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://127.0.0.1:3306/test
db.username=root
db.password=123456</span>
3.1.2 创建mybatis的配置文件mybatis-config.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>
    <typeAliases>
		<typeAlias alias="user" type="com.gray.user.entity.User"/>
    </typeAliases>
</configuration>
3.1.3 创建spring-mybatis配置文件

这个配置文件用于spring和mybatis整合的重要文件,主要有配置数据库、主动扫描和注入一些bean,详细配置如下:

<?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:c="http://www.springframework.org/schema/c"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:ehcache="http://www.springmodules.org/schema/ehcache"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-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-3.1.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springmodules.org/schema/ehcache http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd">
	<!-- 引入属性文件 -->
	<context:property-placeholder location="classpath:jdbc.properties" />
	<!-- 自动扫描(自动注入) -->
	<context:component-scan base-package="com.gray.*.service" />
	<!-- 配置数据源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		destroy-method="close">
		<property name="driverClass" value="${db.driver}" />
		<property name="jdbcUrl" value="${db.url}" />
		<property name="user" value="${db.username}" />
		<property name="password" value="${db.password}" />
		<property name="minPoolSize" value="1" />
		<property name="maxPoolSize" value="20" />
		<property name="maxIdleTime" value="1800" />
		<property name="acquireIncrement" value="2" />
		<property name="maxStatements" value="0" />
		<property name="initialPoolSize" value="2" />
		<property name="idleConnectionTestPeriod" value="1800" />
		<property name="acquireRetryAttempts" value="30" />
		<property name="breakAfterAcquireFailure" value="true" />
		<property name="testConnectionOnCheckout" value="false" />
	</bean>
	
	<!-- myBatis文件 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->
		<property name="configLocation" value="classpath:mybatis-config.xml" />
		<property name="mapperLocations" value="classpath:com/gray/user/entity/mybatis-*.xml" />
	</bean>

	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage"  value="com.gray.*.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"/>  

	<bean id="sqlSession"     class="org.mybatis.spring.SqlSessionTemplate">   
          <constructor-arg index="0" ref="sqlSessionFactory" />   
          <constructor-arg index="1" value="BATCH" />  
     </bean>  
</beans>
3.1.4 日志的输出配置

mybatis内置的日志工厂提供了日志功能,但是它的具体实现有他最先找到的方法来决定,顺序分别是:

  1. slf4j
  2. apache commons logging
  3. log4j 2
  4. log4j
  5. jdk logging
如果一个都没找到,日志功能就被禁用掉了(在我实验的途中,遇到的情况是如果不使用slf4j,只有log4j他就不打印SQL语句,只打印别的日志,可能是我还不会配置不对,因为我见网上的那些博客都没有引入slf4j的包也能使用,对于这问题欢迎牛人给我留言解答)下面是我的创建的log4j.properties文件

##root logger , local level: debug, output: stdout ##
## root logger: better performance than others   ##
log4j.rootLogger=info,stdout

log4j.appender.F=org.apache.log4j.DailyRollingFileAppender
log4j.appender.F.DatePattern='.'yyyy-MM-dd
log4j.appender.F.File=logs/rcp-service-test.log
log4j.appender.F.layout=org.apache.log4j.PatternLayout
log4j.appender.F.layout.ConversionPattern=[%d{ISO8601}|%t|%-5p|%C] - %m%n
log4j.appender.F.encoding=UTF-8

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%d{HH:mm:ss}|%-5p|%c] - %m%n
#show application DEBUG log
log4j.logger.com.asecs = DEBUG,F
#show ibatis DEBUG log
log4j.logger.com.ibatis = DEBUG  
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource = DEBUG  
log4j.logger.com.ibatis.common.jdbc.ScriptRunner = DEBUG  
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate = DEBUG  
log4j.logger.java.sql.Connection = DEBUG  
log4j.logger.java.sql.Statement = DEBUG  
log4j.logger.java.sql.PreparedStatement = DEBUG
log4j.logger.java.sql.ResultSet = DEBUG 
3.1.5 mybatis剩下的工作

前面的工作做完,spring和mybatis的整合就差不多了,接下来是创建实体类、mybatis映射文件以及DAO接口,service以及它的实现类了。

mybatis有通过Generator自动创建代码的,这里我们就勤快点自己手写了,反正也不多。

实体类User 
package com.gray.user.entity;
public class User {
	private String username;
	private String password;
	public String getUsername(){
		return username;
	}
	public void setUsername(String username){
		this.username = username;
	}
	public String getPassword(){
		return password;
	}
	public void setPassword(String password){
		this.password = password;
	}
}
Dao接口 UserDao
package com.gray.user.dao;
import java.util.List;

import org.springframework.stereotype.Repository;
import com.gray.user.entity.User;
@Repository
public interface UserDao<User>{
	List<User> selectId(String username);
}
service接口 UserService
package com.gray.user.service;

import com.gray.user.entity.User;

public interface UserService {
	boolean doUserLogin(User user);
}
以及它的实现类 UserServiceImpl
package com.gray.user.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gray.user.dao.UserDao;
import com.gray.user.entity.User;
import com.gray.user.service.UserService;
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDao<User> dao;
	
	public boolean doUserLogin(User user) {
		List<User> list = dao.selectId(user.getUsername());
		if(list.size() == 0){
			return false;
		}else{
			if(list.get(0).getPassword().equals(user.getPassword())){				
				return true;
			}else{
				return false;
			}			
		}
	}	
}
差点还忘了最重要的映射mybatis-user.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.gray.user.dao.UserDao">
	<resultMap id="BaseResultMap" type="com.gray.user.entity.User">
		<result column="username" property="username" />
		<result column="password" property="password" />
	</resultMap>
  <sql id="Base_Column_List" >
    username, password
  </sql>
  <select id="selectId" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select 
    <include refid="Base_Column_List" />
    from user
    where username = #{username,jdbcType=VARCHAR}
  </select>
</mapper>

3.2 整合SpringMVC

完成上面的操作,接下来还剩下最后的整合springmvc,这个除了写配置文件外还需要额外去配置web.xml,废话不多说,直接上配置文件:

3.2.1 创建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:c="http://www.springframework.org/schema/c"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:ehcache="http://www.springmodules.org/schema/ehcache"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-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-3.1.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
		http://www.springmodules.org/schema/ehcache http://www.springmodules.org/schema/cache/springmodules-ehcache.xsd">
	<mvc:annotation-driven>
		<mvc:message-converters>
			<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
			<bean class="org.springframework.http.converter.FormHttpMessageConverter" />
			<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter" />
			<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
		</mvc:message-converters>
	</mvc:annotation-driven>
	    
	<!-- 使用annotation 自动注册bean,并保证@Required,@Autowired的属性被注入 -->
	<context:component-scan base-package="com.gray"> 
 			<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> 
 			<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" /> 
 	</context:component-scan> 
 	<aop:aspectj-autoproxy proxy-target-class="true">
        <aop:include name="controllerAspect"/>
    </aop:aspectj-autoproxy>
	

	<!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
	<!-- 支持JSON数据格式 -->
	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="mappingJacksonHttpMessageConverter" />
			</list>
		</property>
	</bean>
	<bean id="mappingJacksonHttpMessageConverter"
		class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
	</bean>

	
	<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" /><!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 -->
	</bean>
	
</beans>
3.2.3 配置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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" 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>

<listener>
	<description>spring监听器</description>
	<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>
	<description>spring mvc servlet</description>
	<servlet-name>springMvc</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<init-param>
		<description>spring mvc 配置文件</description>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring-mvc.xml</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
	<servlet-name>springMvc</servlet-name>
	<url-pattern>*.do</url-pattern>
</servlet-mapping>

<filter>
	<description>字符集过滤器</description>
	<filter-name>encodingFilter</filter-name>
	<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
	<init-param>
		<description>字符集编码</description>
		<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>

<!-- 配置session超时时间,单位分钟 -->
<session-config>
	<session-timeout>60</session-timeout>
</session-config>

<!-- DEFAULT PAGE -->
<welcome-file-list>
	<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

</web-app>
四、测试阶段

千辛万苦终于到了测试阶段。。。要弄懂配置文件里面到底写了些什么东西还是需要花点时间去研读的。

4.1 新建测试页面
测试我新建了两个jsp页面,分别是success.jsp和fail.jsp,顾名思义就是登陆成功了就显示success页面,失败则显示fail页面。页面写得很简单,就不把代码贴出来了,需要的在后面的源码里面有。

4.2 新建控制器 LoginController.java

后台逻辑也同样简单

package com.gray.user.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gray.user.entity.User;
import com.gray.user.service.impl.UserServiceImpl;

@Controller
@RequestMapping("/test") 
public class LoginController {
	@Autowired
	private UserServiceImpl userService;

@RequestMapping("/dologin.do") //url
public String dologin(User user, Model model){
	if(userService.doUserLogin(user)){
		model.addAttribute("successMsg", "登陆成功!");//返回到页面所夹带的参数
		model.addAttribute("name", user.getUsername());
		return "/success";//返回的页面
	}else{
		model.addAttribute("failMsg", "用户不存在或密码错误!");
		return "/fail";
	}	
}
}
4.3部署测试

做了那么多,成功或失败测一下就知道了,如果能成功通过测试,那么恭喜你SSM试验整合成功,如果失败了,那就请耐心地调试吧,毕竟程序员整天与bug为伍,或者给我留言或评论,我们一起解决问题一起进步。很显然我的是成功的,不然我也不会写出来是不是,哈哈。

(手动分割线)

这边测试界面写得丑了点,还请大家多多担待.....

终于可以长舒一口气,Maven+Spring+Spring MVC+MyBatis+MySQL整合SSM框架到这里就结束了,要继续加其他功能就在这基础上添加就好,最后附一张项目的完整的目录结构图:

最后同样附上项目源码下载地址:http://download.csdn.net/detail/donggua3694857/9572482

github:https://github.com/HuangJunXiong/Spring-SpringMVC-MyBatis-Maven

注:此demo的spring版本较低,是3.2,最高与jdk1.7兼容,建议更新spring的版本,如有需要请参考我github上的例子,那个是4.3.3.RELEASE





已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页