Spring框架web项目实战全代码分享
以下是一个最简单的示例
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——是xmlnamespace的缩写,因为xml文件的标签名称都是自定义的,自己写的和其他人定义的标签很有可能会重复命名,而功能却不一样,所以需要加上一个namespace来区分这个xml文件和其他的xml文件,类似于java中的package。
xmlns:xsi——是指xml文件遵守xml规范,xsi全名:xmlschemainstance,是指具体用到的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>
总结
以上就是本文关于spring框架web项目实战全代码分享的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:
如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!