一、开发环境
Eclipse:eclipse-jee-luna-SR1a-win32;
JDK:jdk-8u121-windows-i586.exe;
MySql:MySQL Server 5.5;
二、创建Maven项目
1.创建父项目
NEW->PROJECT->MAVEN->Maven Project,点击next>进入下一步,可以看到New Maven Project界面,
点击Next >进入下一步,进入Select an Archetype界面,在Filter:输入simple,选择org.apache.maven.archetypes,
点击next>,进入Enter a group id for the artifact界面,
填写好Group Id和Artifact Id,我这里在ssm分组下创建了一个parent项目。点击Finish。
2.创建子项目
选中parent项目,右键,选择new->project->maven->maven Module,点击Next,进入Enter a module name界面,
填写Module Name,点击next>,进入Select an Archetype界面,
在Filter输入start,选择maven-archetype-quickstart,点击next>,进入Specify Archetype parameters界面,
修改Package,点击Finish。就会创建parent项目下的一个子项目dao。
打开parent项目的pom.xml
可以看到有个<moduls><module>dao</module></modules>,这说明dao已经是parent项目的子项目了。
接着我们按照上述方法继续创建子项目service和model。
创建web子项目时,在进入Select an Archetype界面,在Filter填写web,选择org.apache.maven.archetypes.
点击next>,修改package,最后点击Finish。
这样,我们的父项目和所有子项目就已经创建完了。如下图:
右键web子项目(其他子项目操作相同),build path->configure build path,打开Java Build Path,点击Libraies页,
如图,删除JRE System Lirary[J2SE-1.5],重新选择你自己的jdk;
三、添加Springmvc+MyBatis依赖的jar包
在父类的pom.xml中添加SpringMvc+MyBatis所有依赖包
<?xml version="1.0" encoding="UTF-8"?>
<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>ssm</groupId>
<artifactId>parent</artifactId>
<version>1</version>
<packaging>pom</packaging> <distributionManagement>
<site>
<id>website</id>
<url>scp://webhost.company.com/www/website</url>
</site>
</distributionManagement> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- 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>
<modules>
<module>dao</module>
<module>web</module>
<module>service</module>
<module>model</module>
</modules> <!-- <dependencyManagement> -->
<dependencies>
<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>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
</exclusion>
</exclusions>
</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>
<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core自动创建代码 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.3.2</version>
</dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.3.2</version>
</dependency> </dependencies>
<!-- </dependencyManagement> --> </project>
pom.xml
四,自动生成代码
1.创建数据库和表
/*
Navicat MySQL Data Transfer Source Server : localhost
Source Server Version : 50521
Source Host : localhost:3306
Source Database : test Target Server Type : MYSQL
Target Server Version : 50521
File Encoding : 65001 Date: 2017-03-28 11:11:09
*/ SET FOREIGN_KEY_CHECKS=0; -- ----------------------------
-- Table structure for `user_t`
-- ----------------------------
DROP TABLE IF EXISTS `user_t`;
CREATE TABLE `user_t` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_name` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of user_t
-- ----------------------------
INSERT INTO `user_t` VALUES ('', '张三', '', '');
2.利用mybatis-generator-core-1.3.5.jar自动创建代码
1.在本地创建一个文件夹(我在D盘创建了一个generator文件夹);
2.在generator文件夹下创建一个src文件夹,
3.添加2个jar包mybatis-generator-core-1.3.5.jar和mysql-connector-java-5.1.30.jar
4.在创建一个generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 数据库驱动 -->
<classPathEntry location="mysql-connector-java-5.1.30.jar" />
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true" />
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库链接URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://127.0.0.1:3306/test" userId="root"
password="root">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 生成模型的包名和位置 -->
<javaModelGenerator targetPackage="com.gwx.model"
targetProject="src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 生成映射文件的包名和位置 -->
<sqlMapGenerator targetPackage="com.gwx.mapping"
targetProject="src">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 生成DAO的包名和位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.gwx.dao" targetProject="src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名 -->
<table tableName="user_t" domainObjectName="User"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
generatorConfig.xml
5创建一个start.bat
set current_path="%cd%"
java -jar mybatis-generator-core-1.3.5.jar -configfile generatorConfig.xml -overwrite
pause
exit
start.bat
整体目录结构如下:
然后运行start.bat(双击),则自动生成了dao,mapping,model代码
五、添加子项目之间的依赖
1.给web子项目添加service子项目的依赖
打开web项目的pom.xml
给<dependencies>下添加
<dependency>
<groupId>ssm</groupId>
<artifactId>service</artifactId>
<version>1</version>
</dependency>
完整web/pom.xml如下:
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>ssm</groupId>
<artifactId>parent</artifactId>
<version>1</version>
</parent>
<artifactId>web</artifactId>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ssm</groupId>
<artifactId>service</artifactId>
<version>1</version>
</dependency>
</dependencies>
<build>
<finalName>web</finalName>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
</plugins>
</build>
</project>
web/pom.xml
2.给service子项目添加dao子项目的依赖
打开service项目的pom.xml
给<dependencies>下添加
<dependency>
<groupId>ssm</groupId>
<artifactId>dao</artifactId>
<version>1</version>
</dependency>
完整service/pom.xml如下:
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>ssm</groupId>
<artifactId>parent</artifactId>
<version>1</version>
</parent>
<artifactId>service</artifactId>
<name>service</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ssm</groupId>
<artifactId>dao</artifactId>
<version>1</version>
</dependency>
</dependencies>
</project>
service/pom.xml
3.给dao子项目添加model子项目的依赖
打开dao项目的pom.xml
给<dependencies>下添加
<dependency>
<groupId>ssm</groupId>
<artifactId>model</artifactId>
<version>1</version>
</dependency>
完整dao/pom.xml如下:
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>ssm</groupId>
<artifactId>parent</artifactId>
<version>1</version>
</parent>
<artifactId>dao</artifactId>
<name>dao</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ssm</groupId>
<artifactId>model</artifactId>
<version>1</version>
</dependency>
</dependencies>
</project>
dao/pom.xml
整个项目依赖关系添加完毕:web依赖service,service依赖dao,dao依赖model,parent是父项目
六、添加代码
1.model子项目创建com.gwx.model包,将上面第四节自动生成model目录下的代码复制到com.gwx.model包下;
2.dao子项目src/main/java下创建com.gwx.dao和在src/main/resources下创建mapping包,将上面第四节自动生成dao目录下的的代码复制到
com.gwx.dao包下,将mapping目录下自动生成的代码复制到mapping包下;
3.service子项目创建com.gwx.service包和com.gwx.service.impl包,在com.gwx.service包下创建接口IUserService
package com.gwx.service; import com.gwx.model.User; public interface IUserService {
User getUserById(int id); }
IUserService.java
在com.gwx.service.impl包下创建UserService
package com.gwx.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.gwx.dao.UserMapper;
import com.gwx.model.User;
import com.gwx.service.IUserService; @Service("userService")
public class UserService implements IUserService { @Resource
private UserMapper userDao; public User getUserById(int userId) {
return this.userDao.selectByPrimaryKey(userId);
} }
UserService
七、Spring与MyBatis的整合
1.在子项目web项目中的resources目录下创建jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8
username=root
password=root
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000
jdbc.properties
2.Log4j的配置(可有可无)
在你需要查看日志的子项目的resources目录下创建log4j.properties
#定义LOG输出级别
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/web/log.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
#输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
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
log4j.properties
3.在子项目dao层的resources目录下创建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-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自动扫描 -->
<context:component-scan base-package="com.gwx.dao" />
<context:component-scan base-package="com.gwx.service" />
<context:component-scan base-package="com.gwx.service.impl" />
<context:component-scan base-package="com.gwx.controller" />
<!-- 引入配置文件 -->
<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:mapping/*.xml"></property>
</bean>
<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.gwx.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>
spring-mybatis.xml
4.Junit测试
先将parent/pom.xml,model/pom.xml,dao/pom.xml,service/pom.xml中的
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<!-- <scope>test</scope> -->
</dependency>
删除;将web/pom.xml
中的修改为
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<!-- <scope>test</scope> -->
</dependency>
再右键web项目->properties->Java Compiler->修改为和你当前jdk版本一致;(我本地的jdk版本为1.8)如图
在web项目中的src/main/java包下创建com/gwx/test包,创建TestMyBatis.java
package com.gwx.test;
import javax.annotation.Resource; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.gwx.model.User;
import com.gwx.service.IUserService; @RunWith(SpringJUnit4ClassRunner.class) // 表示继承了SpringJUnit4ClassRunner类
@ContextConfiguration(locations = { "classpath:spring-mybatis.xml" }) public class TestMyBatis {
@Resource
private IUserService userService; @Test
public void test() {
User user = userService.getUserById(1);
System.out.println(user.getUserName());
}
}
TestMyBatis.java
运行。控制台出现'张三'则表示整合成功!
八、SpringMVC整合
在web子项目的resources下创建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"> <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
<bean id="stringHttpMessageConverter"
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
<!-- Jackson 是Spring 自带的功能 -->
<bean id="mappingJackson2HttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
<value>application/xml;charset=UTF-8</value>
<value>text/html;charset=UTF-8</value>
<value>text/plain;charset=UTF-8</value>
<value>text/xml;charset=UTF-8</value>
<value>text/javascript;charset=UTF-8</value>
</list>
</property>
</bean> <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<!-- JSON转换器 -->
<ref bean="mappingJackson2HttpMessageConverter" />
</list>
</property>
</bean> <!-- 对静态资源的访问 -->
<!-- <mvc:resources mapping="/js/**" location="/js/" /><mvc:resources mapping="/css/**"
location="/css/" /> --> <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
<context:component-scan base-package="com.gwx.controller" /> <!-- 添加注解驱动 -->
<mvc:annotation-driven enable-matrix-variables="true" >
<mvc:message-converters>
<ref bean="stringHttpMessageConverter" />
<ref bean="mappingJackson2HttpMessageConverter" />
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 允许对静态资源文件的访问 --> <mvc:default-servlet-handler /> <!-- 定义跳转的文件的前后缀 ,视图模式配置 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<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>
spring-mvc.xml
再配置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.html</welcome-file>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
web.xml
在web子项目的 Java Resources下创建package com.gwx.controller,在com.gwx.controller下面创建UserController.java
package com.gwx.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.gwx.model.User;
import com.gwx.service.IUserService;
import com.gwx.util.JacksonUtil; @Controller
@RequestMapping("/user")
public class UserController { @Resource
private IUserService userService; @RequestMapping("/showUser")
public String toIndex(HttpServletRequest request, Model model) {
User user = this.userService.getUserById(1);
model.addAttribute("user", user);
return "User";
}
@RequestMapping("/showJson")
@ResponseBody
public String showJson(int id) {
User user = this.userService.getUserById(id);
String jSon = JacksonUtil.toJSon(user);
return jSon;
}
}
UserController
在model子项目下创建package com.gwx.util,在com.gwx.util下面创建JacksonUtil.java和httpModel.java
package com.gwx.util; import java.io.Serializable; public class HttpModel implements Serializable{ /**
*
*/
private static final long serialVersionUID = -7484615771443870211L; private int code = 0;
private Object object;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
} }
HttpModel.java
package com.gwx.util; import java.util.UUID; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; /**
* The class JacksonUtil
*
* json字符与对像转换
*
* @version: $Revision$ $Date$ $LastChangedBy$
*
*/
public final class JacksonUtil { public static ObjectMapper objectMapper; /**
* 使用泛型方法,把json字符串转换为相应的JavaBean对象。
* (1)转换为普通JavaBean:readValue(json,Student.class)
* (2)转换为List,如List<Student>,将第二个参数传递为Student
* [].class.然后使用Arrays.asList();方法把得到的数组转换为特定类型的List
*
* @param jsonStr
* @param valueType
* @return
*/
public static <T> T readValue(String jsonStr, Class<T> valueType) {
if (objectMapper == null) {
objectMapper = new ObjectMapper();
} try {
return objectMapper.readValue(jsonStr, valueType);
} catch (Exception e) {
e.printStackTrace();
} return null;
} /**
* json数组转List
* @param jsonStr
* @param valueTypeRef
* @return
*/
public static <T> T readValue(String jsonStr, TypeReference<T> valueTypeRef){
if (objectMapper == null) {
objectMapper = new ObjectMapper();
} try {
return objectMapper.readValue(jsonStr, valueTypeRef);
} catch (Exception e) {
e.printStackTrace();
} return null;
} /**
* 把JavaBean转换为json字符串
*
* @param object
* @return
*/
public static String toJSon(Object object) {
if (objectMapper == null) {
objectMapper = new ObjectMapper();
} try {
return objectMapper.writeValueAsString(object);
} catch (Exception e) {
e.printStackTrace();
} return null;
} /**
* 生成手机令牌
* @return
*/
public final static String generateToken() {
return UUID.randomUUID().toString().replace("-", "");
} public static String toHttpJson(int code,Object object)
{
HttpModel model = new HttpModel();
model.setCode(code);
model.setObject(object);
return JacksonUtil.toJSon(model);
} }
JacksonUtil.java
在web项目的src/main/webapp/WEB-INF下创建jsp文件夹,然后创建User.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>姓名</title>
</head>
<body>${user.userName}
</body>
</html>
User.jsp
此时,springmvc和json都已经整合完成!
开始运行web项目—>右键web->Run as->Run configurations->
左侧选择Maven Build
右侧在Name出填写你的name
在Main页的Base directory出选择web项目,在Goals出输入 tomcat7:run
在JRE页选择你自己的jdk
然后切换到Main页,点击Run。
如果没有报错或者异常,应该就没问题了!
然后springmvc测试
在浏览器上输入网址http://localhost:8080/web/user/showUser?id=1就会返回到User.jsp页面。如图:
json测试:输入网址http://localhost:8080/web/user/showJson?id=1返回结果:
OK!
九、总结
以上就是最近整合的springmvc+mybatis+json的Maven管理一整套项目!是我亲自一步步搭建成功!
如果大家发现有什么问题,欢迎指正批评!
如果想要转载,请加载转载地址【http://www.cnblogs.com/gwx238044/articles/6633252.html】!