Here is a simplest example
1. Create a new standard javaweb project
2. Import some basic jar packages required for spring
3. Configure the web.xml file
<?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 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- Application Spring Context Configuration--> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:applicationContext*.xml, </param-value> </context-param> <!-- spring context loading listener--> <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. Add spring configuration file applicationContext
5. Make the easiest configuration of the applicationContext.xml file
<?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"> <property name="name" value="Zhang San"/> </bean> </beans>
beans-the root node of the xml file.
xmlns - is the abbreviation of XMLNameSpace. Because the tag names of XML files are customized, the tags written by themselves and defined by others are likely to be duplicated, but the functions are different, so a namespace needs to be added to distinguish this xml file from other xml files, similar to package in java.
xmlns:xsi - refers to the xml file complies with the xml specifications. The full name of xsi: xmlschemainstance refers to the specifications that are strictly followed by the elements defined in the schema resource file used. That is, what standards do the elements defined in the /spring-beans-2.0.xsd file comply with?
xsi:schemaLocation - refers to the specifications that the xml element in this document complies with. The schemaLocation property is used to reference (schema) schema document. The parser can use this document to verify the XML instance document if needed. Its value (URI) appears in pairs, the first value represents the namespace, and the second value represents the specific location of the pattern document describing the namespace, separated by spaces.
6. Create a new entity class 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. Test
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()); }Output
This enables the construction of a basic spring framework for web projects. Next, we will do some extensions that will be used in real projects. You can configure some functions or other settings for spring framework integration in web.xml.
<!-- Character encoding filters must be placed at the top of the filter --> <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> <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> <!-- Use 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> <!--Specify which sessionFactory in Spring configuration to use OpenSessionInView--> <param-value>sessionFactory</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- spring security filter org.springframework.web.filter.DelegatingFilterProxy (delegate filter proxy) --> <!-- This filter will be used using springSecurity or 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> <!-- Declaration 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> <!-- Configuration error page--> <error-page> <error-code>404</error-code> <location>errorpage/404.jsp</location> </error-page> <!-- 401 Error--> <error-page> <error-code>401</error-code> <location>/errorpage/401.html</location> </error-page> <!-- Introduce taglib.jspf and other files for each jsp page--> <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>
Among them, jspf is to make some global statements
<%@ 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="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@ taglib prefix="fmt" uri="h 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}" />More functions can be configured in applicationContext.xml
<!-- More statements can be added to 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"> <!-- Define the section with annotations--> <aop:aspectj-autoproxy /> <mvc:annotation-driven /> <!-- The comment replaces configuration, automatically scans the basic package. The scan package and all classes under all subpackages need to be removed from the controller, otherwise it will affect transaction management --> <context:component-scan base-package="com.schoolnet"> <context:exclude-filter type="annotation" expression="org.springframework.steretype.Controller" /> </context:component-scan> <!-- Configure system properties configuration file--> <bean id="propertyConfigurer" > <property name="fileEncoding" value="UTF-8" /> <property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> </bean> <!-- Data source configuration--> <bean id="dataSource" 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" /> <!--Maximum idle time, if the connection is not used within 60 seconds, the connection will be discarded. If it is 0, it will never be discarded. Default: 0 --> <property name="maxIdleTime" value="60" /> <!--The number of connections obtained by c3p0 at the same time at one time when the connection in the connection pool is exhausted. Default: 3 --> <property name="acquireIncrement" value="5" /> <property name="maxStatements" value="0" /> <!--Check idle connections in all connection pools every 60 seconds. Default: 0 --> <property name="idleConnectionTestPeriod" value="60" /> <!--Defines the number of repeated attempts after a new connection failed to be retrieved from the database. Default: 30 --> <property name="acquireRetryAttempts" value="30" /> <!-- Failed to obtain the connection will cause all threads waiting for the connection pool to obtain the connection to throw an exception. However, the data source is still valid and continues to try to get the connection the next time you call getConnection(). If set to true, the data source will declare that it has been disconnected and permanently closed after failed attempts to obtain the connection. Default: false --> <property name="breakAfterAcquireFailure" value="false" /> <!-- Please only use it when needed due to high performance consumption. If set to true, its validity will be verified at each connection submission. It is recommended to use idleConnectionTestPeriod or automaticTestTable to improve the performance of connection testing. Default: false --> <property name="testConnectionOnCheckout" value="false" /> </bean> <!-- Definition of transaction manager (declarative transaction) --> <!-- Support @Transactional tags --> <!-- Way one: DataSourceTransactionManager --> <bean id="transactionManager" > <property name="dataSource" ref="dataSource" /> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- Way two: hibernateTransactionManager --> <bean id="hibernateTransactionManager" > <property name="sessionFactory"> <ref local="sessionFactory" /> </property> </bean> <!-- Configure hibernate's session factory--> <bean id="sessionFactory" > <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> <!-- Solve that hibernate does not automatically generate tables when multiple tablespaces are the same in Oracle. --> <prop key="hibernate.default_schema">${jdbc.username}</prop> <prop key="hibernate.dialect"> org.hibernate.dialect.Oracle10gDialect </prop> <prop key="hibernate.show_sql">true</prop> <!-- Solve memory leak problem--> <prop key="hibernate.generate_statistics">false</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> <!--Solve memory leak problem--> <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 /> </entry> </map> </property> </bean> <!--2.Configure Hibernate transaction characteristics--> <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="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> <!-- Configure methods of those classes for transaction management --> <aop:config> <aop:advisor pointcut="execution(* com.eshine..*.service.*.*(..))" advice-ref="txAdvice" /> </aop:config>spring-mvc.xml file configuration
<?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 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/spring-context-3.0.xsd 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.steretype.Controller" /> </context:component-scan> <mvc:annotation-driven /> <mvc:default-servlet-handler /> <!-- jsp view parser--> <bean id="jspViewResolver"> <property name="prefix" value="/" /> <property name="suffix" value=".jsp" /> <property name="order" value="0" /> <property name="contentType" value="text/html;charset=UTF-8" /> </bean> <!--Multi-text upload, limit 1G files--> <bean id="multipartResolver"> <property name="maxUploadSize" value="1073741824" /> </bean> </beans>
Summarize
The above is all the content of this article about the full code sharing of Spring framework web project. I hope it will be helpful to everyone. Interested friends can continue to refer to this site:
Springmvc Rest style introduction and implementation code example
SpringMVC interceptor implements single sign-on
Spring Integrated Redis Detailed Code Sample
If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!