Idea 搭建 SSM 项目框架

引言

  在平时的JavaEE开发中,为了能够用最快的速度开发项目,一般会选择使用Struts2、SpringMVC、Spring、Hibernate、MyBatis这些开源框架来开发项目。

  本文来总结一下如何使用Maven搭建Spring+SpringMVC+MyBatis的整合开发环境。

创建Maven工程

  根据下图,一步步操作设定,填写GroupId、ArtifactId;创建完成后,Maven install 进行编译发布。

  完成的项目结构,如下图所示

 

在pom.xml引入相关依赖包

  为了方便后面说的时候不需要引入JAR包,这里直接给出所有的jar包。

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>4.0.2.RELEASE</spring.version>
    <mybatis.version>3.2.6</mybatis.version>
    <slf4j.version>1.7.7</slf4j.version>
    <log4j.version>1.2.17</log4j.version>
  </properties>

  <dependencies>
    <!--  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-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-jdbc</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>
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>7.0</version>
    </dependency>
    <!--  mysql  -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.30</version>
    </dependency>
    <!--  dbcp连接池  -->
    <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>
    <!--  日志文件管理  -->
    <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>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.1.23</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.13</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.1.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.1.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.1.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>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
View Code

Spring与MyBatis项目整合

添加JDBC配置文件

  在src/main/resources目录下创建一个jdbc.properties文件,用于连接数据库。

driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://*******:3306/ElimSign?useUnicode=true
jdbc_username=*******
jdbc_password=********
maxActive=20
maxIdle=20
minIdle=1
maxWait=60000

建立spring-mybatis.xml配置文件

  在src/main/resources目录下创建一个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.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--自动扫描-->
    <context:component-scan base-package="com.service" />
    <!--  引入配置文件  -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
        <property name="location" value="classpath:jdbc.properties" />
    </bean>

    <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${driverClassName}" />
        <property name="url" value="${jdbc_url}" />
        <property name="username" value="${jdbc_username}" />
        <property name="password" value="${jdbc_password}" />
        <property name="maxWait" value="${maxWait}" />
        <property name="minIdle" value="${minIdle}" />
        <property name="maxIdle" value="${maxIdle}" />
        <property name="maxActive" value="${maxActive}" />
    </bean>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
    </bean>

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

    <!--  事务管理  -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!--  配置基于注解的声明式事务  -->
    <tx:annotation-driven  transaction-manager="transactionManager" />
</beans>
View Code

配置log4j日志文件

  在src/main/resources目录下创建一个log4j.properties文件,用于整合项目,如图所示:

# 日志输出目的地
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=%-4r [%t] %-5p %c %x - %m%n

# 日志输出级别
log4j.rootLogger=info, Console
log4j.additivity=false

# 文件大小达到指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingCalendar
# 指定输出目录
log4j.appender.File.File = logs/ssm.log
# 定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出日志
log4j.appender.File.Threshold = DEBUG
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern = [%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n

项目框架构建

  在配置完所有文件之后,则在src/main/java下创建相应的业务逻辑文件(包含对象信息类、dao文件、业务逻辑实现类等),具体如下图所示,以及对应代码信息(同时展现数据库中对应表结构与数据信息)。

package com.model;

import java.util.Date;

/**
 * 团契信息类
 * JaminHuang   2019年6月19日 13:36:43
 */
public class Church {

    /**
     * 团契标识
     */
    private String ChurchId;
    /**
     * 团契名称
     */
    private String ChurchName;
    /**
     * Logo地址
     */
    private String Logo;
    /**
     * 最后更新时间
     */
    private Date UpdateTime;

    public Church() {}

    public Church(String churchId, String ChurchName, String logo) {
        this.ChurchId = churchId;
        this.ChurchName = ChurchName;
        this.Logo = logo;
        this.UpdateTime = new Date();
    }

    public String getChurchId() {
        return ChurchId;
    }

    public void setChurchId(String churchId) {
        ChurchId = churchId;
    }

    public String getChurchName() {
        return ChurchName;
    }

    public void setChurchName(String churChName) {
        ChurchName = churChName;
    }

    public String getLogo() {
        return Logo;
    }

    public void setLogo(String logo) {
        Logo = logo;
    }

    public Date getUpdateTime() {
        return UpdateTime;
    }

    public void setUpdateTime(Date updateTime) {
        UpdateTime = updateTime;
    }
}
Church
package com.dao;

import com.model.Church;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.mybatis.spring.annotation.MapperScan;

import java.util.List;

@MapperScan
public interface IChurchDao {

    /**
     * 添加团契信息
     * @param church 团契信息
     */
    @Insert("INSERT INTO Church(ChurchId, ChurchName, Logo, UpdateTime) VALUES(#{churchId},#{churchName},#{logo},#{updateTime})")
    void add(Church church);

    /**
     * 获取指定团契信息
     * @param churchId 团契标识
     * @return 团契对象
     */
    @Select("SELECT * FROM Church WHERE ChurchId = #{churchId}")
    Church get(String churchId);

    /**
     * 获取团契列表
     * @return 团契列表
     */
    @Select("SELECT * FROM Church")
    List<Church> list();
}
IChurchDao
package com.service;

import com.model.Church;

import java.util.List;

public interface IChurchService {
    /**
     * 添加团契信息
     * @param church 团契信息
     */
    void add(Church church);

    /**
     * 获取指定团契信息
     * @param churchId 团契标识
     * @return 团契对象
     */
    Church get(String churchId);

    /**
     * 获取团契列表
     * @return 团契列表
     */
    List<Church> list();
}
IChurchService
package com.service.impl;

import com.dao.IChurchDao;
import com.model.Church;
import com.service.IChurchService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("churchService")
public class ChurchServiceImpl implements IChurchService {

    @Resource
    private IChurchDao churchDao;

    public void add(Church church) {
        churchDao.add(church);
    }

    public Church get(String churchId) {
        return churchDao.get(churchId);
    }

    public List<Church> list() {
        return churchDao.list();
    }
}
ChurchServiceImpl

 测试

  至此,spring+mybatis构建完成;创建dao测试类,进行测试。

package com.test;

import com.alibaba.fastjson.JSON;
import com.dao.IChurchDao;
import com.model.Church;
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 java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring-mybatis.xml"})
public class IChurchDaoTest {

    @Autowired
    private IChurchDao churchDao;

    @Test
    public void testGetChurch() {
        String churchId = "4455ba6a12f26e08";
        Church church = churchDao.get(churchId);
        System.out.println(JSON.toJSON(church));
    }

    @Test
    public void testListChurch() {
        List<Church> list = churchDao.list();
        System.out.println(JSON.toJSON(list));
    }
}

整合SpringMVC

  上述,完成了2大框架的搭建,springmvc的配置文件spring-mvc.xml单独放置,再由web.xml进行整合。

配置spring-mvc.xml

  在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:context="http://www.springframework.org/schema/context"
       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">

    <!-- 扫描web相关的bean -->
    <context:component-scan base-package="com.controller"/>

    <!--  避免IE执行AJAX时,返回JSON出现下载文件  -->
    <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>

    <!-- 开启SpringMVC注解模式,完成请求和注解POJO的映射 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" />
            </list>
        </property>
    </bean>

    <!-- 配置jsp -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <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文件

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<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">
  <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>
  <!-- 编码过滤器 -->
  <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>
  <!--防止内存溢出监听器  -->
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>

  <!-- 配置DispatcherServlet -->
  <servlet>
    <servlet-name>SpringMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 配置springMVC需要加载的配置文件-->
    <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>SpringMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>/index.jsp</welcome-file>
  </welcome-file-list>

</web-app>

测试

  1. 新建jsp文件

<%@ page import="java.util.*" language="java" pageEncoding="UTF-8" %>
<html>
<head>
    <title>团契信息</title>
</head>
<body>
这里是内容!
${church.churchName}
</body>
</html>

  2. 创建Controller控制器

package com.controller;

import com.model.Church;
import com.service.IChurchService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/church")
public class ChurchController {

    @Resource
    private IChurchService churchService;

    @RequestMapping("/get")
    public String getChurch(HttpServletRequest request, Model model) {
        String churchId = request.getParameter("id");
        Church church = churchService.get(churchId);
        model.addAttribute("church", church);
        return "info";
    }
}

  3. 部署项目,在浏览器中输入地址:http://localhost:8080/church/get?id=4455ba6a12f26e08

  至此,SSM三大框架基本完成,可以在此基础上继续添加相应功能。

posted @ 2019-08-01 21:30  JaminHuang  阅读(536)  评论(1编辑  收藏  举报