首页 > 代码库 > Spring MVC+Mybatis+Maven+Velocity+Mysql整合实例

Spring MVC+Mybatis+Maven+Velocity+Mysql整合实例

本篇文章将通过一个简单显示用户信息的实例整合Spring mvc+mybatis+Maven+velocity+mysql.

对于实现整合的重点在于以下几个配置文件的实现

1.Maven依赖包

2.spring配置文件(springContext-user.xml)

3.mybatis配置文件(MyBatis-User-Configuration.xml)

4.spring-mvc配置文件(spring-mvc.xml)

5.web.xml配置文件

源码下载地址:http://download.csdn.net/detail/a123demi/8398665

一、.Maven工程目录

技术分享

二、Spring mvc + mybatis +maven实现

1.Mysql数据库表数据

CREATE TABLE `user` (
  `userId` varchar(20) NOT NULL,
  `userName` varchar(20) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL,
  `sex` char(1) DEFAULT '0',
  `email` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Data for the table `user` */

insert  into `user`(`userId`,`userName`,`password`,`sex`,`email`) values ('1','lm','1','1','aaaaaa@126.com'),('2','dlm','1','0','bbbbbb@qq.com');


2.Maven依赖引入(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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>cms</groupId>
	<artifactId>user_cms</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>user_cms Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<properties>
		<!-- spring版本号 -->
		<spring.version>3.2.4.RELEASE</spring.version>
		<org.aspectj.version>1.7.3</org.aspectj.version>
		<!-- mybatis版本号 -->
		<mybatis.version>3.2.4</mybatis.version>
		<!-- log4j日志文件管理包版本 -->
		<slf4j.version>1.6.6</slf4j.version>
		<log4j.version>1.2.12</log4j.version>
	</properties>
	<dependencies>
		<!-- spring核心包 -->
		<!-- springframe start -->
		<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>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>${org.aspectj.version}</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj.version}</version>
		</dependency>

		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2.2</version>
		</dependency>
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib-nodep</artifactId>
			<version>2.2.2</version>
		</dependency>
		<!-- springframe end -->

		<!-- 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>
		<!-- mysql驱动包 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.29</version>
		</dependency>
		<!-- junit测试包 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
		<!-- 阿里巴巴数据源包 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.2</version>
		</dependency>

		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.1</version>
		</dependency>

		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>

		<!-- json数据 -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.13</version>
		</dependency>

		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>

		<dependency>
			<groupId>org.apache.velocity</groupId>
			<artifactId>velocity</artifactId>
			<version>1.7</version>
		</dependency>
		<dependency>
			<groupId>org.apache.velocity</groupId>
			<artifactId>velocity-tools</artifactId>
			<version>2.0</version>
		</dependency>

		<!-- 日志文件管理包 -->
		<!-- log start -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</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 -->
	</dependencies>
	<build>
		<finalName>user_cms</finalName>
		
			<plugins>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-compiler-plugin</artifactId>
			<configuration>
				<source>1.7</source>
				<target>1.7</target>
			</configuration>
		</plugin>
	</plugins>
	</build>


</project>

3.实体类UserEntity.java

package com.lm.entity;

public class UserEntity {
	private String userId;
	private String userName;
	private String password;
	private String sex;
	private String email;
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	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;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	@Override
	public String toString() {
		return "UserEntity [userId=" + userId + ", userName=" + userName
				+ ", password=" + password + ", sex=" + sex + ", email="
				+ email + "]";
	}
	
	
	
}

4.业务逻辑接口(Service)

package com.lm.service;

import java.util.List;

import com.lm.entity.UserEntity;


public interface UserService {

	UserEntity getUserEntityById(String userId);
	
	List<UserEntity> getUserEntities();
	
	UserEntity insertUserEntity(UserEntity userEntity);
}

说明:1.根据用户id获取用户信息

     2.获取所有的用户信息

     3.插入用户信息


5.接口实现(ServiceImpl)

package com.lm.service.impl;

import java.util.List;

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

import com.lm.entity.UserEntity;
import com.lm.mapping.UserMapper;
import com.lm.service.UserService;

public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;

	public UserMapper getUserMapper() {
		return userMapper;
	}

	public void setUserMapper(UserMapper userMapper) {
		this.userMapper = userMapper;
	}

	@Override
	public UserEntity getUserEntityById(String userId) {
		return this.userMapper.getUserEntityById(userId);
	}

	@Override
	public List<UserEntity> getUserEntities() {
		return this.userMapper.getUserEntities();
	}

	@Override
	public UserEntity insertUserEntity(UserEntity userEntity) {
		this.userMapper.insertUser(userEntity);

		return getUserEntityById(userEntity.getUserId());
	}

}


6.具体操作数据库接口(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.lm.mapping.UserMapper">
	<resultMap id="userEntityMapper" type="UserEntity">
		<id property="userId" column="userId" />
		<result property="userName" column="userName" />
		<result property="password" column="password" />
		<result property="sex" column="sex" />
		<result property="email" column="email" />
	</resultMap>
	
	<select id="getUserEntityById" parameterType="String" resultMap="userEntityMapper">
		select * from user where userid=#{param1}   
	</select>
	
	<select id="getUserEntities" resultMap="userEntityMapper">
		select * from user 
	</select>
	
	<insert id="insertUser" parameterType="userEntity">
		insert into user(userId,userName,password,sex,email) 
		values(#{userEntity.userId},#{userEntity.userName},#{userEntity.password},#{userEntity.sex},#{userEntity.email})
	</insert>
	
</mapper>

说明:mybatis的简单用法
package com.lm.mapping;

import java.util.List;

import com.lm.entity.UserEntity;

public interface UserMapper {
	
	UserEntity getUserEntityById(String userId);
	
	List<UserEntity> getUserEntities();
	
	int insertUser(UserEntity userEntity);
}


7.Spring+mybatis+Spring mvc配置文件

1)spring配置文件(applicationContext-user.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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/context
     			http://www.springframework.org/schema/context/spring-context-3.0.xsd
     			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     			http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
    			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
     			http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
	<task:annotation-driven />
	<bean id="basePropertyPlaceHolder"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
		lazy-init="true">
		<property name="systemPropertiesModeName" value=http://www.mamicode.com/"SYSTEM_PROPERTIES_MODE_OVERRIDE" />>

2)mybatis配置文件(MyBatis-User-Configuration.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>
	<settings>
		<setting name="cacheEnabled" value=http://www.mamicode.com/"true" />>

3)Spring mvc 配置文件(引入velocity相关配置spring-mvc.xml)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 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-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">

	<!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->
	<context:component-scan base-package="com.lm.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>

	<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 -->
			</list>
		</property>
	</bean>

	<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 p:prefix中模板放置路径 -->
	<bean id="velocityConfig"
		class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
		<property name="resourceLoaderPath" value=http://www.mamicode.com/"/WEB-INF/view/" />>

8.数据库和log4j配置

1)数据库配置jdbc.properties

#mysql
mysql.driverClassName=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/test
mysql.username=root
mysql.password=123

2)log4j日志配置

log4j.rootLogger=DEBUG,console

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%p] %c#%M %x: %m%n

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


9.控制层Controller(UserController.java)

package com.lm.controller;

import javax.servlet.http.HttpServletRequest;

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

import com.lm.entity.UserEntity;
import com.lm.service.UserService;

@Controller
public class UserController {

	private UserService userService;

	public UserService getUserService() {
		return userService;
	}

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	//http://localhost:8085/user_cms/userController/1/showUser.do
	@RequestMapping("/{id}/showUser")
	public String showUser(@PathVariable String id, ModelMap modelMap ,HttpServletRequest request) {
		UserEntity u = userService.getUserEntityById(id);
	
		if(u == null){
			u = new UserEntity();
			u.setEmail("");
			u.setUserId("");
		}
		modelMap.put("user", u);
		return "showUser";
	}
	
	//http://localhost:8085/user_cms/userController/showUser.do?id=1
	@RequestMapping("showUser")
	public String showUserEntity(String id, ModelMap modelMap,HttpServletRequest request) {
		UserEntity u = userService.getUserEntityById(id);
		if(u == null){
			u = new UserEntity();
			u.setEmail("");
			u.setUserId("");
		}
		modelMap.put("user", u);
		return "showUser";
	}
	
	@RequestMapping("/showUserExample")
	public String showUsers(Model model){
		return "redirect:/1/showUser.do";
	}
	
    @RequestMapping("/userList")
    public String list(ModelMap model) {
        model.put("users", userService.getUserEntities());
        return "list";
    }
    
    @RequestMapping("/user/{id}")
    public String detail(@PathVariable(value = http://www.mamicode.com/"id") String id, ModelMap model) {>说明:@RequestMapping的具体用法可以参考http://blog.csdn.net/lufeng20/article/details/7598801

三、前端相关配置

1.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>mybatis</display-name>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:config/applicationContext-user.xml,classpath:config/MyBatis-User-Configuration.xml</param-value>
	</context-param>
	<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>

	<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:config/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>
	<welcome-file-list>
		<welcome-file>/index.jsp</welcome-file>
	</welcome-file-list>
	<!-- 配置session超时时间,单位分钟 -->
	<session-config>
		<session-timeout>15</session-timeout>
	</session-config>
</web-app>

2.index.jsp

<script language="javascript">
	window.location.href=http://www.mamicode.com/"userList.do";>

3.相关vm文件

1)模板文件layout.vm

<html>
    <head>
        <title>Spring MVC and Velocity</title>
    </head>
    <body>
        <h1>Spring MVC and Velocity</h1>

        $screen_content

        <hr />
        Copyright &copy 2014 lm
    </body>
</html>

2) list.vm

<h2>List of Feeds</h2>
<ul>
    #foreach($user in $users)
        <li><a href=http://www.mamicode.com/"user/${user.userId}">${user.email}>

3) detail.vm

<h2>Detail of Feed</h2>

<p>Id: ${user.userId}</p>
<p>Title: ${user.email}</p>

以上就是Spring mvc+mybatis+maven+velocity+mysql整合的所有内容







Spring MVC+Mybatis+Maven+Velocity+Mysql整合实例