集成 Spring + Spring MVC + MyBatis 搭建單體應用

這裏使用 Maven 項目管理工具構建項目css

初始化項目

  • 打開 Intellij IDEA,點擊 Create New Project
  • 選擇 Maven 構建項目
  • 選擇 JDK 版本
  • 勾選項目模板
  • 選擇 maven-archetype-webapp 模板(Java Web 項目)
    在這裏插入圖片描述
  • 填寫項目在 Maven 倉庫中的座標(在 Maven 倉庫中根據這個座標才能找到該項目),具體命名規則根據公司決定
    在這裏插入圖片描述
  • 選擇 Maven 安裝路徑(此處不闡述 Maven 安裝教程 的詳細步驟)
  • 選擇 Maven 配置文件路徑
  • 選擇 Maven 本地倉庫路徑
    在這裏插入圖片描述
  • 填寫項目名
  • 選擇工做目錄(不建議存放 C 盤)
    在這裏插入圖片描述

整合 Spring、Spring MVC、Mybatis

src > main 目錄下分別新建 java 源碼目錄 和 resource 配置文件目錄
在這裏插入圖片描述html

java 目錄下建立源碼的基本目錄結構(該目錄結構僅供參考,建議改成模塊化結構)
在這裏插入圖片描述java

webapp 目錄下建立 static 目錄,用於存放靜態資源文件(css, js, img...)
在這裏插入圖片描述mysql

webapp > WEB-INF 目錄下建立 view 目錄,用於存放頁面(jsp, html...)
在這裏插入圖片描述git

完整的 pom.xml 以下:github

<?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 目錄下新建)web

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 數據庫配置文件spring

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

建立 mybatis-config.xmlsql

<?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..
在這裏插入圖片描述

添加 Tomcat 本地服務器配置
在這裏插入圖片描述

配置下載好的 Tomcat 服務器,Tomcat8 官網下載地址

設置訪問端口號,默認 8080
在這裏插入圖片描述

部署項目到 Tomcat 服務器
在這裏插入圖片描述

測試運行訪問

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,後續會持續更新微服務分佈式架構解決方案

相關文章
相關標籤/搜索