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项目实战全代码分享的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:

springmvc Rest风格介绍及实现代码示例

SpringMVC拦截器实现单点登录

Spring集成Redis详解代码示例

如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。