前几天趁空闲时间整合了下SpringMVC+Mybatis+Druid,这里小记录下,这个Demo是基于Maven构建的,数据源用的是阿里巴巴温少的开源项目Druid,数据库用的是Mysql。

由于Eclipse去安装Maven很不方便,也老出错,这里我使用的是Spring Tool Suite(STS,基于 Spring IDE ,提供了其它的一些特性,如 基于 Spring dm Server 的osgi 开发,及其它一些 Spring 项目的支持,如 Spring Roo , Spring Batch 等)。

这里是STS的下载地址(集成了Maven):http://spring.io/tools/sts/all

先看一下整体的项目结构:

  

一、相关JAR包

由于是基于Maven的项目,找起JAR包自然就方便了许多,我们只需要知道JAR的名字或者其中关键字就可以很轻松的把JAR包以及依赖JAR下载下来,需要多少下多少。

这里给出pom的配置文件。

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>SpringMybatis</groupId>
<artifactId>SpringMybatis</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringMybatis Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</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.0.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.11</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<build>
<finalName>SpringMybatis</finalName>
</build>
</project>

由于Maven会把JAR包所依赖的JAR包也一起下载下来,这里我们就不需要逐个去写Spring的相关JAR包。

这里用到了阿里巴巴温少的开源项目Druid的数据源,所以额外的多引入了一个Druid的JAR包。

关于JAR的扩展,如果有需要别的可以到:http://search.maven.org/ 去查找,然后复制到这个配置文件即可,Maven会帮我们自动下载添加。

二、相关配置

spring.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"> <!-- 自动注入 -->
<context:component-scan base-package="lcw/service"/> </beans>

mybatis-spring.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"> <!-- 配置数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="jdbc:mysql:///test"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean> <!-- Mybatis文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations" value="classpath:lcw/mapping/*.xml"></property>
</bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="lcw.dao"></property>
<property name="sqlSessionFactoryBeanName" value ="sqlSessionFactory"></property>
</bean> <!-- 事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>

springmvc.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.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
"> <!-- 启用spring mvc 注解 -->
<context:annotation-config /> <!-- 设置使用注解的类所在的jar包 -->
<context:component-scan base-package="lcw.controller"></context:component-scan> <!-- 完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/" p:suffix=".jsp" /> </beans>

log4j.properties

 #
# Copyright 2009-2012 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ### Global logging configuration
log4j.rootLogger=DEBUG, stdout ### Uncomment for MyBatis logging
log4j.logger.org.apache.ibatis=DEBUG ### 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

三、项目演示

  

关于model、dao以及mapping的生成方式,在之前的文章《使用Mybatis-Generator自动生成Dao、Model、Mapping相关文件》有提到,这里就不再给出。

UserController.java

 package lcw.controller;

 import lcw.model.User;
import lcw.service.UserServiceI; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/userController")
public class UserController { private UserServiceI userService; public UserServiceI getUserService() {
return userService;
}
@Autowired
public void setUserService(UserServiceI userService) {
this.userService = userService;
} @RequestMapping("/showUser")
public String showUser(Model model){
User user=userService.getUserById(1);
model.addAttribute("user", user);
return "showuser";
} }

UserServiceI.java

 package lcw.service;

 import lcw.model.User;

 public interface UserServiceI {

     public User  getUserById(int id);

 }

UserService.java

package lcw.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import lcw.dao.UserMapper;
import lcw.model.User; @Service("userService")
public class UserService implements UserServiceI { private UserMapper userMapper; public UserMapper getUserMapper() {
return userMapper;
} @Autowired
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
} @Override
public User getUserById(int id) {
return userMapper.selectByPrimaryKey(id); } }

showuser.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>Insert title here</title>
</head>
<body>
Hello ${user.password} !!
</body>
</html>

web.xml

 <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_2_5.xsd"
id="WebApp_ID" version="2.5"> <!-- 解决工程编码过滤器 -->
<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>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- SpringMVC配置 -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <!-- 配置文件所在位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml,classpath:mybatis-spring.xml</param-value>
</context-param>
<!-- Spring配置(监听器) -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> </web-app>

看下效果图:

好了,SpringMVC+Mybtis+Druid完美整合~

作者:Balla_兔子
出处:http://www.cnblogs.com/lichenwei/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。
正在看本人博客的这位童鞋,我看你气度不凡,谈吐间隐隐有王者之气,日后必有一番作为!旁边有“推荐”二字,你就顺手把它点了吧,相得准,我分文不收;相不准,你也好回来找我!

最新文章

  1. 理解Java对象的交互:时钟显示程序
  2. 线程同步以及 yield() wait()和notify()、notifyAll()
  3. css study
  4. iOS开发——UI基础-提示框
  5. UIApplication sharedApplication详细解释-IOS
  6. CSS简写指南
  7. java中Date的getTime() 方法奇葩问题
  8. HDU 4749-Parade Show(KMP变形)
  9. springMVC get请求及其请求地址写法
  10. CodeForces 573A Bear and Poker
  11. 修改UISearchBar placeholder textColor
  12. Assets理解随笔
  13. kali linux /etc/apt/source.list
  14. “selection does not contain a main type”解决方法
  15. 开机后发现Win7桌面上什么都没有该如何恢复
  16. HDU X mod f(x)(题解注释)
  17. app.config 配置多项 配置集合 自定义配置(4) 自动增加配置项到配置文件的两种方法
  18. NSRC技术分享——自制Linux Rootkit检测工具
  19. Netty 4源码解析:请求处理
  20. H5页面的高度宽度100%

热门文章

  1. OpenWrt资料汇总
  2. c#访问http接口的&quot;编码&quot;问题
  3. TF Boys (TensorFlow Boys ) 养成记(五)
  4. iOS开发中使用CocoaPods来管理第三方的依赖程序
  5. GO語言基礎教程:數組,切片,map
  6. INFO - InstallShield中的InstallScript工程Setup.exe /s的使用细节
  7. Notes for Linux Administration Handbook (1) : Booting and Shutting Down
  8. 解决chi_sim.traineddata报read_params_file: parameter not found: allow_blob_division
  9. linux上nginx+apache 搭建 svn服务器
  10. C#代码像QQ的右下角消息框一样,无论现在用户的焦点在哪个窗口,消息框弹出后都不影响焦点的变化,那么有两种方法