springmvc+spring+mybatis+Maven+mysql环境搭建,附源码

文章目录

    • 一、准备工作
    • 二、工程创建
    • 三、sping+mybatis配置
    • 四、单元测试
    • 五、转换web工程
    • 六、配置SpringMVC

摘要:本文主要讲了如何使用Maven来搭建Spring+Mybatis+SpringMVC+MySql的搭建实例,文章写得很详细,有代码有图片,最后也带有运行的效果。如果报的错误太多并且难以修改,可以参照本文档最后提供的源码。

一、准备工作

CREATE TABLE `t_user` (
`USER_ID` int(11) NOT NULL AUTO_INCREMENT,
`USER_NAME` char(30) NOT NULL,
`USER_PASSWORD` char(10) NOT NULL,
`USER_EMAIL` char(30) NOT NULL,
PRIMARY KEY (`USER_ID`),
KEY `IDX_NAME` (`USER_NAME`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8

INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (1, 'cehkongfu', '1234567@', '[email protected]');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (2, 'evan', '123', '[email protected]');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (3, 'kaka', 'cadg', '[email protected]');

二、工程创建

1、Maven工程创建
(1)新建
springmvc+spring+mybatis+Maven+mysql环境搭建,附源码_第1张图片
(2)选择快速框架
springmvc+spring+mybatis+Maven+mysql环境搭建,附源码_第2张图片
(3)输出项目名,包,记得选war(表示web项目,以后可以spingMVC连起来用)
springmvc+spring+mybatis+Maven+mysql环境搭建,附源码_第3张图片
(4)创建好之后
目录如下:
springmvc+spring+mybatis+Maven+mysql环境搭建,附源码_第4张图片
springmvc+spring+mybatis+Maven+mysql环境搭建,附源码_第5张图片
项目报错,将后文中的pom.xml内容拷贝进来,然后执行maven->Update Project错误即可消失。

三、sping+mybatis配置

1、整个工程目录如下:
springmvc+spring+mybatis+Maven+mysql环境搭建,附源码_第6张图片
2、POM文件

<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.0modelVersion>
    <groupId>com.cehgroupId>
    <artifactId>ssmMavenartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <packaging>warpackaging>
    
    <properties>
        
        <spring.version>3.2.2.RELEASEspring.version>
        
        <slf4j.version>1.6.6slf4j.version>
        <log4j.version>1.2.12log4j.version>
          
        <junit.version>4.10junit.version>  
          
        <mybatis.version>3.2.1mybatis.version>  
        <java-version>1.7java-version>
    properties>  
  
    <dependencies>  
          
        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-coreartifactId>  
            <version>${spring.version}version>  
        dependency>  
        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-webmvcartifactId>  
            <version>${spring.version}version>  
        dependency>  
        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-contextartifactId>  
            <version>${spring.version}version>  
        dependency>  
        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-context-supportartifactId>  
            <version>${spring.version}version>  
        dependency>  
        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-aopartifactId>  
            <version>${spring.version}version>  
        dependency>  
        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-aspectsartifactId>  
            <version>${spring.version}version>  
        dependency>  
        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-txartifactId>  
            <version>${spring.version}version>  
        dependency>  
        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-jdbcartifactId>  
            <version>${spring.version}version>  
        dependency>  
        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-webartifactId>  
            <version>${spring.version}version>  
        dependency>  
  
          
        <dependency>  
            <groupId>junitgroupId>  
            <artifactId>junitartifactId>  
            <version>${junit.version}version>  
            <scope>testscope>  
        dependency>  
  
          
          
        <dependency>  
            <groupId>log4jgroupId>  
            <artifactId>log4jartifactId>  
            <version>${log4j.version}version>  
        dependency>  
        <dependency>  
            <groupId>org.slf4jgroupId>  
            <artifactId>slf4j-apiartifactId>  
            <version>${slf4j.version}version>  
        dependency>  
        <dependency>  
            <groupId>org.slf4jgroupId>  
            <artifactId>slf4j-log4j12artifactId>  
            <version>${slf4j.version}version>  
        dependency>  
          
  
          
        <dependency>  
            <groupId>org.springframeworkgroupId>  
            <artifactId>spring-testartifactId>  
            <version>${spring.version}version>  
            <scope>testscope>  
        dependency>  
  
          
        <dependency>  
            <groupId>org.mybatisgroupId>  
            <artifactId>mybatisartifactId>  
            <version>${mybatis.version}version>  
        dependency>  
  
          
        <dependency>  
            <groupId>org.mybatisgroupId>  
            <artifactId>mybatis-springartifactId>  
            <version>1.2.0version>  
        dependency>  
  
          
        <dependency>  
            <groupId>mysqlgroupId>  
            <artifactId>mysql-connector-javaartifactId>  
            <version>5.1.29version>
        dependency>
        
          
		<dependency>  
		    <groupId>javaxgroupId>  
		    <artifactId>javaee-apiartifactId>  
		    <version>6.0version>  
		    <scope>providedscope>  
		dependency>  
		  
		  
		<dependency>  
		    <groupId>javaxgroupId>  
		    <artifactId>javaee-web-apiartifactId>  
		    <version>6.0version>  
		    <scope>providedscope>  
		dependency>  
    dependencies>
  
	<build>
		<plugins>
		    <plugin>
	            <groupId>org.apache.maven.pluginsgroupId>
	            <artifactId>maven-war-pluginartifactId>
	            <version>2.6version>
	            <configuration>
	                <failOnMissingWebXml>falsefailOnMissingWebXml>
	            configuration>
        	plugin>
		
			<plugin>
				<artifactId>maven-compiler-pluginartifactId>
				<configuration>
					<encoding>UTF-8encoding>
					<source>1.7source>
					<target>1.7target>
				configuration>
			plugin>
		plugins>
	build>
project>

(1)User.java
对应数据库中表的字段,放在src/main/java下的包com.ceh.domain

package com.ceh.domain;  
  
/** 
 * User映射类 
 *  
 * @author cehkongfu 
 * @time 2018年3月12日
 */  
public class User {  
    private Integer userId;  
    private String userName;  
    private String userPassword;  
    private String userEmail;  
  
    public Integer getUserId() {  
        return userId;  
    }  
  
    public void setUserId(Integer userId) {  
        this.userId = userId;  
    }  
  
    public String getUserName() {  
        return userName;  
    }  
  
    public void setUserName(String userName) {  
        this.userName = userName;  
    }  
  
    public String getUserPassword() {  
        return userPassword;  
    }  
  
    public void setUserPassword(String userPassword) {  
        this.userPassword = userPassword;  
    }  
  
    public String getUserEmail() {  
        return userEmail;  
    }  
  
    public void setUserEmail(String userEmail) {  
        this.userEmail = userEmail;  
    }  
  
    @Override  
    public String toString() {  
        return "User [userId=" + userId + ", userName=" + userName  
                + ", userPassword=" + userPassword + ", userEmail=" + userEmail  
                + "]";  
    }  
      
}  

(2)UserDao.java
Dao接口类,用来对应mapper文件。放在src/main/java下的包com.ceh.dao,内容如下:

package com.ceh.dao;
  
  
import com.ceh.domain.User;
/**
 * 功能概要:User的DAO类
 * 
 * @author cehkongfu
 * @since 2018年3月12日
 */
public interface UserDao {
    /**
     * @author cehkongfu
     * @since 2018年3月12日
     * @param userId
     * @return
     */
    public User selectUserById(Integer userId);
} 

(2)UserService.java和UserServiceImpl.java
service接口类和实现类,放在src/main/java下的包com.ceh.service,内容如下:
UserService.java

package com.ceh.service;
  
import com.ceh.domain.User;  
  
/** 
 * 功能概要:UserService接口类 
 *  
 * @author cehkongfu 
 * @since  2018年3月12日 
 */  
public interface UserService {  
    User selectUserById(Integer userId);  
}  

UserServiceImpl.java

package com.ceh.service;  
  
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ceh.dao.UserDao;
import com.ceh.domain.User;  
  
/** 
 * 功能概要:UserService实现类 
 *  
 * @author cehkongfu 
 * @since  2018年3月12日 
 */  
@Service  
public class UserServiceImpl implements UserService{  
    @Autowired  
    private UserDao userDao;  
  
    public User selectUserById(Integer userId) {  
        return userDao.selectUserById(userId);     
    }  
}  

(4)mapper文件
用来和dao文件对应,放在src/main/java下的com.ceh.mapper包下

    
  
<mapper namespace="com.ceh.dao.UserDao">
  
    <resultMap id="BaseResultMap" type="com.ceh.domain.User">  
        <id column="USER_ID" property="userId" jdbcType="INTEGER" />  
        <result column="USER_NAME" property="userName" jdbcType="CHAR" />  
        <result column="USER_PASSWORD" property="userPassword" jdbcType="CHAR" />  
        <result column="USER_EMAIL" property="userEmail" jdbcType="CHAR" />  
    resultMap>
    
      
    <select id="selectUserById" parameterType="int" resultMap="BaseResultMap">  
        SELECT * FROM t_user WHERE USER_ID = #{userId}  
    select>  
mapper>

4、资源配置-------src/main/resources
目录如下:
springmvc+spring+mybatis+Maven+mysql环境搭建,附源码_第7张图片
(1)mybatis配置文件
因为都被放到application.xml中去了,放在src/main/resources下的mybatis文件夹下, 虽然这里没有什么内容,但是可以用于后面功能扩展。
mybatis-config.xml内容如下:

    
    
<configuration>      
configuration>

(2)数据源配置jdbc.properties
放在src/main/resources下的properties文件夹下

jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/new
jdbc_username=root
jdbc_password=sorry

(3)Spring配置
这是最重要的:application.xml内容如下

  
<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:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
           http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd    
           http://www.springframework.org/schema/aop    
           http://www.springframework.org/schema/aop/spring-aop-3.2.xsd  
           http://www.springframework.org/schema/context    
           http://www.springframework.org/schema/context/spring-context-3.2.xsd">  
       
         
     <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="locations">  
            <list>  
               <value>classpath:properties/*.propertiesvalue>  
                  
            list>  
        property>  
    bean>
  
    
    <bean id="dataSource"  
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
          
          
         
        <property name="driverClassName">  
            <value>${jdbc_driverClassName}value>  
        property>  
        <property name="url">  
            <value>${jdbc_url}value>  
        property>  
        <property name="username">  
            <value>${jdbc_username}value>  
        property>  
        <property name="password">  
            <value>${jdbc_password}value>  
        property>
	bean>
  
    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.ceh.dao" />
    bean>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath*:com/ceh/mapper/*.xml"/>
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
        
    bean>
  
      
    <context:component-scan base-package="com.ceh.service" />  
beans>  

(4)日志打印log4j.properties
就放在src/main/resources

log4j.rootLogger=DEBUG,Console,Stdout

#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n

log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

log4j.appender.Stdout = org.apache.log4j.DailyRolcehgFileAppender
log4j.appender.Stdout.File = D://logs/log.log
log4j.appender.Stdout.Append = true
log4j.appender.Stdout.Threshold = DEBUG
log4j.appender.Stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.Stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

四、单元测试

上面的配置完好,接下来就是测验成功
整个目录 如下:
springmvc+spring+mybatis+Maven+mysql环境搭建,附源码_第8张图片
(1)测试基类

package com.ceh.baseTest;  
  
import org.junit.runner.RunWith;  
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
import org.springframework.test.context.ContextConfiguration;  
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;  
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  
/** 
 * 功能概要: 
 *  
 * @author cehkongfu 
 * @since  2018年3月12日 
 */  
//指定bean注入的配置文件  
@ContextConfiguration(locations = { "classpath*:application.xml" })  
//使用标准的JUnit @RunWith注释来告诉JUnit使用Spring TestRunner  
@RunWith(SpringJUnit4ClassRunner.class)  
public abstract class SpringTestCase extends AbstractJUnit4SpringContextTests{  
    protected Logger logger = LoggerFactory.getLogger(getClass());  
}  

(2)测试类

package com.ceh.service;  
  
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.ceh.baseTest.SpringTestCase;
import com.ceh.domain.User;  

/**
 * 功能概要:UserService单元测试
 *
 * @author cehkongfu
 * @since  2015年9月28日
 */
public class UserServiceTest extends SpringTestCase {
    @Autowired
    private UserService userService;
    Logger logger = Logger.getLogger(UserServiceTest.class);

    @Test
    public void selectUserByIdTest(){
        User user = userService.selectUserById(10);
        logger.debug("查找结果" + user);
    }
}

选中selectUserByIdTest,然后右键如下运行
springmvc+spring+mybatis+Maven+mysql环境搭建,附源码_第9张图片

重要打印的结果
springmvc+spring+mybatis+Maven+mysql环境搭建,附源码_第10张图片
数据库:
springmvc+spring+mybatis+Maven+mysql环境搭建,附源码_第11张图片
程序成功运行,并且结果正确!

到这里配置好spring+mybatis+mysql

======================================

这里开始添加spirngMVC,并转换maven工程为web项目

五、转换web工程

接上面的工程接着说,此时要加spingMVC之前,工程得再稍微转换下
此时webapp下的结果还没有显示出来,因为此时我们还没有配置此的项目为web项目
springmvc+spring+mybatis+Maven+mysql环境搭建,附源码_第12张图片

再次进去Properties配置,如下图所示:如果没有显示如下,那就先把dynamic web module的√给去掉,然后重新再打开这个
springmvc+spring+mybatis+Maven+mysql环境搭建,附源码_第13张图片
进入,然后输入如下内容
springmvc+spring+mybatis+Maven+mysql环境搭建,附源码_第14张图片
确定OK之后,webapp下面就会自动生成一些文件,如下
springmvc+spring+mybatis+Maven+mysql环境搭建,附源码_第15张图片

六、配置SpringMVC

(1)修改POM文件,增加了一此内容, 增加了下面两个:

  
 	<dependency>
 		<groupId>javaxgroupId>
 		<artifactId>javaee-apiartifactId>
 		<version>6.0version>
 		<scope>providedscope>
 	dependency>

 	
 	<dependency>
 		<groupId>javaxgroupId>
 		<artifactId>javaee-web-apiartifactId>
 		<version>6.0version>
 		<scope>providedscope>
 	dependency>

(2) 在src/main/resource中添加springmvc文件夹,然后添加文件spring-mvc.xml,内容如下:

  
<beans xmlns="http://www.springframework.org/schema/beans"  
  xmlns:p="http://www.springframework.org/schema/p"  
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  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.2.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.2.xsd  
    http://www.springframework.org/schema/mvc  
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">  
       
      
   <context:component-scan base-package="com.ceh.controller"/>    
       
     
   <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"  
   p:prefix="/WEB-INF/view/" p:suffix=".jsp"/>  
beans>

(3)配置web,xml
目录如下 :
springmvc+spring+mybatis+Maven+mysql环境搭建,附源码_第16张图片
这里是关键,web.xml是用来起动sping、spingMVC
放在src/main/webapp/WEB-INF下。内容如下:


<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
    <display-name>Archetype Created Web Applicationdisplay-name>  
     
    <welcome-file-list>  
        <welcome-file>index.jspwelcome-file>  
    welcome-file-list>
	<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
      
    <context-param>  
        <param-name>contextConfigLocationparam-name>  
        <param-value>classpath*:application.xmlparam-value>  
    context-param>  
    
    <context-param>
        <param-name>webAppRootKeyparam-name>
        <param-value>springmvc.rootparam-value>  
    context-param>  
   
   
      
    <filter>  
        <filter-name>SpringEncodingFilterfilter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>  
        <init-param>  
            <param-name>encodingparam-name>  
            <param-value>UTF-8param-value>  
        init-param>  
        <init-param>  
            <param-name>forceEncodingparam-name>  
            <param-value>trueparam-value>  
        init-param>  
    filter>  
    <filter-mapping>  
        <filter-name>SpringEncodingFilterfilter-name>  
        <url-pattern>/*url-pattern>  
    filter-mapping>  
   
      
    <context-param>  
          
        <param-name>log4jConfigLocationparam-name>  
        <param-value>classpath:log4j.propertiesparam-value>  
    context-param>  
    <context-param>  
          
        <param-name>log4jRefreshIntervalparam-name>  
        <param-value>6000param-value>  
    context-param>  
    <listener>  
        <listener-class>org.springframework.web.util.Log4jConfigListenerlistener-class>  
    listener>  
   
      
    <servlet>  
        <servlet-name>dispatcherServletservlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>  
        <init-param>  
            <param-name>contextConfigLocationparam-name>  
              
            <param-value>classpath:spring-mvc.xmlparam-value>  
        init-param>
        <load-on-startup>1load-on-startup>  
    servlet>  
      
    <servlet-mapping>  
        <servlet-name>dispatcherServletservlet-name>  
        <url-pattern>/url-pattern>  
    servlet-mapping>  
   
      
    <error-page>  
          
        <error-code>404error-code>  
        <location>/WEB-INF/errorpage/404.jsplocation>  
    error-page>  
    <error-page>  
          
        <error-code>405error-code>  
        <location>/WEB-INF/errorpage/405.jsplocation>
    error-page>
    <error-page>
        
        <error-code>500error-code>
        <location>/WEB-INF/errorpage/500.jsplocation>
    error-page>
web-app>

(4)添加index.jsp
在src/main/webapp/WEB-INF下新建一个文件夹view,添加一个index.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>Insert title here</title>
</head>
	<body>
		<h2>Hello World!</h2>
		 ${user.userId}<br>
		 ${user.userName}<br>
		 ${user.userPassword}<br>
		 ${user.userEmail}<br>
	</body>
</body>
</html>

(5)最后就是controller的书写了
在src/main/java下新建一个包com.ceh.controller.然后新建一个类UserController.java,其内容如下:

package com.ceh.controller;  
  
import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.ceh.domain.User;
import com.ceh.service.UserService;  
  
/** 
 * 功能概要:UserController 
 *  
 * @author cehkongfu 
 * @since  2018年3月12日 
 */  
@Controller  
public class UserController {  
    @Resource  
    private UserService userService;  
      
    @RequestMapping("/")    
    public ModelAndView getIndex(){      
        ModelAndView mav = new ModelAndView("index");   
        User user = userService.selectUserById(1);  
        mav.addObject("user", user);   
        return mav;    
    }    
}  

(6)最后的运行!
最后,就是成果了,已经全部都配置好了。我们可以开始以web工程运行了!
springmvc+spring+mybatis+Maven+mysql环境搭建,附源码_第17张图片

然后一路next
springmvc+spring+mybatis+Maven+mysql环境搭建,附源码_第18张图片

接下来控制台就会打印日志出来了!如下
springmvc+spring+mybatis+Maven+mysql环境搭建,附源码_第19张图片

打印浏览器,输入网址:http://localhost:8088/ssmMaven/
springmvc+spring+mybatis+Maven+mysql环境搭建,附源码_第20张图片

最后附上源码: https://download.csdn.net/download/chekongfu/10630645

你可能感兴趣的:(mybatis,spring,springmvc)