第四十四章:單一(偽分散式)架構:SSM整合02
單一(偽分散式)架構之使用Maven建立各個工程之間的依賴、繼承、聚合關係
SSM jar包依賴統一管理
工程:parent
pom.xml
<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</groupId> <artifactId>parent</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>pom</packaging> <modules> <module>common</module> <module>ui-manager</module> <module>component</module> </modules> <!-- 宣告properties對依賴版本進行統一管理 --> <properties> <spring.version>4.0.0.RELEASE</spring.version> </properties> <!-- 依賴資訊的統一管理 --> <dependencyManagement> <dependencies> <!-- Spring依賴 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring輔助依賴 --> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.8</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.2</version> </dependency> <!-- 資料庫相關依賴 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.37</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.31</version> </dependency> <!-- Mybatis相關依賴 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- Mybatis的PageHelper外掛依賴 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.0.0</version> </dependency> <!-- 日誌列印相關 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.7</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.7</version> </dependency> <!-- 檔案上傳 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <!-- JSTL標籤 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- junit依賴 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <!-- jsp-api --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1.3-b06</version> <scope>provided</scope> </dependency> </dependencies> </dependencyManagement> </project>
建庫建表SQL
CREATE DATABASE IF NOT EXISTS `atcrowdfunding` CHARACTER SET utf8 COLLATE utf8_bin; USE atcrowdfunding; create table IF NOT EXISTS t_user ( id int not null auto_increment, loginacct varchar(255) not null, userpswd char(32) not null, username varchar(255) not null, email varchar(255) not null, createtime char(19), primary key (id) );
Mybatis相關
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>
</configuration>
建立MyBatis逆向工程
在其他工程之外建立另外一個工程
pom.xml設定
<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</groupId>
<artifactId>reverse</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- 這個依賴是為了避免生成Mapper介面後報錯,不影響資源生成過程 -->
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
</dependencies>
<!-- 配置逆向工程的Maven外掛 -->
<build>
<!-- plugins:構建過程中用到的外掛 -->
<plugins>
<!-- plugin:具體外掛 -->
<plugin>
<!-- MyBatis逆向工程外掛座標 -->
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.0</version>
<!-- 外掛工作過程中用到的依賴 -->
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.8</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
逆向工程配置檔案: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>
<context id="tables" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<commentGenerator>
<!-- 是否去除自動生成的註釋 true:是;false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--資料庫連線的資訊:驅動類、連線地址、使用者名稱、密碼 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/atcrowdfunding" userId="root"
password="root">
</jdbcConnection>
<!-- 預設false,把JDBC DECIMAL 和 NUMERIC 型別解析為 Integer,為 true時把JDBC DECIMAL
和 NUMERIC 型別解析為java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- targetProject:生成Entity類的路徑 -->
<javaModelGenerator targetProject=".\src\main\java"
targetPackage="com.entity">
<!-- enableSubPackages:是否讓schema作為包的字尾 -->
<property name="enableSubPackages" value="false" />
<!-- 從資料庫返回的值被清理前後的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:XxxMapper.xml對映檔案生成的路徑 -->
<sqlMapGenerator targetProject=".\src\main\java"
targetPackage="com.component.mapper">
<!-- enableSubPackages:是否讓schema作為包的字尾 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:Mapper介面生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetProject=".\src\main\java" targetPackage="com.component.mapper">
<!-- enableSubPackages:是否讓schema作為包的字尾 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 資料庫表名字和我們的entity類對應的對映指定 -->
<table tableName="t_user" domainObjectName="UserDO" />
</context>
</generatorConfiguration>
生成資源的Maven命令:mybatis-generator:generate
資源歸位F5重新整理專案
複製檔案到其他專案
Spring和MyBatis整合
在common工程加入Spring和MyBatis整合需要的依賴
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
</dependencies>
在ui-manger專案中加入
jdbc.properties
jdbc.user=root
jdbc.password=root
jdbc.url=jdbc:mysql://localhost:3306/atcrowdfunding?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf8
jdbc.driver=com.mysql.jdbc.Driver
jdbc.initialSize=20
jdbc.minIdle=10
jdbc.maxActive=50
jdbc.maxWait=10000
jdbc.timeBetweenEvictionRunsMillis=60000
jdbc.minEvictableIdleTimeMillis=300000
jdbc.testWhileIdle=true
log4j.properties
# For JBoss: Avoid to setup Log4J outside $JBOSS_HOME/server/default/deploy/log4j.xml!
# For all other servers: Comment out the Log4J listener in web.xml to activate Log4J.
# DEBUG < INFO < WARN < ERROR < FATAL
log4j.rootLogger=DEBUG, a, logfile
log4j.appender.a=org.apache.log4j.ConsoleAppender
log4j.appender.a.layout=org.apache.log4j.PatternLayout
log4j.appender.a.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,S} %-5p [%c] %l - %m%n
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=D:/atcrowdfunding.log
log4j.appender.logfile.MaxFileSize=512KB
# Keep three backup files.
log4j.appender.logfile.MaxBackupIndex=3
# Pattern to output: date priority [category] - message
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
spring-tx.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-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 引入外部屬性檔案 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 配置自動掃描的包 -->
<context:component-scan base-package="com.component.service.impl"/>
<!-- 配置資料來源 -->
<bean id="dataSource"
class="com.alibaba.druid.pool.DruidDataSource">
<property name="username" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
<property name="url" value="${jdbc.url}" />
<property name="driverClassName" value="${jdbc.driver}" />
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="${jdbc.initialSize}" />
<property name="minIdle" value="${jdbc.minIdle}" />
<property name="maxActive" value="${jdbc.maxActive}" />
<!-- 配置獲取連線等待超時的時間 -->
<property name="maxWait" value="${jdbc.maxWait}" />
<!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis"
value="${jdbc.timeBetweenEvictionRunsMillis}" />
<!-- 配置一個連線在池中最小生存的時間,單位是毫秒 -->
<property name="minEvictableIdleTimeMillis"
value="${jdbc.minEvictableIdleTimeMillis}" />
<property name="testWhileIdle" value="${jdbc.testWhileIdle}" />
</bean>
<!-- 配置SqlSessionFactoryBean -->
<!-- SqlSessionFactoryBean實現了FactoryBean介面,所以這裡配置的bean返回的物件是SqlSessionFactory的物件 -->
<!-- SqlSessionFactoryBean將建立SqlSessionFactory物件的繁瑣細節進行了封裝和遮蔽 -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 裝配資料來源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 指定MyBatis配置檔案位置 -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 配置Mapper配置檔案路徑 -->
<property name="mapperLocations" value="classpath:mapper/*Mapper.xml"></property>
</bean>
<!-- 為Mapper介面的掃描器指定Mapper介面所在包 -->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定Mapper介面所在的包 -->
<property name="basePackage" value="com.component.mapper"/>
</bean>
<!-- 配置宣告式事務 -->
<!-- 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 裝配資料來源 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置事務切面的切入點表示式 -->
<aop:config>
<aop:pointcut expression="execution(* *..*Service.*(..))" id="txPointCut"/>
<!-- 將切入點表示式和事務通知配置關聯起來 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
<!-- 配置事務通知屬性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="list*" read-only="true"/>
<tx:method name="count*" read-only="true"/>
<!--rollback-for屬性:指定事務回滾的異常 -->
<!--propagation屬性:事務的傳播行為 -->
<!--REQUIRED:當前方法必須執行在事務中,但如果當前執行緒上已經開啟了事務,則在當前事務中執行 -->
<!--REQUIRES_NEW:當前方法必須執行在事務中,而且一定要開啟一個新事務,在自己的事務中執行。避免在共用事務時其他方法操作失敗導致當前方法回滾。 -->
<tx:method name="remove*" rollback-for="java.lang.Exception" propagation="REQUIRES_NEW"/>
<tx:method name="save*" rollback-for="java.lang.Exception" propagation="REQUIRES_NEW"/>
<tx:method name="update*" rollback-for="java.lang.Exception" propagation="REQUIRES_NEW"/>
</tx:attributes>
</tx:advice>
</beans>
測試類
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring-tx.xml")
public class AtCrowdfundingTest {
@Autowired
private DataSource dataSource;
@Test
public void testDataSource() throws SQLException {
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
}
將spring-tx.xml,jdbc.properties檔案放到測試src/test/resources下
如果出現下列錯誤
發現報錯add新增junit.jar和spring-test
或者在ui-manger專案的pom.xml檔案中
<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>
<parent>
<groupId>com</groupId>
<artifactId>parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>ui-manager</artifactId>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>com</groupId>
<artifactId>component</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
</dependencies>
</project>
如果還有報錯
在common專案的pom.xml中新增
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
Spring和SpringMVC整合
建立SpringMVC的配置檔案
spring-mvc.xml
在common工程中加入Web開發相關依賴,之前如果新增過就不用再添加了
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
</dependency>
在ui-manger工程加入Web開發相關依賴
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<scope>provided</scope>
</dependency>
在spring-mvc.xml中加入名稱空間
配置spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- 配置自動掃描的包 -->
<context:component-scan base-package="com.component.handler"/>
<!-- 配置檢視解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 標配 -->
<mvc:annotation-driven/>
<!-- DefaultServletHandler[可選]
計劃在web.xml中讓DispatcherServlet對映副檔名,所以DefaultServletHandler可以不配置。 -->
<mvc:default-servlet-handler/>
</beans>
在web.xml中配置
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name>ui-manager</display-name>
<!-- needed for ContextLoaderListener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-tx.xml</param-value>
</context-param>
<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- DispatcherServlet -->
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<servlet>
<servlet-name>springDispatcherServlet</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>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<!-- CharacterEncodingFilter -->
<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>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- HiddenHttpMethodFilter -->
<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>
</web-app>
如果有其他問題可能是jar包下載失敗,可以將你的maven倉庫刪除重新下載,你也可以按alt+F5,選擇專案更新,也可能是你的eclipse沒有maven配置或者評論下方留言,如果有時間我可以幫你看看
偽靜態效果
通過讓DispatcherServlet對映*.html實現偽靜態。可以將由SpringMVC處理的動態請求從表面看起來像是訪問一個HTML靜態頁面,這樣讓專案不容易被猜到用什麼技術實現的。
給黑客入侵製造障礙。
一定程度上有利於SEO優化:讓搜尋引擎更容易找到我們的網站。
我自己寫好的專案,完整版的SSM整合reverse和parent父專案下有子專案,匯入帶有spring外掛的eclipse時,子專案從父專案中匯入就即可,注意有spring外掛的eclipse要maven配置
我們做個首頁展示
首頁展示
建立index.jsp
可能報錯,解決方案
在index.jsp中執行轉發操作
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.getRequestDispatcher("/index.html").forward(request, response);
%>
為/index.html地址對映一個handler方法
package com.component.handler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class PortalMainHandler {
@RequestMapping("/index")
public String showIndexPage() {
//準備首頁要顯示的資料……
return "portal/main";
}
}
經過spring-mvc.xml的檢視解析器拼接,我們建立main.jsp
頁面自己寫,現在直接
就可以看到自己的頁面了
還可以將原型程式碼(前端人員寫的)加入main.jsp中
但是加上base標籤
<base href="http://${pageContext.request.serverName }:${pageContext.request.serverPort}${pageContext.request.contextPath}/"/>
注意點1:埠號和contextPath之間不要再加“/”。
注意點2:contextPath後面要加“/”。
樣式加一下