1. 程式人生 > >web專案整合spring框架

web專案整合spring框架

以下是一個最簡單的示例

1、新建一個標準的javaweb專案

2、匯入spring所需的一些基本的jar包

3、配置web.xml檔案

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<!-- 應用程式Spring上下文配置 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			classpath*:applicationContext*.xml,
		</param-value>
	</context-param>

	<!-- spring上下文載入監聽器 -->
	<listener>
		<listener-class>
			org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

4、新增spring配置檔案applicationContext

5、對applicationContext.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" 

	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"

	default-lazy-init="false" default-autowire="byName">
	<bean id="user" class="com.po.User">
		<property name="name" value="張三"/>
	</bean>
</beans>

beans —— xml檔案的根節點。

xmlns ——是XML NameSpace的縮寫,因為XML檔案的標籤名稱都是自定義的,自己寫的和其他人定義的標籤很有可能會重複命名,而功能卻不一樣,所以需要加上一個namespace來區分這個xml檔案和其他的xml檔案,類似於java中的package。

xmlns:xsi ——是指xml檔案遵守xml規範,xsi全名:xml schema instance,是指具體用到的schema資原始檔裡定義的元素所準守的規範。即/spring-beans-2.0.xsd這個檔案裡定義的元素遵守什麼標準。

xsi:schemaLocation——是指,本文件裡的xml元素所遵守的規範,schemaLocation 屬性用來引用(schema)模式文件,解析器可以在需要的情況下使用這個文件對 XML 例項文件進行校驗。它的值(URI)是成對出現的,第一個值表示名稱空間,第二個值則表示描述該名稱空間的模式文件的具體位置,兩個值之間以空格分隔。
 

6、新建一個實體類User.java

package com.po;

public class User {
	private String name;
	private String age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
}

7、測試

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ApplicationContext ac = new FileSystemXmlApplicationContext("config/applicationContext.xml");
		User user =(User)ac.getBean("user");
		System.out.println(user.getName());
	}

輸出



這就實現web專案搭建基礎spring框架。接下來就做一些真正專案中會用到的一些擴充套件

可以在web.xml中配置一些spring框架整合的功能或其他設定

<!-- 字元編碼過濾器,必須放在過濾器的最上面 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
		<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>

	<!-- 配置延遲載入時使用OpenSessionInView-->
	<filter>
		<filter-name>openSessionInViewFilter</filter-name>
		<filter-class>
		org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
		</filter-class>
		<init-param>
			<param-name>singleSession</param-name>
			<param-value>true</param-value>
		</init-param>
		<init-param>
			<param-name>sessionFactoryBeanName</param-name>
			<!--指定對Spring配置中哪個sessionFactory使用OpenSessionInView-->
			<param-value>sessionFactory</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>openSessionInViewFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- spring security過濾器 org.springframework.web.filter.DelegatingFilterProxy(委託過濾器代理)-->
        <!-- 使用springSecurity或apache shiro就會用到這個過濾器,-->
	<filter>
		<filter-name>springSecurityFilterChain</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
<!-- 宣告 Spring MVC DispatcherServlet -->
	<servlet>
		<servlet-name>springDispatcher</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 for /* to the dispatcher servlet -->
	<servlet-mapping>
		<servlet-name>springDispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
<!-- 配置出錯頁面 -->
	<error-page>
		<error-code>404</error-code>
		<location>errorpage/404.jsp</location>
	</error-page>
	<!-- 401錯誤 -->
	<error-page>
		<error-code>401</error-code>
		<location>/errorpage/401.html</location>
	</error-page>
<!-- 為每個jsp頁面引入taglib.jspf等檔案 -->
	<jsp-config>
		<taglib>
			<taglib-uri>/WEB-INF/runqianReport4.tld</taglib-uri>
			<taglib-location>/WEB-INF/runqianReport4.tld</taglib-location> 
		</taglib>
		<jsp-property-group>
			<url-pattern>*.jsp</url-pattern>
			<page-encoding>UTF-8</page-encoding>
			<include-prelude>/tag/taglib.jspf</include-prelude>
			<!--<trim-directive-whitespaces>true</trim-directive-whitespaces> -->
		</jsp-property-group>
	</jsp-config>

其中jspf就是做一些全域性的宣告

<%@ page language="java" contentType="text/html; charset=UTF-8"
<span style="white-space:pre">	</span>pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fnc" uri="/WEB-INF/tlds/fnc.tld" %>
<%@ taglib tagdir="/WEB-INF/tags" prefix="mytag"%>
<c:set var="ctx" scope="session"
<span style="white-space:pre">	</span>value="${pageContext.request.contextPath}" />

可以在applicationContext.xml中配置更多的功能

<!-- beans可以新增更多宣告 -->
<beans xmlns="http://www.springframework.org/schema/beans"

	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"

	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"

	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-3.0.xsd

	http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd 

	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 

	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.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-3.0.xsd"

	default-lazy-init="false" default-autowire="byName">
<!-- 使用註解定義切面 -->
	<aop:aspectj-autoproxy />

	<mvc:annotation-driven /> 
<!-- spring 註釋代替配置,自動掃描的基礎包,將掃描該包以及所有子包下的所有類需要把controller去掉,否則影響事務管理 -->

	<context:component-scan base-package="com.schoolnet">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
	</context:component-scan>
<!-- 配置系統properties配置檔案 -->
<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="fileEncoding" value="UTF-8" />
		<property name="locations">
			<list>
				<value>classpath:jdbc.properties</value>
			</list>
		</property>
	</bean>
<!-- 資料來源配置 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"

		destroy-method="close">

		<property name="driverClass" value="${jdbc.driverClassName}" />

		<property name="jdbcUrl" value="${jdbc.url}" />

		<property name="user" value="${jdbc.username}" />

		<property name="password" value="${jdbc.password}" />

		<property name="minPoolSize">

			<value>1</value>

		</property>

		<property name="maxPoolSize" value="100" />

		<property name="initialPoolSize" value="3" />

		<!--最大空閒時間,60秒內未使用則連線被丟棄。若為0則永不丟棄。Default: 0 -->

		<property name="maxIdleTime" value="60" />

		<!--當連線池中的連線耗盡的時候c3p0一次同時獲取的連線數。Default: 3 -->

		<property name="acquireIncrement" value="5" />

		<property name="maxStatements" value="0" />

		<!--每60秒檢查所有連線池中的空閒連線。Default: 0 -->

		<property name="idleConnectionTestPeriod" value="60" />

		<!--定義在從資料庫獲取新連線失敗後重復嘗試的次數。Default: 30 -->

		<property name="acquireRetryAttempts" value="30" />

		<!-- 獲取連線失敗將會引起所有等待連線池來獲取連線的執行緒丟擲異常。但是資料來源仍有效 保留,並在下次呼叫getConnection()的時候繼續嘗試獲取連線。如果設為true,那麼在嘗試 

			獲取連線失敗後該資料來源將申明已斷開並永久關閉。Default: false -->

		<property name="breakAfterAcquireFailure" value="false" />

		<!-- 因效能消耗大請只在需要的時候使用它。如果設為true那麼在每個connection提交的 時候都將校驗其有效性。建議使用idleConnectionTestPeriod或automaticTestTable 

			等方法來提升連線測試的效能。Default: false -->

		<property name="testConnectionOnCheckout" value="false" />

	</bean>	
<!-- 定義事務管理器(宣告式的事務)-->
<!-- 支援 @Transactional 標記 -->
<!-- 方式一:DataSourceTransactionManager -->
	<bean id="transactionManager"

		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

		<property name="dataSource" ref="dataSource" />

	</bean> 
	<tx:annotation-driven transaction-manager="transactionManager"/>  

<!-- 方式二:hibernateTransactionManager -->
	<bean id="hibernateTransactionManager"

		class="org.springframework.orm.hibernate3.HibernateTransactionManager">

		<property name="sessionFactory">

			<ref local="sessionFactory" />

		</property>

	</bean>
	<!-- 配置hibernate的session工廠 -->

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="lobHandler" ref="lobHandler"/>
		<property name="mappingLocations">
			<list>
				<value>classpath*:/com/schoolnet/**/*.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<!-- 解決在Oracle多個表空間表名相同導致hibernate不會自動生成表 -->
				<prop key="hibernate.default_schema">${jdbc.username}</prop>
				<prop key="hibernate.dialect">
					org.hibernate.dialect.Oracle10gDialect
				</prop>
				<prop key="hibernate.show_sql">true</prop>
				<!--解決記憶體洩漏問題 -->
				<prop key="hibernate.generate_statistics">false</prop>
				<prop key="hibernate.connection.release_mode">
					auto
				</prop>
				<prop key="hibernate.autoReconnect">true</prop>
				<prop key="hibernate.cache.provider_class">
					org.hibernate.cache.EhCacheProvider
				</prop>
				<!--解決記憶體洩漏問題 -->
				<prop key="hibernate.cache.use_query_cache">false</prop>
				<prop key="use_second_level_cache">false</prop>
				 <prop key="hibernate.hbm2ddl.auto">update</prop>
				<prop key="current_session_context_class">thread</prop>
			</props>
		</property>
		<property name="eventListeners">
			<map>
				<entry key="merge">
					<bean
						class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener" />
				</entry>
			</map>
		</property>
	</bean>
<!--2.配置Hibernate事務特性 -->
	<tx:advice id="txAdvice" transaction-manager="hibernateTransactionManager">
		<tx:attributes>
			<tx:method name="save*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="add*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="update*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="modify*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="del*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="start*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="stop*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="assign*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="clear*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="execute*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="insert*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="do*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="set*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="*N" propagation="NEVER" />
   			<tx:method name="*" read-only="true"/>
		</tx:attributes>
	</tx:advice>
<!-- 配置那些類的方法進行事務管理 -->
	<aop:config>
		<aop:advisor pointcut="execution(* com.eshine..*.service.*.*(..))"
			advice-ref="txAdvice" />
	</aop:config>

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:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 
	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/jee http://www.springframework.org/schema/jee/spring-jee.xsd 
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
	http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

	<context:component-scan base-package="com.schoolnet" use-default-filters="false">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
	</context:component-scan>
	<mvc:annotation-driven />
	<mvc:default-servlet-handler />
	<!-- jsp檢視解析器 -->
	<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/" />
		<property name="suffix" value=".jsp" />
		<property name="order" value="0" />
		<property name="contentType" value="text/html;charset=UTF-8" />
	</bean>
     <!--多文上傳,限制1G檔案 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="1073741824" />
	</bean>
</beans>