가장 간단한 예입니다
1. 새로운 표준 Javaweb 프로젝트를 만듭니다
2. 스프링에 필요한 기본 항아리 패키지를 가져 오십시오
3. Web.xml 파일을 구성하십시오
<? xml version = "1.0"encoding = "utf-8"?> <web-app version = "2.5"xmlns = "http://java.sun.com/xml/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"! <CENTEXT-PARAM> <Param-Name> ContextConfigLocation </param-name> <Param-value> classPath*: ApplicationContext*.xml, </param- value> </context-param> <!-스프링 컨텍스트로드 리스너-> <layer> <lareer> <lareer> <liseer> org.springframework.weaterb.contextextexterxterxterxterterterterterterterterterterternextextertextrons. </listener> <welcome-file-list> <welcome-file> index.jsp </welcome-file> </welcome-file-list> </web-app>
4. 스프링 구성 파일 ApplicationContext 추가
5. ApplicationContext.xml 파일에서 가장 쉬운 구성을 만드십시오
<? xml 버전 = "1.0"alcoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://ww.w.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 = "<id ="id "> 값 = "Zhang San"/> </bean> </beans>
Beans- XML 파일의 루트 노드.
XMLNS- XMLNamespace의 약어입니다. XML 파일의 태그 이름이 사용자 정의되므로 자체적으로 작성되고 다른 사람이 정의한 태그는 복제 될 가능성이 있지만 기능은 다르 므로이 XML 파일을 Java의 패키지와 유사한 다른 XML 파일과 구별하기 위해 네임 스페이스를 추가해야합니다.
XMLNS : XSI- XML 파일을 말하면 XML 사양을 준수합니다. XSI : XMLSCHEMAINSTANCE의 전체 이름은 사용 된 스키마 리소스 파일에 정의 된 요소 뒤에 엄격하게 이어지는 사양을 나타냅니다. 즉, /spring-beans-2.0.xsd 파일에 정의 된 요소는 어떤 표준을 준수합니까?
XSI : Schemalocation-이 문서의 XML 요소가 준수하는 사양을 나타냅니다. 스키마 위치는 스키마 문서 (스키마)를 참조하는 데 사용됩니다. 파서는이 문서를 사용하여 필요한 경우 XML 인스턴스 문서를 확인할 수 있습니다. 값 (URI)은 쌍으로 표시되고, 첫 번째 값은 네임 스페이스를 나타내고, 두 번째 값은 공백으로 분리 된 네임 스페이스를 설명하는 패턴 문서의 특정 위치를 나타냅니다.
6. 새 엔티티 클래스 user.java를 만듭니다
패키지 com.po; 공개 클래스 사용자 {개인 문자열 이름; 개인 문자열 시대; 공개 문자열 getName () {return name; } public void setName (문자열 이름) {this.name = 이름; } public String getage () {반환 연령; } public void setage (String Age) {this.age = age; }}7. 테스트
public static void main (String [] args) {// todo 자동 생성 메소드 Stub ApplicationContext ac = new FileSystemxMlApplicationContext ( "config/applicationContext.xml"); 사용자 user = (사용자) ac.getBean ( "사용자"); System.out.println (user.getName ()); }산출
이를 통해 웹 프로젝트를위한 기본 스프링 프레임 워크를 구성 할 수 있습니다. 다음으로 실제 프로젝트에서 사용될 확장 기능을 수행합니다. web.xml에서 스프링 프레임 워크 통합을위한 일부 기능 또는 기타 설정을 구성 할 수 있습니다.
<!-문자 인코딩 필터는 필터 상단에 배치해야합니다-> <filter> <filter-name> encodingFilter </filter-name> <filter-class> org.spramework.web.filter.caracterencodingfilter </filterclass> <init-param> <param-name> <param- value> true </param- value> </init-param> <init-param> <init-param> <init-param> <param-name> 인코딩 </param-name> <param- value> utf-8 </param-value> </init-param> </filter-mapping> <filter-name> encodingfilter </filter-name> <Url-pattern>/*</url-pattern> </filter-mapping> <!-OpenSessionInView 사용-> <filter-name> OpenSessionInViewFilter </filter-name> <filter-class> org.springframework.orm.orm.opport.opensessioninviewfilter <<inittparam> <Param-Name> Singlessession </param-name> <param- value> true </param-value> </init-param> <init-param> <param-name> sessionfactorybeanname </param-name> <!-Spring 구성에서 어떤 sessionFactory를 사용하여 <param-value> </agortAm- value>를 지정하십시오. <Filter-Mapping> <filter-name> OpenSessionInViewFilter </filter-name> <Url-pattern>/*</url-pattern> </url-pattern> </url-pattern> </url-pattern> </url-pattern> </url-pattern> </url-pattern> </url-pattern> </url-pattern> </url-pattern> </url-pattern> </url-pattern> </url-pattern> </url-pattern> </url-pattern> </url-pattern> </url-pattern>-스프링 보안 필터 org.spramework.web.filter. Shiro,-> <filter> <filter-name> springsecurityfilterchain </filter-name> <filter-class> org.spramework.web.filter.delegatingfilterproxy </filter> <filter-mapping> <filter-name> springsecurityfilterchain </filter-name> <Url-pattern>/*</url-pattern> </filter-mapping> <!-선언 스프링 MVC DispatcherServlet-> <servlet-name> springdispatcher </servlet-name> <servlet-class> org.springframework.web.servlet.dispitcherservlet </servlet class> <Param-Name> ContextConfigLocation </param-name> <param-value> classpath* : spring-mvc.xml </param- value> </init-param> <load-on-startup> 1 </load-on-startup> </servlet> <! <servlet-mapping> <servlet-name> <Url-pattern>/</url-pattern> </servlet-mapping> <!-구성 오류 페이지-> <Error-Page> <Error-Code> 404 </error-code> <location> errorpage/404.jsp </location> </error-page> <!-401 Error-> <Error-Page> <Error-Code> 401 </Error-Code> <coate>/errorpage/401.html </location> </error-page> <!-각 JSP 페이지에 taglib.jspf 및 기타 파일을 소개합니다-> <jsp-config> <gaglib> <taglib-uri> /web-inf/runqianreport4.tld </taglib-uri> <taglib-inf/runqianreport4.tld </taglib-location> </taglib> <jsp-property-group> <url-pattern>* <!-<Trim-Directive-Whitespaces> true </trim-directive-whitespaces>-> </jsp-property-group> </jsp-config>
그중에서도 JSPF는 몇 가지 글로벌 진술을하는 것입니다
<%@ page language = "java"contmenttype = "text/html; charset = utf-8"<span style = "화이트 공간 : pre"> </span> pageencoding = "utf-8"%> <%@ taglib prefix = "c"uri = "http://java.sun.com/jsp/jstl/jstl/jstl/core"%> 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/jsp/jstl/fmt"%> <%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt"%> <%@ taglib prefix = "fmt"uri = "http://java.sun.com/jsp/jstl/jsp/jstl/fmt"%> <%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt"%> <%@ taglib prefix = "fmt"uri = "http://java.sun.com/jsp/jstl/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/tag ". <c : set var = "ctx"scope = "session"<span style = "white-space : pre"> < /span value = "$ {pagecontext.request.contextPath}" />ApplicationContext.xml에서 더 많은 기능을 구성 할 수 있습니다
<!-콩에 더 많은 문장을 추가 할 수 있습니다-> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://www.w.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.springframwork.org/schema/op" xmlns : context = "http://www.springframework.org/schema/context"xmlns : mvc = "http://www.springframework.org/schema/mvc"xsi : skemalocation = "http://www.spremframframwork.org/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/sprring-jee.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.spramework.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-conxt.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 ">- /> <mvc : 주석 구동 /> <!-주석은 구성을 대체하고 기본 패키지를 자동으로 스캔합니다. 스캔 패키지 및 모든 서브 포장의 모든 클래스는 컨트롤러에서 제거해야합니다. 그렇지 않으면 트랜잭션 관리에 영향을 미칩니다.-> <Context : Com.Schoolnet "> <Context :"Annotation "expression ="org.springframework.steretype.controller " /context : component sysitations> secan sysites systerates systat at rightice system : contentifities에 영향을 미칩니다. 파일-> <bean id = "propertyconfigurer"> <property name = "fileencoding"value = "utf-8"/> <property name = "locts"> <list> <sl value> classpath : jdbc.properties </value> </list> </property> </bean> </bean> <dataSource "dataSource" "norlough" "" "davestod" value = "$ {jdbc.driverclassname}" /> <속성 이름 = "jdbcurl"value = "$ {jdbc.url}" /> <property name = "user"value = "$ {jdbc.username}" /> <property name = "password"value = "$ {jdbc.password}"> <value> 1 < /value> < /property> <속성 이름 = "maxpoolsize"value = "100" /> <속성 이름 = "initialpoolsize"value = "3" /> <!-연결이 60 초 안에 사용되지 않으면 연결이 버립니다. 그것이 0이라면, 그것은 결코 폐기되지 않습니다. 기본값 : 0-> <속성 이름 = "maxIdletime"value = "60" /> <!-연결 풀의 연결이 소진 될 때 한 번에 C3P0에 의해 얻은 연결 수. 기본값 : 3-> <속성 이름 = "AcquireIncrement"value = "5" /> <속성 이름 = "maxstatements"value = "0" /> <!-60 초마다 모든 연결 풀에서 유휴 연결을 확인하십시오. 기본값 : 0-> <속성 이름 = "idleconnectionTestPeriod"value = "60" /> <!-새로운 연결이 데이터베이스에서 검색되지 않은 후 반복 시도 수를 정의합니다. 기본값 : 30-> <속성 이름 = "AcquiReretRecTempts"value = "30" /> <!-연결을 얻지 못하면 연결 풀이 예외를 던지기 위해 모든 스레드가 대기하는 모든 스레드가 발생합니다. 그러나 데이터 소스는 여전히 유효하며 다음에 getConnection ()을 호출 할 때 계속 연결하려고합니다. true로 설정되면 데이터 소스는 연결을 얻으려는 시도가 실패한 후 연결이 끊어지고 영구적으로 닫혔다 고 선언합니다. 기본값 : false-> <속성 이름 = "breakfteracquirefailure"value = "false" /> <!-고성능 소비로 인해 필요할 때만 사용하십시오. true로 설정되면 각 연결 제출시 유효성이 확인됩니다. 연결 테스트의 성능을 향상시키기 위해 IdleConnectionTestPeriod 또는 AutomaticTestTable을 사용하는 것이 좋습니다. 기본값 : false-> <property name = "testConnectionOnCheckout"value = "false" /> < /bean> <!-트랜잭션 관리자의 정의 (선언 트랜잭션)-> <!-지원 @transactional tags-> <!-way one : dataSourcetransactionManager-> <bean id = "transactionManager"> <속성 이름 = "dataSource"ref = "ref ="ref = "ref =" <TX : 주석 중심 트랜잭션-매너 = "TransactionManager"/> <!-웨이 2 : way 2 : hibernateTransactionManager-> <bean id = "hibernateTransactionManager"> <property name = "sessionFactory"> <Ref local = "sessionActory"/> </property> </bean> <!-session hibernate 's Session's indure "> <"id = "id ="id = "session hibernate의 세션 이름 = "dataSource"ref = "dataSource"/> <property name = "lobhandler"ref = "lobhandler"/> <property name = "mappinglocations"> <list> <sallocations "> <list> <value> <classpath*:/com/schoolnet/**/*. hbm.xml </value> </list> </property> <속성 이름 ="hibernateproperties ". 오라클에서 여러 테이블 스페이스가 동일 할 때 테이블을 자동으로 생성합니다. -> <prop key = "hibernate.default_schema"> $ {jdbc.username} </prop> <prop key = "hibernate.dialect"> org.hibernate.dialect.oracle10gdialect </prop> <prople key = "hibernate.show_sql"! 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"> <prop key = hibely.cache. 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.hbm22ddddddddddddl.aut. key = "current_session_context_class"> Thread </prop> </props> </property> <속성 이름 = "eventListeners"> <map> <enterd key = "merge"> <bean/> </enterd> </map> </property> </bean> <!-2. Configure Hibernate Transaction 특성-> <tx : txadvice " Transaction-Manager = "HiberNateTransactionManager"> <tx : attributes> <tx : method name = "save*"propagation = "필수"rollback-for = "exception" /> <tx : "add*"propagation = "required"rollback-for = "예외" /> <tx : method name = "propudagation ="rollback-for = "rollback-for ="rollback-for = "propagation ="rollback-for = "update" name = "modify*"propagation = "필수"롤백 -for = "예외" /> <tx : 메소드 이름 = "del*"propagation = "필수"rollback-for = "exception" /> <tx : "start*"propagation = "필수"롤백-= "예외" /> <tx : "정지*"propagation = "rollback-for ="rollback-for = "mether : 이름 = "할당*"propagation = "필수"rollback-for = "Exception" /> <tx : method name = "clear*"propagation = "필수"rollback-for = "rollback-for ="exception " /> <tx :"clear*"propagation ="rollback-for = "excection name ="execute*"propagation ="rollback-for = "rollback-for ="mether. name = "insert*"propagation = "필수"rollback-for = "exception" /> <tx : method name = "do*"propagation = "필수"롤백-"rollback-for ="exception " /> <tx :"method name = "set*"propagation = "rollback-por ="exception " /> <tx : method name ="*n "propagation ="never name = "*" read-folly = "true"/> </tx : 속성> </tx : 조언> <!-트랜잭션 관리를위한 해당 클래스의 메소드를 구성-> <aop : config> <aop : advisor pointcut = "execution (*com.eshine ..*. service.Spring-mvc.xml 파일 구성
<? xml 버전 = "1.0"alcoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://ww.w.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.springframwork.org/schema/op" xmlns : context = "http://www.springframework.org/schema/context"xmlns : mvc = "http://www.springframework.org/schema/mvc"xsi : skemalocation = "http://www.spremframframwork.org/beans http://www.springframework.org/schema/beans http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://wwww.sprompramegma/og http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.spramework.org/schema/tx/sprring-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.springframwork.org/schema/mv http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd "> <context : component-scan base-package ="com.schoolnet "use-default-filters ="false "> <context : filter type ="annotation "/>> < /context : component-scan> <mvc : mvc : mvc : default-servlet handler /> <!-jsp view parser-> <bean id = "jspviewresolver"> <property name = "prefix"value = " /" /> <spodix "value"value ". 이름 = "contenttype"value = "text/html; charset = utf-8"/> </bean> <!-멀티 텍스트 업로드, 1g 파일 제한-> <bean id = "multipartresolver"> <property name = "maxuploadsize"value = "1073741824"/>> </beans>
요약
위는 Spring Framework 웹 프로젝트의 전체 코드 공유에 대한이 기사의 모든 내용입니다. 모든 사람에게 도움이되기를 바랍니다. 관심있는 친구들은이 사이트를 계속 참조 할 수 있습니다.
SpringMVC REST 스타일 소개 및 구현 코드 예제
SpringMVC 인터셉터는 단일 사인온을 구현합니다
스프링 통합 Redis 상세 코드 샘플
단점이 있으면 메시지를 남겨 두십시오. 이 사이트를 지원해 주신 친구들에게 감사드립니다!