服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Spring框架web项目实战全代码分享

Spring框架web项目实战全代码分享

2021-02-21 12:00zz_cl Java教程

这篇文章主要介绍了Spring框架web项目实战全代码分享,具有一定参考价值,需要的朋友可以了解下。

以下是一个最简单的示例

1、新建一个标准的javaweb项目

Spring框架web项目实战全代码分享

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

Spring框架web项目实战全代码分享

3、配置web.xml文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?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

Spring框架web项目实战全代码分享

5、对applicationcontext.xml文件做最简单的配置

?
1
2
3
4
5
6
7
8
9
10
11
12
<?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

Spring框架web项目实战全代码分享

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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、测试

?
1
2
3
4
5
6
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());
}

输出

Spring框架web项目实战全代码分享

这就实现web项目搭建基础spring框架。接下来就做一些真正项目中会用到的一些扩展
可以在web.xml中配置一些spring框架集成的功能或其他设置

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<!-- 字符编码过滤器,必须放在过滤器的最上面 -->
  <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就是做一些全局的声明

?
1
2
3
4
5
6
7
8
9
<%@ 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中配置更多的功能

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
<!-- 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文件配置

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?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项目实战全代码分享的全部内容,希望对大家有所帮助。如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

原文链接:http://blog.csdn.net/zz_cl/article/details/52502168

延伸 · 阅读

精彩推荐