eclipse构建maven项目整合SSM(spring+springMVC+mybatis)框架

maven整合SSM

转载请注明出处

0x00 开发环境

  1. Windows 7
  2. Eclipse Java EE IDE for Web Developers Mars.2 Release (4.5.2)
  3. Maven 3.2.2
  4. Spring 4.0.2
  5. Mybatis 3.2.6
  6. Tomcat 7.0
  7. Log4j 1.2.7
  8. MySQL 5.7.17

版本虽然不是太重要,建议注意一下

0x01 简介

本文是在整合SSM框架的时候的一些笔记。项目采用maven构建,整合了SSM框架,集成了log4j和mysql。

0x02 创建项目

选择菜单:

File -> New -> Other -> Maven -> Maven Project

点击 Next >,再点击Next >

eclipse构建maven项目整合SSM(spring+springMVC+mybatis)框架_第1张图片

然后Next >

eclipse构建maven项目整合SSM(spring+springMVC+mybatis)框架_第2张图片

然后点击 Finish,就生成项目了。如下图一样。

eclipse构建maven项目整合SSM(spring+springMVC+mybatis)框架_第3张图片

是不是发现没有 src/main/java 目录,没关系,创建一个。

选中项目 ,然后选择New -> Folder

eclipse构建maven项目整合SSM(spring+springMVC+mybatis)框架_第4张图片

注意选择 main 目录

小提示:如果你不小心又把 java 目录给删除了,那么上面这个方法就不行了。

创建方法:选中项目 ,然后选择New -> Source Folder

eclipse构建maven项目整合SSM(spring+springMVC+mybatis)框架_第5张图片

建议你删除项目重新创建,因为我没有试过这种方法。

0x03 添加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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0modelVersion>
    <groupId>cn.com.zdrgroupId>
    <artifactId>ssmRartifactId>
    <packaging>warpackaging>
    <version>0.0.1-SNAPSHOTversion>
    <name>ssmR Maven Webappname>
    <url>http://maven.apache.orgurl>
    <properties>
        
        <spring.version>4.0.2.RELEASEspring.version>
        
        <mybatis.version>3.2.6mybatis.version>
        
        <slf4j.version>1.7.7slf4j.version>
        <log4j.version>1.2.17log4j.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>3.8.1version>
            <scope>testscope>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-oxmartifactId>
            <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-webmvcartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-aopartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-context-supportartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>${spring.version}version>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>${mybatis.version}version>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>1.2.2version>
        dependency>
        
        <dependency>
            <groupId>javaxgroupId>
            <artifactId>javaee-apiartifactId>
            <version>7.0version>
        dependency>

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.36version>
        dependency>
        
        <dependency>
            <groupId>commons-dbcpgroupId>
            <artifactId>commons-dbcpartifactId>
            <version>1.2.2version>
        dependency>

        
        <dependency>
            <groupId>jstlgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>
        
        
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>${log4j.version}version>
        dependency>


        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.1.41version>
        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.codehaus.jacksongroupId>
            <artifactId>jackson-mapper-aslartifactId>
            <version>1.9.13version>
        dependency>

    dependencies>
    <build>
        <finalName>ssmRfinalName>
    build>
project>

0x04 配置 springMVC

resources创建spring-mvc.xml,内容如下:


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

        
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">    
        <property name="messageConverters">    
            <list>    
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">    
                    <property name="supportedMediaTypes">    
                        <list>    
                            <value>text/plain;charset=UTF-8value>  
                            <value>text/html;charset=UTF-8value>  
                            <value>applicaiton/javascript;charset=UTF-8value>    
                        list>    
                    property>    
                bean>    
            list>    
        property>    
    bean> 
        
    <context:annotation-config />                      
    
    <context:component-scan base-package="com.zdr.ssmR" />
    
    <mvc:annotation-driven/>  

    
    <bean id="mappingJacksonHttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8value>
                <value>application/json; charset=UTF-8value>    
                <value>application/x-www-form-urlencoded; charset=UTF-8value> 
            list>
        property>
    bean>

    
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" /> 
            list>
        property>
    bean>

    
    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <property name="order" value="1">property>
        <property name="mediaTypes">
            <map>
                
                <entry key="json" value="application/json" />
                <entry key="xml" value="application/xml" />
                <entry key="htm" value="text/htm" />
            map>
        property>
        <property name="defaultViews">
            <list>
                
                <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
            list>
        property>
        <property name="ignoreAcceptHeader" value="true">property>
    bean>

    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    bean>
beans>

需要注意 你创建的所有包的前缀要跟这个一致(当然,也可以不一致,但是要配置多个),所以可能跟我的不一样。

我们现在创建一个包,com.zdr.ssmR.controller,创建一个Controller。
代码如下:

package com.zdr.ssmR.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

    @RequestMapping(value = "/hello")
    @ResponseBody
    public String hello(){
        return "hello world";
    }

}

修改 src/main/webapp/WEB-INF/web.xml 文件,内容如下:



<web-app>
    <display-name>Archetype Created Web Applicationdisplay-name>

    
    <servlet>
        <servlet-name>mvcservlet-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>mvcservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
web-app>

注意:classpath:spring-mvc.xml 中的classpath是刚刚创建的xml文件,文件名是你自己创建的。

启动一下,然后访问 http://localhost:8080/ssmR/hello,不出错的话会出现下面的结果:

eclipse构建maven项目整合SSM(spring+springMVC+mybatis)框架_第6张图片

OK!继续下一步。

0x05 添加log4j

src/main/resources 下创建 log4j.properties,内容如下,中文在eclipse下可能会显示不出来,不用担心,不影响项目。

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/ssmR.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  

修改 HelloController.java,内容如下:

package com.zdr.ssmR.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {
    private static Logger log=LoggerFactory.getLogger(HelloController.class);

    @RequestMapping(value = "/hello")
    @ResponseBody
    public String hello(){
        log.info("测试 log配置");
        return "hello world";
    }

}

再运行一下,访问 http://localhost:8080/ssmR/hello,看看控制台有没有输出,配置的路径下有没有产生log文件。

0x06 配置JDBC

创建数据库:

CREATE DATABASE ssmR CHARACTER SET utf8;

创建表:

CREATE TABLE user(
id INTEGER PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
money INTEGER,
);

别忘了插入几条数据。

src/main/resources 下创建 jdbc.properties,内容如下,同样中文也是显示不出来,不影响项目。

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ssmR
username=root
password=root
#定义初始连接数  
initialSize=0  
#定义最大连接数  
maxActive=20  
#定义最大空闲  
maxIdle=20  
#定义最小空闲  
minIdle=1  
#定义最长等待时间  
maxWait=60000 

username、password字段就不要用我的了

0x07 构建 MVC项目框架

我们开发一个通过名字查找信息的接口,入参是一个名字,出参是名字和对应的金额。

创建 com.zdr.ssmR.domain 包,在该包下创建 User.java,内容如下:

package com.zdr.ssmR.domain;

import java.io.Serializable;

public class User implements Serializable {
    /***/
    private Integer id;

    /***/
    private String name;

    /***/
    private Integer money;

    private static final long serialVersionUID = 1L;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getMoney() {
        return money;
    }

    public void setMoney(Integer money) {
        this.money = money;
    }
}

创建 com.zdr.ssmR.dao 包,在该包下创建 IUserDao.java,内容如下:

package com.zdr.ssmR.dao;

import com.zdr.ssmR.domain.User;

public interface IUserDao {

    User selectByName(String name);
}

创建 com.zdr.ssmR.mapping 包,在该包下创建 UserMapper.xml,内容如下:



<mapper namespace="com.zdr.ssmR.dao.IUserDao">
    <resultMap id="BaseResultMap" type="com.zdr.ssmR.domain.User">
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="name" property="name" jdbcType="VARCHAR" />
        <result column="money" property="money" jdbcType="INTEGER" />
    resultMap>

    <sql id="Base_Column_List">
        id, name, money
    sql>
    <select id="selectByName" resultMap="BaseResultMap"
        parameterType="java.lang.String">
        select
        <include refid="Base_Column_List" />
        from user
        where name = #{name,jdbcType=VARCHAR}
    select>

mapper>

select id 的值要跟接口的方法一致

创建 com.zdr.ssmR.service 包,在该包下创建 UserService.java,内容如下:

package com.zdr.ssmR.service;

import com.zdr.ssmR.domain.User;

public interface UserService {
    User getUserByName(String name);
}

创建 com.zdr.ssmR.service.impl 包,在该包下创建 UserServiceImpl.java,内容如下:

package com.zdr.ssmR.service.impl;

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

import com.zdr.ssmR.dao.IUserDao;
import com.zdr.ssmR.domain.User;
import com.zdr.ssmR.service.UserService;
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    IUserDao userDao;

    public User getUserByName(String name) {
        return userDao.selectByName(name);
    }

}

修改 HelloController.java,内容如下:

package com.zdr.ssmR.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zdr.ssmR.domain.User;
import com.zdr.ssmR.service.UserService;


@Controller
public class HelloController {
    private static Logger log=LoggerFactory.getLogger(HelloController.class);

    @Autowired
    UserService userService;

    @RequestMapping(value = "/hello")
    @ResponseBody
    public String hello(){
        log.info("测试 log配置");
        return "hello world";
    }
    @RequestMapping(value = "/user/{name}")
    @ResponseBody
    public String helloUser(@PathVariable("name")String name){
        User user = userService.getUserByName(name);
        return "hello "+user.getName()+",金额:"+user.getMoney();
    }
}

我是不会告诉你 mybaits 有一个逆向生成工具叫 mybatis-generator-core-1.3.2.jar 的

0x08 创建 spring-mybaits.xml文件

src/main/resources 下创建 spring-mybaits.xml,内容如下:


<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">  
      
    <context:component-scan base-package="com.zdr.ssmR" />  

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

      
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
          
        <property name="mapperLocations" value="classpath:com/zdr/ssmR/mapping/*.xml">property>  
    bean>  

      
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.zdr.ssmR.dao" />  
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory">property>  
    bean>  

      
    <bean id="transactionManager"  
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    bean>  

beans>  

修改 src/main/webapp/WEB-INF/web.xml 文件,内容如下:



<web-app>
    <display-name>Archetype Created Web Applicationdisplay-name>
    
    <context-param>  
        <param-name>contextConfigLocationparam-name>  
        <param-value>classpath:spring-mybatis.xmlparam-value>  
    context-param>
    
    <filter>
        <filter-name>encodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>encodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
     
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>  
    listener>
    <listener>  
        <listener-class>org.springframework.web.util.IntrospectorCleanupListenerlistener-class>  
    listener>
    
    <servlet>
        <servlet-name>mvcservlet-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>mvcservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
web-app>

访问http://localhost:8080/ssmR/user/zdr
试试吧。
结果如下:
eclipse构建maven项目整合SSM(spring+springMVC+mybatis)框架_第7张图片


0x09 Other

完整项目在这里

不采用maven构建的ssm例子在这里

你可能感兴趣的:(学习笔记)