本篇文章将通过一个简单显示用户信息的实例整合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
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','[email protected]'),('2','dlm','1','0','[email protected]');
<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>
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 + "]"; } }
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.插入用户信息
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()); } }
<?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); }
<?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="SYSTEM_PROPERTIES_MODE_OVERRIDE" /> <property name="ignoreResourceNotFound" value="true" /> <property name="locations"> <list> <value>classpath*:/properties/jdbc.properties</value> </list> </property> </bean> <!-- mysql configuration --> <bean id="baseDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${mysql.driverClassName}" /> <property name="url" value="${mysql.url}" /> <property name="username" value="${mysql.username}" /> <property name="password" value="${mysql.password}" /> </bean> <!-- Transaction management, use PlatformTransactionManager instead of JtaTransactionManager with jndi --> <bean id="txManagerUser" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="baseDataSource" /> </bean> <tx:advice id="txAdvicedrugUser" transaction-manager="txManagerUser"> <tx:attributes> <tx:method name="get*" read-only="true" /> <tx:method name="*" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="userServiceOperation1" expression="execution(* com.lm.*.service..*Service.*(..)))" /> <aop:pointcut id="userServiceOperation2" expression="execution(* com.lm.*.*.service..*Service.*(..)))" /> </aop:config> <!-- define the SqlSessionFactory --> <bean id="sqlSessionFactoryUser" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="baseDataSource" /> <property name="configLocation" value="classpath:config/MyBatis-User-Configuration.xml" /> </bean> <!-- DAO Mapper 层 --> <bean id="baseMapperUser" class="org.mybatis.spring.mapper.MapperFactoryBean" abstract="true" lazy-init="true"> <property name="sqlSessionFactory" ref="sqlSessionFactoryUser" /> </bean> <bean id="userMapper" parent="baseMapperUser"> <property name="mapperInterface" value="com.lm.mapping.UserMapper" /> </bean> <!-- Service层 --> <bean id="userService" class="com.lm.service.impl.UserServiceImpl"> <property name="userMapper" ref="userMapper" /> </bean> </beans>
<?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="true" /> <setting name="lazyLoadingEnabled" value="true" /> <setting name="multipleResultSetsEnabled" value="true" /> <setting name="useColumnLabel" value="true" /> <setting name="useGeneratedKeys" value="false" /> <setting name="autoMappingBehavior" value="PARTIAL" /> <setting name="defaultExecutorType" value="SIMPLE" /> <!-- BATCH, REUSE --> <setting name="defaultStatementTimeout" value="25000" /> <setting name="safeRowBoundsEnabled" value="false" /> <setting name="mapUnderscoreToCamelCase" value="false" /> <setting name="localCacheScope" value="SESSION" /> <setting name="jdbcTypeForNull" value="OTHER" /> <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString" /> </settings> <typeAliases> <typeAlias alias="UserEntity" type="com.lm.entity.UserEntity" /> </typeAliases> </configuration>
<?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="/WEB-INF/view/" /> <property name="velocityProperties"> <props> <prop key="input.encoding">UTF-8</prop> <prop key="output.encoding">UTF-8</prop> </props> </property> </bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver"> <property name="cache" value="true" /> <property name="prefix" value="" /> <property name="layoutUrl" value="layout.vm" /> <property name="suffix" value=".vm" /> <property name="contentType"><value>text/html;charset=UTF-8</value></property> </bean> <!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/view/" p:suffix=".jsp" /> --> <!-- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding"> <value>UTF-8</value> </property> <property name="maxUploadSize"> <value>32505856</value>上传文件大小限制为31M,31*1024*1024 </property> <property name="maxInMemorySize"> <value>4096</value> </property> </bean> --> </beans>
#mysql mysql.driverClassName=com.mysql.jdbc.Driver mysql.url=jdbc:mysql://localhost:3306/test mysql.username=root mysql.password=123
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
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 = "id") String id, ModelMap model) { model.put("user", userService.getUserEntityById(id)); return "detail"; } }说明:@RequestMapping的具体用法可以参考http://blog.csdn.net/lufeng20/article/details/7598801
<?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</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>
<script language="javascript"> window.location.href="userList.do"; </script>
<html> <head> <title>Spring MVC and Velocity</title> </head> <body> <h1>Spring MVC and Velocity</h1> $screen_content <hr /> Copyright © 2014 lm </body> </html>
<h2>List of Feeds</h2> <ul> #foreach($user in $users) <li><a href="user/${user.userId}">${user.email}</a></li> #end </ul>
<h2>Detail of Feed</h2>
<p>Id: ${user.userId}</p> <p>Title: ${user.email}</p>