Spring框架web項(xiàng)目實(shí)戰(zhàn)全代碼分享
以下是一個(gè)最簡(jiǎn)單的示例
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)聽(tīng)器 -->
<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、對(duì)applicationContext.xml文件做最簡(jiǎn)單的配置
<?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的縮寫(xiě),因?yàn)閄ML文件的標(biāo)簽名稱(chēng)都是自定義的,自己寫(xiě)的和其他人定義的標(biāo)簽很有可能會(huì)重復(fù)命名,而功能卻不一樣,所以需要加上一個(gè)namespace來(lái)區(qū)分這個(gè)xml文件和其他的xml文件,類(lèi)似于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屬性用來(lái)引用(schema)模式文檔,解析器可以在需要的情況下使用這個(gè)文檔對(duì)XML實(shí)例文檔進(jìn)行校驗(yàn)。它的值(URI)是成對(duì)出現(xiàn)的,第一個(gè)值表示命名空間,第二個(gè)值則表示描述該命名空間的模式文檔的具體位置,兩個(gè)值之間以空格分隔。
6、新建一個(gè)實(shí)體類(lèi)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、測(cè)試
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框架。接下來(lái)就做一些真正項(xiàng)目中會(huì)用到的一些擴(kuò)展
可以在web.xml中配置一些spring框架集成的功能或其他設(shè)置
<!-- 字符編碼過(guò)濾器,必須放在過(guò)濾器的最上面 -->
<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>
<!--指定對(duì)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過(guò)濾器 org.springframework.web.filter.DelegatingFilterProxy(委托過(guò)濾器代理)-->
<!-- 使用springSecurity或apache shiro就會(huì)用到這個(gè)過(guò)濾器,-->
<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ò)頁(yè)面 -->
<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頁(yè)面引入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 注釋代替配置,自動(dòng)掃描的基礎(chǔ)包,將掃描該包以及所有子包下的所有類(lèi)需要把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ù)庫(kù)獲取新連接失敗后重復(fù)嘗試的次數(shù)。Default: 30 -->
<property name="acquireRetryAttempts" value="30" />
<!-- 獲取連接失敗將會(huì)引起所有等待連接池來(lái)獲取連接的線程拋出異常。但是數(shù)據(jù)源仍有效 保留,并在下次調(diào)用getConnection()的時(shí)候繼續(xù)嘗試獲取連接。如果設(shè)為true,那么在嘗試
獲取連接失敗后該數(shù)據(jù)源將申明已斷開(kāi)并永久關(guān)閉。Default: false -->
<property name="breakAfterAcquireFailure" value="false" />
<!-- 因性能消耗大請(qǐng)只在需要的時(shí)候使用它。如果設(shè)為true那么在每個(gè)connection提交的 時(shí)候都將校驗(yàn)其有效性。建議使用idleConnectionTestPeriod或automaticTestTable
等方法來(lái)提升連接測(cè)試的性能。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)存泄漏問(wèn)題 -->
<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)存泄漏問(wèn)題 -->
<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>
<!-- 配置那些類(lèi)的方法進(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)全代碼分享的全部?jī)?nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站:
springmvc Rest風(fēng)格介紹及實(shí)現(xiàn)代碼示例
SpringMVC攔截器實(shí)現(xiàn)單點(diǎn)登錄
如有不足之處,歡迎留言指出。感謝朋友們對(duì)本站的支持!
相關(guān)文章
Java處理異常2種機(jī)制關(guān)鍵字區(qū)別解析
這篇文章主要介紹了java處理異常2種機(jī)制關(guān)鍵字區(qū)別解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-01-01
springboot開(kāi)發(fā)擴(kuò)展springmvc實(shí)現(xiàn)解析
這篇文章主要介紹了springboot開(kāi)發(fā)擴(kuò)展springmvc實(shí)現(xiàn)解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02
java數(shù)據(jù)結(jié)構(gòu)與算法之雙向循環(huán)隊(duì)列的數(shù)組實(shí)現(xiàn)方法
這篇文章主要介紹了java數(shù)據(jù)結(jié)構(gòu)與算法之雙向循環(huán)隊(duì)列的數(shù)組實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了雙向循環(huán)隊(duì)列的原理與數(shù)組實(shí)現(xiàn)技巧,并附帶說(shuō)明了該算法的用途,需要的朋友可以參考下2016-08-08
RabbitMQ?延遲隊(duì)列實(shí)現(xiàn)訂單支付結(jié)果異步階梯性通知(實(shí)例代碼)
這篇文章主要介紹了RabbitMQ?延遲隊(duì)列實(shí)現(xiàn)訂單支付結(jié)果異步階梯性通知,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-02-02
Java實(shí)現(xiàn)根據(jù)前端所要格式返回樹(shù)形3級(jí)層級(jí)數(shù)據(jù)
這篇文章主要為大家詳細(xì)介紹了Java如何實(shí)現(xiàn)根據(jù)前端所要格式返回樹(shù)形3級(jí)層級(jí)數(shù)據(jù),文中的示例代碼講解詳細(xì),有需要的小伙伴可以了解下2024-02-02
java通過(guò)snmp協(xié)議獲取物理設(shè)備信息
這篇文章主要介紹了java通過(guò)snmp協(xié)議獲取物理設(shè)備信息,snmp中文含義是簡(jiǎn)單網(wǎng)絡(luò)管理協(xié)議,可用完成對(duì)計(jì)算機(jī)、路由器和其他網(wǎng)絡(luò)設(shè)備的遠(yuǎn)程管理和監(jiān)視,本文我們是通過(guò)java程序來(lái)獲取,需要的朋友可以參考下2023-07-07
Java 超詳細(xì)圖解集合框架的數(shù)據(jù)結(jié)構(gòu)
什么是集合框架呢?集合框架是為表示和操作集合而規(guī)定的一種統(tǒng)一的標(biāo)準(zhǔn)的體系結(jié)構(gòu)。最簡(jiǎn)單的集合如數(shù)組、列表和隊(duì)列等,任何集合框架一般包含:對(duì)外的接口、接口的實(shí)現(xiàn)和對(duì)集合運(yùn)算的算法2022-04-04

