转载

集成 Spring + Spring MVC + MyBatis 搭建单体应用

这里使用 Maven 项目管理工具构建项目

初始化项目

  • 打开 Intellij IDEA,点击 Create New Project
  • 选择 Maven 构建项目
  • 选择 JDK 版本(此处不阐述 JDK 安装的详细步骤,不会的小伙伴戳 JDK 安装教程 )
  • 勾选项目模板
  • 选择 maven-archetype-webapp 模板(Java Web 项目) 集成 Spring + Spring MVC + MyBatis 搭建单体应用
  • 填写项目在 Maven 仓库中的坐标(在 Maven 仓库中根据这个坐标才能找到该项目),具体命名规则根据公司决定 集成 Spring + Spring MVC + MyBatis 搭建单体应用
  • 选择 Maven 安装路径(此处不阐述 Maven 安装教程 的详细步骤)
  • 选择 Maven 配置文件路径
  • 选择 Maven 本地仓库路径 集成 Spring + Spring MVC + MyBatis 搭建单体应用
  • 填写项目名
  • 选择工作目录(不建议存放 C 盘) 集成 Spring + Spring MVC + MyBatis 搭建单体应用

整合 Spring、Spring MVC、Mybatis

src > main 目录下分别新建 java 源码目录 和 resource 配置文件目录 集成 Spring + Spring MVC + MyBatis 搭建单体应用

java 目录下创建源码的基本目录结构(该目录结构仅供参考,建议改为模块化结构) 集成 Spring + Spring MVC + MyBatis 搭建单体应用

webapp 目录下创建 static 目录,用于存放静态资源文件(css, js, img...) 集成 Spring + Spring MVC + MyBatis 搭建单体应用

webapp > WEB-INF 目录下创建 view 目录,用于存放页面(jsp, html...) 集成 Spring + Spring MVC + MyBatis 搭建单体应用

完整的 pom.xml 如下:

<?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.antoniopeng</groupId>
  <artifactId>hello-ssm</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>hello-ssm Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <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>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>compile</scope>
    </dependency>

    <!-- log4j begin-->
    <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>
    <!-- log4j end-->

    <!-- ssm begin-->
    <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-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-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.6.2</version>
    </dependency>
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.2</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.30</version>
    </dependency>
    <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>
    <!-- ssm end-->

    <!-- commons begin -->
    <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-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>2.6</version>
    </dependency>
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.9</version>
    </dependency>
    <!-- commons end -->
  </dependencies>

  <build>
    <finalName>hello-ssm</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
      <resource>
        <directory>src/main/resource</directory>
        <includes>
          <include>*.xml</include>
          <include>*.dll</include>
          <include>*.properties</include>
        </includes>
      </resource>
    </resources>
  </build>
</project>复制代码

创建 log4j.properties 日志配置文件(以下配置文件均在 resource 目录下新建)

log4j.rootLogger=error, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
log4j.appender.stdout.layout.ConversionPattern=[service] %d - %c -%-4r [%t] %-5p %c %x - %m%n  

log4j.logger.com.ibatis = debug  
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource = debug  
log4j.logger.com.ibatis.common.jdbc.ScriptRunner = debug  
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate = debug  
log4j.logger.java.sql.Connection = debug  
log4j.logger.java.sql.Statement = debug  
log4j.logger.java.sql.PreparedStatement = debug
log4j.logger.java.sql.ResultSet =debug  
log4j.logger.com.pro.mapper =debug复制代码

创建 db.properties 数据库配置文件

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://{host}:{port}/{db_name}?useUnicode=true&characterEncoding=UTF-8
user={username}
password={pwd}复制代码

创建 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="logImpl" value="STDOUT_LOGGING" />
  </settings>
  <typeAliases>
    <package name="com.antoniopeng.hello.ssm.entity" />
  </typeAliases>
</configuration>复制代码

创建 spring-context.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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop.xsd">

  <context:component-scan base-package="com.antoniopeng.hello.ssm.service.impl" />

  <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation" value="classpath:mybatis-config.xml" />
  </bean>

  <context:property-placeholder location="classpath:db.properties" />
  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="${driver}" />
    <property name="jdbcUrl" value="${url}" />
    <property name="user" value="${user}" />
    <property name="password" value="${password}" />
  </bean>

  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.antoniopeng.hello.ssm.mapper" />
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean" />
  </bean>

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

  <!--  拦截器方式配置事务 -->
  <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
    <tx:attributes>
      <tx:method name="edit*" propagation="REQUIRED"  rollback-for="java.lang.Throwable"/>
      <tx:method name="insert*" propagation="REQUIRED"  rollback-for="java.lang.Throwable"/>
      <tx:method name="delete*" propagation="REQUIRED"   rollback-for="java.lang.Throwable"/>
      <tx:method name="update*" propagation="REQUIRED"  rollback-for="java.lang.Throwable"/>
      <tx:method name="find*" read-only="true" />
      <tx:method name="select*" read-only="true"/>
      <tx:method name="count*" read-only="true"/>
      <tx:method name="*" />
    </tx:attributes>
  </tx:advice>

  <!-- 开启注解事务-->
  <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"  order="0"/>

  <aop:config proxy-target-class="true">
    <!-- 定义切入点 -->
    <aop:pointcut id="mysqlTransactionPointcut" expression="execution(* com.antoniopeng.hello.ssm.service.impl.*.*(..))" />
    <!-- 将事务通知 与 切入点组合 -->
    <aop:advisor pointcut-ref="mysqlTransactionPointcut" advice-ref="transactionAdvice" order="1"/>
  </aop:config>

</beans>复制代码

创建 spring-servlet.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">

  <mvc:annotation-driven />

  <context:component-scan base-package="com.antoniopeng.hello.ssm.controller" />

  <mvc:resources mapping="/statics/**" location="/static/" />

  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/view/" />
    <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="10240000"></property>
    <property name="maxInMemorySize" value="40960" />
  </bean>

</beans>复制代码

com.antoniopeng.hello.ssm 目录下创建 filter 目录,并在其目录下创建 CharacterFilter 类,这一步是为了防止网页乱码

import javax.servlet.*;
import java.io.IOException;

public class CharacterFilter implements Filter {

    public CharacterFilter() {
        // TODO Auto-generated constructor stub
    }

    public void destroy() {
        // TODO Auto-generated method stub
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        chain.doFilter(request, response);
    }

    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
    }
}复制代码

修改后完整的 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_3_1.xsd"
         version="3.1">
  <welcome-file-list>
    <welcome-file>/</welcome-file>
  </welcome-file-list>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      classpath:spring-context.xml
    </param-value>
  </context-param>

  <filter>
      <filter-name>characterFilter</filter-name>
      <filter-class>com.antoniopeng.hello.ssm.filter.CharacterFilter</filter-class>
  </filter>
  <filter-mapping>
      <filter-name>characterFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>

  <filter>
    <filter-name>characterEncoding</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>characterEncoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <servlet>
    <servlet-name>springServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-servlet.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>复制代码

部署到 Tomcat 服务器

点击 Intellij IDEA 页面右上方 `Add Configuration.. 集成 Spring + Spring MVC + MyBatis 搭建单体应用

添加 Tomcat 本地服务器配置 集成 Spring + Spring MVC + MyBatis 搭建单体应用

配置下载好的 Tomcat 服务器, Tomcat8 官网下载地址

设置访问端口号,默认 8080 集成 Spring + Spring MVC + MyBatis 搭建单体应用

部署项目到 Tomcat 服务器 集成 Spring + Spring MVC + MyBatis 搭建单体应用

测试运行访问

webapp > WEB-INF > view 目录下新建 index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>index</title>
</head>

<body>
       hello ssm
</body>
</html>复制代码

controller 目录下创建 IndexController

package com.antoniopeng.hello.ssm.controller;

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

@Controller
public class IndexController {

    @RequestMapping(value = "/")
    public String index() {
        return "index";
    }
}复制代码

启动 Tomcat 服务器,访问 http://localhost:8080

项目已经上传至 Git Hub ,后续会持续更新微服务分布式架构解决方案

  • 文章作者:彭超
  • 本文首发于个人博客: antoniopeng.com/2019/04/25/…
  • 版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 彭超 | Blog !
原文  https://juejin.im/post/5e91af8b6fb9a03c37303d58
正文到此结束
Loading...