欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

搭建SpringMVC + Spring + Mybatis 框架

程序员文章站 2022-06-13 20:48:21
...

参考博文: http://blog.csdn.net/zhshulin , http://blog.csdn.net/zhshulin/article/details/37956105

使用工具:Eclipse 4.5.1

一、使用maven创建项目工程结构

搭建SpringMVC + Spring + Mybatis 框架

搭建SpringMVC + Spring + Mybatis 框架

搭建SpringMVC + Spring + Mybatis 框架

搭建SpringMVC + Spring + Mybatis 框架

搭建SpringMVC + Spring + Mybatis 框架

到目前为止一个新的项目已经创建完毕了,但是项目结构是错误的,需要稍作调整。

首先将大项目的字符集调整为UTF-8。

搭建SpringMVC + Spring + Mybatis 框架

接下来调整下jre

搭建SpringMVC + Spring + Mybatis 框架

搭建SpringMVC + Spring + Mybatis 框架

将jre调整为默认的Java SE 8后,项目结构自动变正确了。

搭建SpringMVC + Spring + Mybatis 框架

到目前为止项目结构就创建好了。

二、整合SSM框架

1⃣️引入需要的JAR包

打开pom文件

搭建SpringMVC + Spring + Mybatis 框架

可以看到系统生成的pom文件如上图所示,接下来将以下jar包引入系统。

<properties>
		<!-- 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>
<!-- 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>
		</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>
保存pom后可以看到eclipse右下角在Building 

搭建SpringMVC + Spring + Mybatis 框架

点开可以查看系统正在下载引入的jar包

搭建SpringMVC + Spring + Mybatis 框架

2⃣️整合Spring 与 MyBatis

搭建SpringMVC + Spring + Mybatis 框架

定义包与文件夹具体结构:这边我新建了几个包与一个mapper文件夹,com.jerry是总包,下面又分为project与core,project打算放关于此项目的一些文件,core放项目的核心文件,比如:一些工具类等等,目的是可以移植到其他项目上使用。dal里面放Mapper接口,param放请求参数对象...src/main/resources下面的mapper放的是Mapper的xml文件。

创建框架相关文件:第一个文件就是在src/main/resources下新建一个jdbc.properties文件,代码如下:

test.driverClass=com.mysql.jdbc.Driver
test.jdbcUrl=jdbc:mysql://120.26.201.213:3306/warehouse?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
test.user=111
test.password=2222
 
##################################DETAIL CONFIG##################################
datasource.initialSize=1
datasource.maxActive=30
datasource.maxIdle=2
datasource.minIdle=1
datasource.whenExhaustedAction=1
datasource.validationQuery=select 1 from dual
datasource.testOnBorrow=true
datasource.testOnReturn=false
datasource.testWhileIdle=true·
datasource.logAbandoned=false
datasource.removeAbandoned=false
datasource.removeAbandonedTimeout=10
datasource.maxWait=1000
datasource.timeBetweenEvictionRunsMillis=10000
datasource.numTestsPerEvictionRun=10
datasource.minEvictableIdleTimeMillis=10000

第二个文件是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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	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/aop
			http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
			http://www.springframework.org/schema/tx
			http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
			http://www.springframework.org/schema/mvc
			http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

	<!-- 1.配置MyBatis自动扫描,将Mapper接口生成代理注入到Spring -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 为MapperScannerConfigurer类的属性basePackage 设置值,也就是指定Mapper文件所在包名 -->
		<property name="basePackage" value="com.jerry.project.dal" />

		<!-- 配置会话工厂 -->
		<property name="sqlSessionFactoryBeanName" value="sqlSessionTemplate" />
	</bean>


	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 配置数据源 -->
		<property name="dataSource" ref="dbSource" />

		<!-- 自动扫描mapper.xml文件,这边扫描的是src/main/resources/mapper文件夹 -->
		<property name="mapperLocations">
			<list>
				<value>classpath:/mapper/*.xml</value>
			</list>
		</property>
	</bean>

	<!-- spring对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
	<context:component-scan base-package="com.jerry" />

	<!-- 加载jdbc配置文件 -->
	<context:property-placeholder location="classpath:jdbc.properties" />

	<!-- 配置数据库连接 -->
	<bean id="dbSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="${test.driverClass}" />
		<property name="url" value="${test.jdbcUrl}" />
		<!-- 数据库用户名 -->
		<property name="username" value="${test.user}" />
		<!-- 数据库密码 -->
		<property name="password" value="${test.password}" />
		<!-- 连接池启动时的初始值 -->
		<property name="initialSize" value="${datasource.initialSize}" />
		<!-- 连接池的最大值 -->
		<property name="maxActive" value="${datasource.maxActive}" />
		<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
		<property name="maxIdle" value="${datasource.maxIdle}" />
		<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
		<property name="minIdle" value="${datasource.minIdle}" />

		<!-- 连接被泄露时是否打印 -->
		<property name="logAbandoned" value="${datasource.logAbandoned}" />
		<!--removeAbandoned: 是否自动回收超时连接 -->
		<property name="removeAbandoned" value="${datasource.removeAbandoned}" />
		<!--removeAbandonedTimeout: 超时时间(以秒数为单位) -->
		<property name="removeAbandonedTimeout" value="${datasource.removeAbandonedTimeout}" />
		<!--maxWait: 超时等待时间以毫秒为单位 1000等于60秒 -->
		<property name="maxWait" value="${datasource.maxWait}" />
		<!-- 在空闲连接回收器线程运行期间休眠的时间值,以毫秒为单位. -->
		<property name="timeBetweenEvictionRunsMillis" value="${datasource.timeBetweenEvictionRunsMillis}" />
		<!-- 在每次空闲连接回收器线程(如果有)运行时检查的连接数量 -->
		<property name="numTestsPerEvictionRun" value="${datasource.numTestsPerEvictionRun}" />
		<!-- 1000 * 60 * 30 连接在池中保持空闲而不被空闲连接回收器线程 -->
		<property name="minEvictableIdleTimeMillis" value="${datasource.minEvictableIdleTimeMillis}" />
		<property name="validationQuery" value="${datasource.validationQuery}" />

	</bean>


</beans>
看spring-mybatis.xml代码要与项目的包名联系在一起看。
以上两个文件可以说完成了Spring与MyBatis的大部分整合工作了,接下来使用Junit测试配置是否正确。

3⃣️测试Spring与MyBatis整合是否成功

1.创建简单的用户表:

CREATE TABLE `user` (
  `ID` varchar(32) NOT NULL COMMENT '主键',
  `USER_NAME` varchar(500) NOT NULL COMMENT '登录名',
  `PASSWORD` varchar(200) NOT NULL COMMENT '密码',
  `NICK_NAME` varchar(500) NOT NULL COMMENT '昵称',
  `TYPE` tinyint(1) NOT NULL COMMENT '类型(1=超管 2=普通用户)',
  `SEX` varchar(10) DEFAULT NULL COMMENT '性别',
  `VERSION` bigint(20) NOT NULL DEFAULT '0' COMMENT '版本号',
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户';

插入一条数据:

INSERT INTO `user` (`ID`, `USER_NAME`, `PASSWORD`, `NICK_NAME`, `TYPE`, `SEX`, `VERSION`)
VALUES
('3bd1c041327d463cba80388d91e93eda', 'admin', '1111', '张龙', 0, '男', 1);

2.编写数据库方面的代码

在dal包中新建UserMapper接口

package com.jerry.project.dal;

import org.apache.ibatis.annotations.Param;

import com.jerry.project.vo.UserVO;

/**
 * 
 * UserMapper数据库操作接口类
 * 
 **/

public interface UserMapper {

	// @Param("id") 中的id 与 xml中的id对应
	UserVO queryById(@Param("id") String id);

}

在src/main/resources/mapper中定义UserMapper.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">
<!-- namespace 指向Mapper接口 -->
<mapper namespace="com.jerry.project.dal.UserMapper">

	<!-- 将数据库字段与VO做影射,自动组装VO对象 -->
	<resultMap id="tableColunmsMap" type="com.jerry.project.vo.UserVO">
		<!-- column 是数据库字段名,property是vo属性名, jdbcType是数据类型 -->
		<id column="ID" jdbcType="VARCHAR" property="id" />
		<result column="USER_NAME" jdbcType="VARCHAR" property="userName"></result>
		<result column="PASSWORD" jdbcType="VARCHAR" property="password"></result>
		<result column="NICK_NAME" jdbcType="VARCHAR" property="nickName"></result>
		<result column="TYPE" jdbcType="NUMERIC" property="type"></result>
		<result column="SEX" jdbcType="VARCHAR" property="sex"></result>
		<result column="VERSION" jdbcType="NUMERIC" property="version"></result>
	</resultMap>

	<!-- 定义数据库字段 -->
	<sql id="tableColunms">
		ID,USER_NAME,PASSWORD,NICK_NAME,TYPE,SEX,VERSION
	</sql>

	<!-- 查询 -->
	<select id="queryById" resultMap="tableColunmsMap">
		SELECT
		<include refid="tableColunms" />
		FROM user
		WHERE ID = #{ id }
	</select>

</mapper>

3编写业务代码

在vo包中创建用户Class名为UserVO:

package com.jerry.project.vo;

/**
 * 
 * 用户
 * 
 **/
public class UserVO {

	/**
	 * 主键
	 */
	private String id;

	/**
	 * 登录名
	 */
	private String userName;

	/**
	 * 密码
	 */
	private String password;

	/**
	 * 昵称
	 */
	private String nickName;

	/**
	 * 类型(1=超管 2=普通用户)
	 */
	private Integer type;

	/**
	 * 性别
	 */
	private String sex;

	/**
	 * 版本号
	 */
	private Long version;

	public void setId(String id) {
		this.id = id;
	}

	public String getId() {
		return this.id;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserName() {
		return this.userName;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPassword() {
		return this.password;
	}

	public void setNickName(String nickName) {
		this.nickName = nickName;
	}

	public String getNickName() {
		return this.nickName;
	}

	public void setType(Integer type) {
		this.type = type;
	}

	public Integer getType() {
		return this.type;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getSex() {
		return this.sex;
	}

	public void setVersion(Long version) {
		this.version = version;
	}

	public Long getVersion() {
		return this.version;
	}

}

在service包里新建一个IUserService接口:

package com.jerry.project.service;

import com.jerry.project.vo.UserVO;

/**
 * @author JiaJiCheng
 * @date 2017年9月23日 下午9:29:31
 * 
 */
public interface IUserService {
	// 根据ID查询用户信息
	UserVO queryUserById(String id);
}

再新建一个UserServiceImpl实现类

package com.jerry.project.service.impl;

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

import com.jerry.project.dal.UserMapper;
import com.jerry.project.service.IUserService;
import com.jerry.project.vo.UserVO;

/**
 * @author JiaJiCheng
 * @date 2017年9月23日 下午9:29:53
 * 
 */

@Service("userServiceImpl")
public class UserServiceImpl implements IUserService {

	@Autowired
	private UserMapper userMapper;

	public UserVO queryUserById(String id) {
		return userMapper.queryById(id);
	}

}

4.测试

在src/test/main中新建com.test包,然后新建UserTest类

package com.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.jerry.project.service.IUserService;
import com.jerry.project.service.impl.UserServiceImpl;
import com.jerry.project.vo.UserVO;

/**
 * @author JiaJiCheng
 * @date 2017年9月23日 下午9:33:28
 * 
 */

@RunWith(SpringJUnit4ClassRunner.class) // 表示继承了SpringJUnit4ClassRunner类
@ContextConfiguration(locations = { "classpath:spring-mybatis.xml" })
public class UserTest {
	@Autowired
	private IUserService userServiceImpl;

	@Test
	public void test() {
		String userId = "3bd1c041327d463cba80388d91e93eda";
		UserVO userVO = userServiceImpl.queryUserById(userId);
		System.out.println("用户名:" + userVO.getUserName() + "昵称:" + userVO.getNickName());
	}

}

如果运行后如下图则说明配置成功了:

搭建SpringMVC + Spring + Mybatis 框架


三、整合Spring MVC

在src/main/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">

	<!-- spring-mvc 对包进行扫描,为了找到控制器,进行路由转发 -->
	<context:component-scan base-package="com.jerry.project.controller" />

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

	<!--避免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>

	<!-- 定义跳转的文件的前后缀 ,视图模式配置 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 配置默认返回前缀 -->
		<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>

配置web.xml文件,整合SSM框架:

web容器加载项目时首先会读取web.xml文件,为了初始化SSM框架,需要将SSM框架的两个配置文件告诉web容器,需要它加载。

<?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>

	<!-- Spring监听器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- 防止Spring内存溢出监听器 -->
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>

	<!-- 配置编码过滤器,对所有request请求都会过滤 -->
	<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 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.jsp</welcome-file>
	</welcome-file-list>

</web-app>


整体框架测试

在com.jerry包下新建controller包,在controller包中新建UserController类:

package com.jerry.project.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.web.bind.annotation.RequestMapping;

import com.jerry.project.service.IUserService;
import com.jerry.project.vo.UserVO;

/**
 * @author JiaJiCheng
 * @date 2017年9月24日 上午8:13:57
 * 
 */
@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private IUserService userServiceImpl;

	@RequestMapping("/queryUser")
	public String queryUser(HttpServletRequest request, Model model) {
		String userId = request.getParameter("id");
		UserVO userVO = userServiceImpl.queryUserById(userId);
		model.addAttribute("user", userVO);
		return "test"; // 地址:/WEB-INF/jsp/test.jsp
	}
}

在WEB-INF下新建jsp文件夹,在jsp文件夹下新建test.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>test</title>
</head>
<body>
	欢迎:${user.userName },登录成功!
</body>
</html>

部署项目,启动项目

在浏览器中输入:http://localhost:8080/项目名称/user/queryUser?id=3bd1c041327d463cba80388d91e93eda

搭建SpringMVC + Spring + Mybatis 框架

到目前为止,SSM就已经整合完毕了。

四、配置Log4j

在src/main/resources下新建 log4j.properties

log4j.rootLogger=INFO,console,file
log4j.appender.console=org.apache.log4j.ConsoleAppender 
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d %5p [%t] (%F:%L) - %m%n
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss} [%c]-[%p] %m%n 
log4j.appender.file=org.apache.log4j.RollingFileAppender 
log4j.appender.file.File=${catalina.home}/logs/testSpring.log
log4j.appender.file.MaxBackupIndex=1000
log4j.appender.file.MaxFileSize=10240KB

源码下载地址:https://coding.net/s/488a1812-2a63-4a29-9ca8-ef2ae36f3984