Вот самый простой пример
1. Создайте новый стандартный проект Javaweb
2. Импортируйте некоторые базовые пакеты JAR, необходимые для весны
3. Настройте файл web.xml
<? xml version = "1.0" Encoding = "utf-8"?> <web-app arser = "2,5" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns: xsi = "http://www.w3.org/2001/xmlschema electan "/www.w3. 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.xssd"> <>---> <>---> <>---> <>--! <mame-dame> contextConfiglocation </param-name> <param-value> classpath*: ApplicationContext*.xml, </param-value> </context-param> <!-Spring Context Загрузить слушатель-> <Lidseer> <llauser-class> org.springframework.web.context.contextulderlister </slieder-class> <//rusemile <selcoveryfile> index.jsp </wervedied-file> </werving-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-init = "false-autowire =" byname "> <Bean IDI-INIT =" false-autowire = "byname"> <bean Ide-init = "false-autowire =" byname "> <Bean IDI-init =" false-autowire = "<bean eme init =" forse-autowire = ". value = "Zhang San"/> </bean> </beans>
Бобы-корневой узел файла XML.
XMLNS - это аббревиатура XMLNAMESPACE. Поскольку имена тегов файлов XML настраиваются, теги, написанные самим собой и определены другими, вероятно, будут дублироваться, но функции различны, поэтому необходимо добавить пространство имен, чтобы отличить этот файл XML от других файлов XML, аналогичного пакетию в Java.
XMLNS: XSI - относится к файлу XML, соответствует спецификациям XML. Полное имя XSI: xmlschemainstance относится к спецификациям, за которыми строго следуют элементы, определенные в используемом файле ресурса схемы. То есть какие стандарты выполняют элементы, определенные в файле /SPRING-Beans-2.0.xsd, соответствуют?
XSI: Схемалокация - относится к спецификациям, с которыми соблюдает элемент XML в этом документе. Свойство схемы используется для ссылки (схема) схемы. Парсер может использовать этот документ для проверки документа экземпляра XML, если это необходимо. Его значение (URI) появляется в парах, первое значение представляет пространство имен, а второе значение представляет конкретное местоположение документа с шаблоном, описывающее пространство имен, разделенное пространствами.
6. Создайте новый класс объекта user.java
пакет com.po; Пользователь открытого класса {Private String name; частный возраст строк; 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 Автопогенерированный метод STUB ApplicationContext ac = new FileSystemXmlApplicationContext ("config/applicationContext.xml"); Пользователь пользователь = (пользователь) ac.getbean ("user"); System.out.println (user.getName ()); }Выход
Это позволяет построить базовую весеннюю структуру для веб -проектов. Далее мы сделаем некоторые расширения, которые будут использоваться в реальных проектах. Вы можете настроить некоторые функции или другие настройки для интеграции Spring Framework в web.xml.
<!-Фильтры кодирования символов должны быть размещены в верхней части фильтра-> <Filter> <Filter-name> EncodingFilter </filter-name> <filter-class> org.springframework.web.filter.characterencodingfilter </filter-class> <init-param> <param-name> forceencoding </filter-class> <init-param> <param-name> parameNecoding </name-name-name> </paramue> </parame-name> </parame-name> </parame-name> </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)-> <!-Этот фильтр будет использоваться с использованием Springsecurity или Apache Shiro,-> <Filect> <Filter-name> SpringSecurityFilterChain </filter-name> <filter-class> org.springframework.web.filter.delegatingfilterProxy </filter-class> </filter> <urlter-pathern> <filter-name> springsecurityfilterchain </filter-name> <url-pattern> urlersecurityfilterchain </filter> </filter-mapping> <!-объявление Spring Spring MVC DispatcherServlet-> <servlet> <servlet-name> SpringDispatcher </servlet-name> <verlet-class> org.springframework.web.servlet.dispatcherservlet </servlet-class> <init-param> <param-name-name> contextconfiglocation </servlet> <init-param> <param-name> nameconfiglocation </servlet> <init-param> <param-name> <param-name> </servlet-class> <IniceParam> <Amber-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> <!-Страница ошибки конфигурации-> <ошибка page> <ошибка Code> 404 </error-code> <location> errorpage/404.jsp </location> </error-page> <!-401 Ошибка-> <ошибка page> <Rirry-code> 401 </error-code> <socative> /errorpage/401.html </location> <! taglib.jspf и другие файлы для каждой страницы JSP-> <jsp-config> <Aglib> <Aglib-uri>/web-inf/runqianreport4.tld </taglib-uri> <taglib-location> /web-inf/runqianreport4.tld </taglib-location> </taglib> <jsp-properport. <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 = "белое пространство: pre"> </span> pageencoding = "utf-8"%> <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl"%at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at at attp://java.sun.com@ 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/fnc.tld "%> <%@ taglib ="/web-inf/tags ". <C: set var = "ctx" scope = "session" <span style = "белое пространство: pre"> < /span> value = "$ {pagecontext.request.contextPath}" />Больше функций может быть настроено в ApplicationContext.xml
<!-Больше утверждений может быть добавлено в бобы-> <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://wwww.springframe. xmlns: context = "http://www.springframework.org/schema/context" xmlns: mvc = "http://www.springframework.org/schema/mvc" xsi: schemalocation = "http://wwww.spramemema. 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-defaultawire = "byname"> <!-Define с разделом Andotations->> <! <AOP: AspectJ-autoproxy /> <MVC: Annotation-raven /> <!-Комментарий заменяет конфигурацию, автоматически сканирует базовый пакет. 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"> <значение> 1 < /value> < /property> <name = "maxPoolSize" value = "100" /> <name = "initialPoolsize" value = "3" /> <!-Максимальное время холостого хода, если соединение не используется в течение 60 секунд, соединение будет отброшено. Если это 0, это никогда не будет отброшено. По умолчанию: 0-> <name = name = "maxidletime" value = "60" /> <!-количество соединений, полученных C3P0 в одно и то же время, когда соединение в пуле соединений исчерпано. По умолчанию: 3-> <name = "eaffireIncrement" value = "5" /> <name = "maxStatements" value = "0" /> <!-Проверьте соединения на холостом порядке во всех пулах соединений каждые 60 секунд. По умолчанию: 0-> <name = name = "idleconnectionTesteStEriod" value = "60" /> <!-Определяет количество повторяющихся попыток после того, как новое соединение не удалось извлечь из базы данных. По умолчанию: 30-> <name = name = "acpireretryattempts" value = "30" /> <!-Не удалось получить соединение, приведет к тому, что все потоки ожидают, пока пул соединений получает соединение, чтобы бросить исключение. Тем не менее, источник данных по -прежнему действителен и продолжает пытаться получить соединение в следующий раз, когда вы вызовите getConnection (). Если установить True, источник данных заявит, что он был отключен и навсегда закрыт после неудачных попыток получить соединение. По умолчанию: false-> <name = "breakafteracquirefailure" value = "false" /> <!-Пожалуйста, используйте его только при необходимости из-за высокого потребления производительности. Если установить True, его достоверность будет проверена при каждом представлении подключения. Рекомендуется использовать IdleConnectionTestEStEriod или AutomatictStable для повышения производительности тестирования подключения. 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: управляемая аннотациями Transaction-Manager = "TransactionManager"/> <!-Way Two: HibernateTransactionManager-> <Bean Id = "hibernateTransactionManager"> <name = "sessionFactory"> <ref local = "SessionFactory"/> </property> </bean> <!-Конфигурация Сессионного Сессия. name = "dataSource" ref = "dataSource"/> <name = "lobhandler" ref = "lobhandler"/> <name = "mappingLocations"> <Sist> <value> classpath*:/com/schoolnet/**/*. Hbm.xml </value> </list> </propetion> <propecty name = "hibernateperties> </value> </list> </properation> <propectyperties> </value> </list> </properation> <propectyperties>- Hibernate не автоматически генерирует таблицы, когда несколько табличных пространств одинаковы в 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> <! key = "hibernate.generate_statistics"> false </prop> <prop key = "hibernate.generate_statistics"> false </prop> <prop key = "hibernate.connection.release_mode"> auto </prop> <prop key = "hibernate.autoreconce"> true </prop> <prop> " org.hibernate.cache.ehcacheprovider </prop> <!-Решение проблемы утечки памяти-> <prop key = "hibernate.cache.use_query_cache"> false </prop> <prop key = "use_second_level_cache"> false </prop> <prop = "hibernate.hbm2ddl. key = "current_session_context_class"> Thread </prop> </props> </property> <name = "eventlisteners"> <Map> <intpirt key = "merge"> <bean/> </intry> </map> </property> </bean> <!-2. Конфигурная транзакция характерно Transaction-manager = "hibernatetransactionmanager"> <tx: атрибуты> <tx: method name = "save*" opragation = "require" hollback-for = "исключение" /> <tx: method name = "add*" Propagation = "требуется" hollback-for = "Exception" /> <tx: method name = "uppartion*" Пропаганда = "xlwack-for" /> <tx: method name = "uppaltagation =" allback-for " />" /> <tx: "method =" name = "modify*" opragation = "обязательно" hollback-for = "Исключение" /> <tx: method name = "del*" oppagation = "обязательно" hollback-for = "Исключение" /> <tx: method name = "start*" Propagation = "требуется" hollback-for = "Исключение" /> <tx: method name = "stop*" Propagation = "roplback-for =" tx: tx xemposempation: "tx: tx xeception:" tx: "tx:" tx: "tx:" tx: "tx:" tx: "tx:" tx: "tx:" tx: "method name =" stop*"". name = "назначить*" Propagation = "require" hollback-for = "exception" /> <tx: method name = "clear*" oppagation = "обязательно" hollback-for = "Исключение" /> <tx: method name = "clear*" Propagation = "требуется" hollback-for = "Exception" /> <tx: method name = "execute*" execution = "uplback-for =" xechipt xextbure " /> <tx: tx name =" execute*"" exepute*"". name = "insert*" opragation = "refend" roplack-for = "Exception" /> <tx: method name = "do*" Propagation = "обязательно" Rollback-for = "Исключение" /> <TX: method name = "set*" Propagation = "Необходимый" Rollback-for = "Exception" /> <TX: Method name = "*N" Propagation = "никогда" /> <TX " />" TX: "Method ="*n "". read-only = "true"/> </tx: атрибуты> </tx: консультант> <!-Настройка методов этих классов для управления транзакциями-> <aop: config> <aop: Advisor pointcut = "execution (*com.shine ..*.Конфигурация файла 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://wwww.springframe. xmlns: context = "http://www.springframework.org/schema/context" xmlns: mvc = "http://www.springframework.org/schema/mvc" xsi: schemalocation = "http://wwww.spramemema. http://www.springframework.org/schema/beans http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http./www.schema/jee/spring-jee.xsd http:/www.schema/spring-jee.xsdh http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-30.xsd http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/context/spring-3.0.xsd http://www.springframe.orgema. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd "> <Контекст: компонент-скандальный базовый пакет =" com.schoolnet "use-default-filters =" false "> <context: filter type =" annotation "org.springframework. < /context: component-scan> <MVC: annotation-raven /> <mvc: по умолчанию-servlet-handler /> <!-jsp view parser-> <bean id = "jspviewresolver"> <property name = "prefix" value = " /" /> <name = "suffix" value = ". name = "contentType" value = "text/html; charset = utf-8"/> </bean> <!-Multi-Text upload, Limit 1G файлы-> <Bean id = "Multipresolver"> <property name = "maxuploadsize" value = "1073741824"/> </bean> </beans>
Суммировать
Выше приведено все содержание этой статьи о полном обмене кодом веб -проекта Spring Framework. Я надеюсь, что это будет полезно для всех. Заинтересованные друзья могут продолжать ссылаться на этот сайт:
Пример кода введения и индекса SpringMVC RESTC REST
Interceptor Springmvc реализует отдельный вход
Spring Integrated Redis Подробный пример кода
Если есть какие -либо недостатки, пожалуйста, оставьте сообщение, чтобы указать это. Спасибо, друзья, за вашу поддержку на этом сайте!