从无到有搭建SSM框架

从无到有搭建SSM框架

  虽然现在SpringBoot框架能帮助我们减少很多必要的配置工作,采用约定大于配置的配置方式,但是通过这种方式不利于新人知道他究竟帮我们完成了哪些工作,也不利于问题的排查,所以,我们还是最好自己搭建一遍SSM框架来熟悉相关的配置。

  下面我们就使用IDEA配合Maven一步一步的搭建一个SSM框架,并集成Restful风格和swagger。

  首先介绍一下swagger,swagger是一种能通过我们按规范写在controller上的注释,生成相应的API文档,并能模拟我们所需要的如post、delete等接口请求,帮助后端人员完成单元

使用Maven构建Web项目

  打开IDEA,点击File→New→Project,选择Maven,不勾选Create from archetype,这样会直接帮我们生成对应的目录。


    点击Next,进入如下界面,输入对应的信息。


  再点击Next,选择你要放置的文件目录。


  点击Finish,就完成一个空的Maven工程的搭建了。然后在界面右下角的弹框这选择Enable Auto-Import


  如果没有左侧的工程目录,则点击窗口最上方View→Tool Windows→Project。

  右键左侧项目名,选择Add FrameWork Support,再弹出的界面选择Web Application,添加Web依赖,再点击OK。

    

  然后在java目录下创建一些包,最后我们看到如下的工程目录:

    

SSM框架的配置

首先,引入相关Maven依赖,pom文件如下:

<?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>com.cjw</groupId>
    <artifactId>SSM</artifactId>
    <version>1.0-SNAPSHOT</version>


    <properties>
        <spring.version>4.3.7.RELEASE</spring.version>
        <mybatis.version>3.4.2</mybatis.version>
        <mybatis-spring.version>1.3.1</mybatis-spring.version>
        <c3p0.version>0.9.1</c3p0.version>
        <mysql.version>5.1.41</mysql.version>
        <mbg.version>1.3.6</mbg.version>
        <pagehelper.version>5.0.0</pagehelper.version>
        <slf4j.version>1.7.5</slf4j.version>
        <jackson-databind.version>2.8.8</jackson-databind.version>
        <junit.version>4.12</junit.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>


        <!-- spring web mvc -->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>




        <!--spring aspects-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--spring test-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>


        <!--Mybatis-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>


        <!--Mybatis整合spring适配包-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis-spring.version}</version>
        </dependency>


        <!--数据库连接池-->
        <!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>${c3p0.version}</version>
        </dependency>


        <!--数据库驱动-->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.8.0</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>
        <!--返回json字符串-->
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson-databind.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson-databind.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson-databind.version}</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <!--mybatis逆向工程插件-->
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>${mysql.version}</version>
                    </dependency>
                    <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper</artifactId>
                        <version>3.4.3</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

    等待Maven自动下载对应的jar包。

    紧接着,创建对应配置文件,相关配置文件都放在在src/main/resources下。

    首先创建数据库配置文件,右键resources,New→File,输入文件名为:dbconfig.properties,包含数据库的驱动和一些连接配置,配置如下:

jdbc.jdbcUrl=jdbc:mysql://localhost:3306/Test?useSSL=false&useUnicode=true&characterEncoding=UTF-8
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=111111

    然后创建spring配置文件,右键resources,New→XML Configuration File→Spring Config,输入文件名为application,该配置文件下,我们用于开启注解,整合Mybatis以及相关事务,配置文件如下:

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <context:component-scan base-package="com.ssm">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!--spring配置文件-->
    <context:property-placeholder location="classpath:dbconfig.properties"/>

    <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!--Mybatis整合-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--指定Mybaties全局配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <property name="dataSource" ref="pooledDataSource"></property>
        <!--指定Mybaties-mapper配置文件-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    </bean>

    <!--配置扫描器-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--扫描dao接口加入到ioc-->
        <property name="basePackage" value="com.ssm.dao"></property>
    </bean>

    <!--配置sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
        <constructor-arg name="executorType" value="BATCH"></constructor-arg>
    </bean>

    <!--事务控制-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--控制数据源-->
        <property name="dataSource" ref="pooledDataSource"></property>
    </bean>
    <aop:config>
        <!--切入点-->
        <aop:pointcut id="txPoint" expression="execution(* com.ssm.service..*(..))"/>
        <!--配置事务增强-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
    </aop:config>

    <!--事务增强-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*"/>
            <tx:method name="get*" read-only="true"/>
        </tx:attributes>
    </tx:advice>

</beans>

再创建mybatis配置文件为mybatis-config.xml,配置文件如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <!--实体类别名开启-->
    <typeAliases>
        <package name="com.ssm.bean"/>
    </typeAliases>
    
</configuration>

    再创建逆向工程配置文件,逆向工程能够帮助我们节省很多重复的xml文件的书写,在resources下创建逆向工程配置文件为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>
    <properties resource="dbconfig.properties"></properties>
    <context id="DB2Tables" targetRuntime="MyBatis3">
        <!--是否关闭注释-->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--配置数据库连接-->
        <jdbcConnection driverClass="${jdbc.driverClass}"
                        connectionURL="${jdbc.jdbcUrl}"
                        userId="${jdbc.user}"
                        password="${jdbc.password}">
        </jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!--指定JavaBean生成位置-->
        <javaModelGenerator targetPackage="com.ssm.bean" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!--指定sql映射生成位置-->
        <sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!--指定dao生成位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.ssm.dao" targetProject=".\src\main\java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!--denmo示例-->
        <table tableName="userInfo" domainObjectName="UserInfo"></table>

    </context>
</generatorConfiguration>
    这样我们就可以使用maven插件生成数据层的对应文件了,具体使用:点击界面左下角,选择Maven Projects,然后在右侧点击项目名,点击Plugs,找到mybatis-generator,点击列表第一个,就可以根据配置文件自动去生成文件了。

    再创建springmvc配置文件为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: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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--springmvc配置文件-->
    <context:component-scan base-package="com.ssm" use-default-filters="false">
        <!--只扫描控制器-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!-- 添加的两个 自动配置器(restful 风格所必须) -->
    <!--将springmvc不能处理的资源交给tomcat-->
    <mvc:default-servlet-handler/>
    <!--支持springmvc的更高级功能-->
    <mvc:annotation-driven/>
</beans>

    再创建日志配置文件,其中数据库输出,只需创建对应字段,类型varchar就行,配置文件如下:

log4j.rootLogger=INFO,appender1,appender2,appender3
# org.springframework包下面所有的日志输出的级别设为DEBUG 
log4j.logger.org.springframework=DEBUG
# 控制台输出
log4j.appender.appender1=org.apache.log4j.ConsoleAppender
log4j.appender.appender1.layout=org.apache.log4j.PatternLayout
log4j.appender.appender1.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss:SSS}[%p]: %m%n
# 文件输出,这里默认为追加方式 
log4j.appender.appender2=org.apache.log4j.FileAppender
log4j.appender.appender2.File=log/LogMonitor.log
log4j.appender.appender2.layout=org.apache.log4j.PatternLayout
log4j.appender.appender2.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss:SSS}[%p]: %m%n
# 数据库输出 
log4j.appender.appender3=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.appender3.database.BufferSize=10
log4j.appender.appender3.driver=com.mysql.jdbc.Driver
log4j.appender.appender3.URL=jdbc:mysql://127.0.0.1:3306/test
log4j.appender.appender3.user=root
log4j.appender.appender3.password=111111
log4j.appender.appender3.sql=insert into log(level,category,thread,time,location,note) values('%p','%c','%t','%d{yyyy-MM-dd HH:mm:ss:SSS}','%l','%m') 

    配置swagger,采用java配置,在config包下,创建SwaggerConfig类,配置内容如下:

package com.ssm.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SSM-Swagger")
                .description("SSM简单Demo")
                .termsOfServiceUrl("https://blog.csdn.net/qq_28131641")
                .version("1.0")
                .build();
    }
}

    最后,修改web.xml配置,用于加载相关配置文件,配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<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_4_0.xsd"
         version="4.0">
    <!--启动spring容器-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:application.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--springmvc前端控制器-->
    <servlet>
        <servlet-name>dispatcher</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>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--字符编码过滤器-->
    <filter>
        <filter-name>CharacterEncodingFilter</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>
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--rest风格URI-->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter>
        <filter-name>HttpPutFormContentFilter</filter-name>
        <filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HttpPutFormContentFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

写一个简单的测试接口如下:

package com.ssm.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/test")
@Api(description = "测试")
public class TestController {
    //获得所有用户信息列表
    @GetMapping(value = "test")
    @ApiOperation(value = "普通查询")
    public String getUserInfoList() {
        return "Hello SSM";
    }
}

IDEA配置下tomcat

点击如图所示structure,进入配置界面


选择Artifacts,右键如图所示,选择Put into output Root


    然后点击右上角箭头所示位置,选择Edit Configuration,进入如图界面,再选择Deployment,点击+号,选择Artifact


最后启动项目,再浏览器路径后加上swagger-ui.html则可以进入Swagger的页面,如图所示:


至此,我们的项目就已经搭建好了,也是新手,不妥之处,请大家评论指出。

项目下载地址:空的的SSM项目

没有更多推荐了,返回首页