idea spring+springmvc+mybatis环境配置整合详解
1.配置整合前所需准备的环境:
1.1:jdk1.8
1.2:idea2017.1.5
1.3:Maven 3.5.2
2.查看idea中是否安装Maven插件:
2.1:File --> Settings --> Plugins
2.2:如下图所示的步骤进行操作(注:安装完插件,idea会重新启动)
3.
3.idea创建Maven项目的步骤
4.搭建目录结构
下图就是我搭建Maven项目之后,添加对应的目录和文件
5.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>com.chen.web</groupId>
<artifactId>MaevnDemo</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>MaevnDemo Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- spring版本号 -->
<spring.version>4.2.5.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.8</mybatis.version>
<!-- mysql驱动版本号 -->
<mysql-driver.version>5.1.29</mysql-driver.version>
<!-- log4j日志包版本号 -->
<slf4j.version>1.7.18</slf4j.version>
<log4j.version>1.2.17</log4j.version>
</properties>
<dependencies>
<!-- 添加jstl依赖 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<!-- 添加junit4依赖 -->
<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-context</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-aop</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.3.0</version>
</dependency>
<!-- 添加mysql驱动依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-driver.version}</version>
</dependency>
<!-- 添加数据库连接池依赖 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<!-- 添加fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</version>
</dependency>
<!-- 添加日志相关jar包 -->
<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 -->
<!-- 映入JSON -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.0</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>
</dependencies>
<build>
</build>
</project>
6.jdbc.properties配置文件
#驱动
driverClasss=com.mysql.jdbc.Driver
#链接地址 db_tosys:数据库名称
jdbcUrl=jdbc:mysql://localhost:3306/db_tosys?useUnicode=true&characterEncoding=utf-8
#数据库用户名
username=root
#数据库密码
password=root
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000
7.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 自动扫描 -->
<context:component-scan base-package="com.chen.ssm"/>
<!-- 第一种方式:加载一个properties文件 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties"/>
</bean>
<!-- 第二种方式:加载多个properties文件
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<value>classpath:common.properties</value>
</list>
</property>
<property name="fileEncoding" value="UTF-8"/>
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="configProperties"/>
</bean>
-->
<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driverClasss}"/>
<property name="url" value="${jdbcUrl}"/>
<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>
<!-- mybatis和spring完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath*:mapper/*.xml"></property>
</bean>
<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.chen.ssm.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>
<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
8..进行web.xml的配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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>web-ssm</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>
<!-- 编码过滤器 -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 防止spring内存溢出监听器,比如quartz -->
<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 形式 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 设置默认的启动时的初始页面-->
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
<!-- session配置 设置session会话的超时时间 -->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
9.配置类:UserController
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@RequestMapping("/test")
public String test() {
return "list";
}
@RequestMapping("/index")
public String index() {
return "login";
}
@RequestMapping("/login")
public String login(User user, HttpServletRequest request) {
User loginUser = userService.login(user);
if (loginUser != null) {
request.getSession().setAttribute("userName",loginUser.getUsername());
return "success";
}
request.getSession().setAttribute("message","用户名或密码有误!!!");
System.out.println(loginUser.getUsername());
return "login";
}
}
10.配置类:IUserDao
public interface IUserDao {
User login(User user);
User selectByPrimaryKey(Integer id);
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}
11.实体类:User.java
public class User {
private Integer id;
private String email;
private String password;
private String phone;
private String sex;
private String sfz;
private String truename;
private String username;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email == null ? null : email.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone == null ? null : phone.trim();
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex == null ? null : sex.trim();
}
public String getSfz() {
return sfz;
}
public void setSfz(String sfz) {
this.sfz = sfz == null ? null : sfz.trim();
}
public String getTruename() {
return truename;
}
public void setTruename(String truename) {
this.truename = truename == null ? null : truename.trim();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
}
12.UserService
public interface UserService {
User login(User user);
User getUserById(String id);
void add(User user);
void update(User user);
}
13.IUserService
@Service("userService")
public class IUserService implements UserService {
@Autowired
private IUserDao userDao;
public User login(User user) {
return userDao.login(user);
}
public User getUserById(String id) {
return userDao.selectByPrimaryKey(Integer.parseInt(id));
}
public void add(User user) {
}
public void update(User user) {
}
}
14.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" >
<mapper namespace="com.chen.ssm.dao.IUserDao" >
<resultMap id="BaseResultMap" type="com.chen.ssm.entity.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="email" property="email" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="phone" property="phone" jdbcType="VARCHAR" />
<result column="sex" property="sex" jdbcType="VARCHAR" />
<result column="sfz" property="sfz" jdbcType="VARCHAR" />
<result column="trueName" property="truename" jdbcType="VARCHAR" />
<result column="userName" property="username" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List" >
id, email, password, phone, sex, sfz, trueName, userName
</sql>
<select id="login" resultMap="BaseResultMap" parameterType="com.chen.ssm.entity.User">
SELECT <include refid="Base_Column_List"/> FROM t_user WHERE userName = #{username,jdbcType=VARCHAR} and password = #{password,jdbcType=VARCHAR}
</select>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from t_user
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from t_user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.chen.ssm.entity.User" >
insert into t_user (id, email, password,
phone, sex, sfz, trueName,
userName)
values (#{id,jdbcType=INTEGER}, #{email,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{phone,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR}, #{sfz,jdbcType=VARCHAR}, #{truename,jdbcType=VARCHAR},
#{username,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.chen.ssm.entity.User" >
insert into t_user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="email != null" >
email,
</if>
<if test="password != null" >
password,
</if>
<if test="phone != null" >
phone,
</if>
<if test="sex != null" >
sex,
</if>
<if test="sfz != null" >
sfz,
</if>
<if test="truename != null" >
trueName,
</if>
<if test="username != null" >
userName,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="email != null" >
#{email,jdbcType=VARCHAR},
</if>
<if test="password != null" >
#{password,jdbcType=VARCHAR},
</if>
<if test="phone != null" >
#{phone,jdbcType=VARCHAR},
</if>
<if test="sex != null" >
#{sex,jdbcType=VARCHAR},
</if>
<if test="sfz != null" >
#{sfz,jdbcType=VARCHAR},
</if>
<if test="truename != null" >
#{truename,jdbcType=VARCHAR},
</if>
<if test="username != null" >
#{username,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.chen.ssm.entity.User" >
update t_user
<set >
<if test="email != null" >
email = #{email,jdbcType=VARCHAR},
</if>
<if test="password != null" >
password = #{password,jdbcType=VARCHAR},
</if>
<if test="phone != null" >
phone = #{phone,jdbcType=VARCHAR},
</if>
<if test="sex != null" >
sex = #{sex,jdbcType=VARCHAR},
</if>
<if test="sfz != null" >
sfz = #{sfz,jdbcType=VARCHAR},
</if>
<if test="truename != null" >
trueName = #{truename,jdbcType=VARCHAR},
</if>
<if test="username != null" >
userName = #{username,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.chen.ssm.entity.User" >
update t_user
set email = #{email,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
phone = #{phone,jdbcType=VARCHAR},
sex = #{sex,jdbcType=VARCHAR},
sfz = #{sfz,jdbcType=VARCHAR},
trueName = #{truename,jdbcType=VARCHAR},
userName = #{username,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
15.建立一个测试类,用于测试mybatis,类名:TestMybatis.java
@RunWith(SpringJUnit4ClassRunner.class) //表示继承了SpringJUnit4ClassRunner类
@ContextConfiguration(locations = {"classpath*:spring-mvc.xml","classpath*:spring-mybatis.xml"})
public class TestMybatis {
private static Logger logger = Logger.getLogger(TestMybatis.class);
@Autowired
private IUserDao dao;
@Test
public void testSelectUser() throws Exception {
Integer id = 1;
User user = dao.selectByPrimaryKey(id);
System.out.println(user.getUsername());
}
}
如下图所示,则说明我们mybatis的配置是正确的!!!
16.配置项目的运行环境
17.接着新建一个jsp页面(index.jsp),来测试springmvc+mybatis+spring的整合
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登陆界面</title>
<script type="text/javascript">
// window.location.href = "http://localhost:8080/MavenDemo/user/index";
// window.location.href = "${pageContext.request.contextPath}/user/index";
</script>
</head>
<body>
<h1>hello world!!!</h1>
<form action="${pageContext.request.contextPath}/user/login">
用户名:<input type="text" name="username"><br>
密 码:<input type="password" name="password"><br>
<input type="submit" value="submit"/>
</form>
</body>
</html>
18.成功之后的跳转界面(loginSuccess.jsp)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>信息界面</title>
</head>
<body>
<div style="padding-left: 10px;">
<div class="panel panel-default">
<div class="panel-heading" style="font-size: 18px;">用户信息</div>
<table class="table" style="text-align: center;">
<thead>
<tr style="text-align: center;">
<th style="width: 45px;">编号</th>
<th style="width: 75px;">用户名</th>
<th style="width: 75px;">密码</th>
<th style="width: 145px;">真实姓名</th>
<th style="width: 45px;">性别</th>
<th style="width: 145px;">邮件</th>
<th style="width: 145px;">联系电话</th>
</tr>
</thead>
<tbody>
<tr>
<td>${currentUser.id }</td>
<td>${currentUser.username}</td>
<td>${currentUser.password }</td>
<td>${currentUser.truename }</td>
<td>${currentUser.sex }</td>
<td>${currentUser.email }</td>
<td>${currentUser.phone }</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
源码分享链接地址:enter description here 密码:tt6e
注:SpringMvc+Spring+Mybatis Maven的整合到此,已经整合完成了,再次过程中主要参考的https://www.cnblogs.com/hackyo/p/6646051.html 此篇博文的文章,在整合的过程当中也踩到一些坑,最终还是趟过了,在此就不列举出来,提醒下关于Mybatis的.xml数据库操作的配置文件,在此篇博文中需要存放在resources目录底下(不然项目测试的时候报错,也是搜索网上的博文得知,具体博文地址不记得了)