您好,登錄后才能下訂單哦!
以下是一個(gè)最簡單的示例
1、新建一個(gè)標(biāo)準(zhǔn)的javaweb項(xiàng)目
2、導(dǎo)入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"> <!-- 應(yīng)用程序Spring上下文配置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:applicationContext*.xml, </param-value> </context-param> <!-- spring上下文加載監(jiān)聽器 --> <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文件的根節(jié)點(diǎn)。
xmlns——是XMLNameSpace的縮寫,因?yàn)閄ML文件的標(biāo)簽名稱都是自定義的,自己寫的和其他人定義的標(biāo)簽很有可能會(huì)重復(fù)命名,而功能卻不一樣,所以需要加上一個(gè)namespace來區(qū)分這個(gè)xml文件和其他的xml文件,類似于java中的package。
xmlns:xsi——是指xml文件遵守xml規(guī)范,xsi全名:xmlschemainstance,是指具體用到的schema資源文件里定義的元素所準(zhǔn)守的規(guī)范。即/spring-beans-2.0.xsd這個(gè)文件里定義的元素遵守什么標(biāo)準(zhǔn)。
xsi:schemaLocation——是指,本文檔里的xml元素所遵守的規(guī)范,schemaLocation屬性用來引用(schema)模式文檔,解析器可以在需要的情況下使用這個(gè)文檔對XML實(shí)例文檔進(jìn)行校驗(yàn)。它的值(URI)是成對出現(xiàn)的,第一個(gè)值表示命名空間,第二個(gè)值則表示描述該命名空間的模式文檔的具體位置,兩個(gè)值之間以空格分隔。
6、新建一個(gè)實(shí)體類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()); }
輸出
這就實(shí)現(xiàn)web項(xiàng)目搭建基礎(chǔ)spring框架。接下來就做一些真正項(xiàng)目中會(huì)用到的一些擴(kuò)展
可以在web.xml中配置一些spring框架集成的功能或其他設(shè)置
<!-- 字符編碼過濾器,必須放在過濾器的最上面 --> <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> <!-- 配置延遲加載時(shí)使用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配置中哪個(gè)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就會(huì)用到這個(gè)過濾器,--> <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> <!-- 配置出錯(cuò)頁面 --> <error-page> <error-code>404</error-code> <location>errorpage/404.jsp</location> </error-page> <!-- 401錯(cuò)誤 --> <error-page> <error-code>401</error-code> <location>/errorpage/401.html</location> </error-page> <!-- 為每個(gè)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 > </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 > </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 注釋代替配置,自動(dòng)掃描的基礎(chǔ)包,將掃描該包以及所有子包下的所有類需要把controller去掉,否則影響事務(wù)管理 --> <context:component-scan base-package="com.schoolnet"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- 配置系統(tǒng)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> <!-- 數(shù)據(jù)源配置 --> <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" /> <!--最大空閑時(shí)間,60秒內(nèi)未使用則連接被丟棄。若為0則永不丟棄。Default: 0 --> <property name="maxIdleTime" value="60" /> <!--當(dāng)連接池中的連接耗盡的時(shí)候c3p0一次同時(shí)獲取的連接數(shù)。Default: 3 --> <property name="acquireIncrement" value="5" /> <property name="maxStatements" value="0" /> <!--每60秒檢查所有連接池中的空閑連接。Default: 0 --> <property name="idleConnectionTestPeriod" value="60" /> <!--定義在從數(shù)據(jù)庫獲取新連接失敗后重復(fù)嘗試的次數(shù)。Default: 30 --> <property name="acquireRetryAttempts" value="30" /> <!-- 獲取連接失敗將會(huì)引起所有等待連接池來獲取連接的線程拋出異常。但是數(shù)據(jù)源仍有效 保留,并在下次調(diào)用getConnection()的時(shí)候繼續(xù)嘗試獲取連接。如果設(shè)為true,那么在嘗試 獲取連接失敗后該數(shù)據(jù)源將申明已斷開并永久關(guān)閉。Default: false --> <property name="breakAfterAcquireFailure" value="false" /> <!-- 因性能消耗大請只在需要的時(shí)候使用它。如果設(shè)為true那么在每個(gè)connection提交的 時(shí)候都將校驗(yàn)其有效性。建議使用idleConnectionTestPeriod或automaticTestTable 等方法來提升連接測試的性能。Default: false --> <property name="testConnectionOnCheckout" value="false" /> </bean> <!-- 定義事務(wù)管理器(聲明式的事務(wù))--> <!-- 支持 @Transactional 標(biāo)記 --> <!-- 方式一: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多個(gè)表空間表名相同導(dǎo)致hibernate不會(huì)自動(dòng)生成表 --> <prop key="hibernate.default_schema">${jdbc.username}</prop> <prop key="hibernate.dialect"> org.hibernate.dialect.Oracle10gDialect </prop> <prop key="hibernate.show_sql">true</prop> <!--解決內(nèi)存泄漏問題 --> <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> <!--解決內(nèi)存泄漏問題 --> <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事務(wù)特性 --> <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> <!-- 配置那些類的方法進(jìn)行事務(wù)管理 --> <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>
總結(jié)
以上就是本文關(guān)于Spring框架web項(xiàng)目實(shí)戰(zhàn)全代碼分享的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站:
springmvc Rest風(fēng)格介紹及實(shí)現(xiàn)代碼示例
SpringMVC攔截器實(shí)現(xiàn)單點(diǎn)登錄
Spring集成Redis詳解代碼示例
如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。