블로그는 데모 형태의 인터셉터 사용을 알려줍니다.
프로젝트 구조는 그림에 나와 있습니다.
필요한 JAR : SpringMVC 구성에 필요한 항아리가 있으며 JSTL에 필요한 항아리가 있습니다.
SpringMVC 패키지의 기능에 대한 설명 :
AOPALLIANCE.JAR : 이 패키지는 AOP Alliance API 패키지로 패싯을위한 인터페이스가 포함되어 있습니다. 일반적으로 동적 직조 기능이있는 스프링과 같은 다른 프레임 워크는이 병에 의존합니다.
Spring-Core.jar : 이 JAR 파일에는 스프링 프레임 워크의 기본 핵심 도구 클래스가 포함되어 있습니다. Spring의 다른 모든 구성 요소는 다른 구성 요소의 기본 핵심 인이 패키지의 클래스를 사용해야합니다. 물론 자체 애플리케이션 시스템에서 이러한 도구 클래스를 사용할 수도 있습니다.
외부 의존성 커먼즈 로깅, (log4j).
Spring-Beans.jar : 이 JAR 파일은 모든 응용 프로그램에서 사용됩니다. 구성 파일에 액세스, 콩 생성 및 관리 및 제어 반전 수행이 포함됩니다.
의존성 주입 (IOC/DI) 작업은 모두 관련된 클래스입니다. 응용 프로그램에 기본 IOC/DI 지원이 필요한 경우 Spring-Core.jar 및 Spring-Beans.jar 파일을 소개하십시오.
Spring-Aop.jar : 이 JAR 파일에는 응용 프로그램에서 Spring의 AOP 기능을 사용할 때 필요한 클래스 및 소스 수준 메타 데이터 지원이 포함되어 있습니다. 선언 트랜잭션 관리와 같은 AOP를 기반으로하는 스프링 기능을 사용하고 응용 프로그램 에이 JAR 패키지도 포함하십시오.
외부 의존성 스프링 코어 (스프링 콩, AOP 연합, CGLIB, 커먼즈 속성).
Spring-Context.jar : 이 JAR 파일은 스프링 코어에 대한 많은 확장을 제공합니다. Spring ApplicationContext 기능을 사용해야하는 모든 클래스, JDNI를 찾을 수 있습니다.
모든 필수 클래스, 계측 구성 요소 및 검증 검증을위한 관련 클래스.
외부 의존성 스프링 빔, (스프링 aop).
Spring-Context-Support : MVC에 사용되는 Spring-Context 확장 지원
SPRING-WEB.JAR :이 JAR 파일에는 웹 응용 프로그램 개발 중에 스프링 프레임 워크에 사용하는 데 필요한 핵심 클래스가 포함되어 있습니다. 웹 애플리케이션 기능, Struts 및 JSF 통합 클래스를 자동으로로드하는 클래스, 파일 업로드에 대한 클래스, 필터 클래스 및 많은 수많은 공구 보조 클래스가 포함됩니다.
외부 종속성 Spring-Context, Servlet API, (JSP API, JSTL, Commons FileUpload, COS).
Spring-webmvc.jar : 이 JAR 파일에는 Spring MVC 프레임 워크와 관련된 모든 클래스가 포함되어 있습니다. 서블릿, 웹 MVC 프레임 워크, 컨트롤러 및 프레임 워크에 대한 뷰 지원이 포함되어 있습니다. 물론 응용 프로그램에서 독립형 MVC 프레임 워크를 사용하는 경우이 JAR 파일에 클래스가 필요하지 않습니다.
외부 의존성 스프링 웹, (스프링 지원, 타일, itext, poi).
Spring-Aspect.jar : Eclipse AJDT와 같은 IDE에 쉽게 통합 될 수 있도록 Spring-Aspect.jar를 지원합니다.
외부 의존성.
Spring-jdbc.jar : 이 JAR 파일에는 Spring의 JDBC 데이터 액세스를 캡슐화하는 모든 클래스가 포함되어 있습니다.
외부 의존성 스프링 빔, 스프링 앤오.
Spring-test.jar : Junit과 같은 테스트 프레임 워크의 간단한 캡슐화
Spring-Tx.jar : TX 트랜잭션 처리를위한 Spring 's Jar
Spring-Expression.jar : 스프링 표현 언어
컨트롤러 작성 :
패키지 com.mvc.action; import javax.servlet.http.httpsession; org.springframework.stereotyp.controller import; org.springframework.web.bind.annotation.requestmapping; /** * 인증 컨트롤러 로그인 */@Controller public class logincontrol {/** * 로그인 * @param 세션 * httpsession * @param username * username * @param password * @requestmapping (value =/login ") public string (httpssession session, string ustrows and string and string the string). session.setattribute ( "사용자 이름", 사용자 이름); // "리디렉션 : hello.action"을 리디렉션합니다. }/** * 시스템 종료 * @Param 세션 * 세션 * @return * @Throws Exception */@RequestMapping (value = "/logout") public String logout (httpsession session) 예외 {// clear session.invalidate (); "리디렉션 : hello.action"을 반환합니다. }} 인터셉터 작성 :
패키지 com.mvc.interceptor; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.http.httpsession; org.springframework.web.servlet.handlerinterceptor import; org.springframework.web.servlet.modelandview import; /*** 로그인 인증 인터셉터* /public class logininterceptor는 핸들러 인터셉터를 구현합니다. { /*** 핸들러가 실행 된 후이 메소드를 호출* /public void afthCompletion (httpservletrequest 요청, 객체 핸들러, 예외) 예외 {** ** 후에 핸들러가 실행 된 후, ModelAndView returns*/public void posthandle (httpservletrequest 요청, httpservletResponse 응답, 객체 핸들러, ModelView ModelandView)은 예외 {}/***핸들러 실행 전에 호출됩니다*/public boolean prehandle (httpservletrequest 요청, httpserver resance repless, got get get get get get get repuctiond). URL 문자열 url = request.getRequesturi (); //url:login.jsp는 공개적으로 액세스 할 수 있습니다. 이 데모는 login.jsp를 제외하고 가로 채 웁니다. 다른 URL은 if (url.indexof ( "login.action")> = 0) {return true; } // 세션 가져 오기 httpsession session = request.getSession (); 문자열 username = (string) session.getAttribute ( "사용자 이름"); if (username! = null) {return true; } // 조건이 조건을 충족하지 않으면 로그인 인터페이스 요청으로 점프하십시오. getRequestDispatcher ( "/web-inf/jsp/login.jsp"). forward (요청, 응답); 거짓을 반환합니다. }} SpringMVC 구성 파일 :
<? xml version = "1.0"encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : aop = "http://www.springframework.org/aop" xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance"xmlns : context = "http://www.springframework.org/schema/context"xmlns : mvc = "http://wwww.spramfffram work.org. xsi : schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/aoop http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.spramework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/sprons--com-mvc-4.0.xsd "> 스캔-> <!-동작을 스캔하고 스프링 컨테이너에 등록하고 스프링 컨테이너에 자동으로 구성됩니다-> <context : component-scan base-package = "com.mvc.action"/> <!-프로젝트 핸들러 <bean name = "/hello.action"> </bean>-> <!-프로세서 맵퍼 핸들 레미 테르핑-> <bean> <property name/> <bean> </bean> </list> </property> </bean> <!-Resolver보기-> <!-Parse JSP, jstl에 대한 기본 지원-> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <property name = "org.springframework.web.servlet.view.jstlview"> 이름 = "접미사"value = ". jsp" /> < /bean> <!-실제 개발에서 일반적으로 MVC : 주석 구동 태그를 구성해야합니다. 이 태그는 주석-> <mvc : Annotation-Driven> </mvc : annotation-driven> <!-인터셉터-> <mvc : interceptors> <!-여러 인터셉터, 순차적으로 실행 된 다중 인터셉터-> <mvc : interceptor> <mvc : 맵핑 경로 = "/** <bean> </bean> </bean> </bean> </mvc : 인터셉터> </beans>
로그인 인터페이스 :
<%@ page language = "java"import = "java.util.*"pageencoding = "utf-8"%> <%@ taglib uri = "http://java.sun.com/jsp/jstl/core"prefix = "c"%> <%string path = request.getContextPath (); String BasePath = request.getScheme ()+": //"+request.getServerName ()+":"+request.getServerport ()+path+"/"; %> <! doctype html public "-// w3c // dtd html 4.01 전환 // en"> <html> <head> <head> <base href = "<%= basepath%>"> <title> 나의 jsp 'login.jsp'시작 페이지 </title> <meta http-equiv = "no-cache" "no-cache" " http-equiv = "Cache-control"content = "no-cache"> <meta http-equiv = "chewors"content = "0"> <meta http-equiv = "keyword ="keyword1, keyword2, keyword2, keyword3 "> <meta http-equiv ="descript "> <" "rel rel rele"> type = "text/css"href = "styles.css"> -> -> </head> <body> <form action = "$ {pagecontext.request.contextpath} /login.action"method = "post"> username : <input type = "text"= "username"/> <br> password = input type = "inputy". type = "제출"value = "로그인"/> </form> </body> </html> 성공적으로 로그인 한 후 인터페이스로 이동하십시오
hello.jsp
<%@page language = "java"import = "java.util.*"pageencoding = "utf-8"%> <%@taglib uri = "http://www.springframework.org/tags"prefix = "spring"%> <%@taglib uri = "http://www.sprongrww.spronger.s" prefix = "form" %> < %@taglib uri = "http://java.sun.com/jsp/jstl/core"prefix = "c" %> < %string path = request.getContextPath (); String BasePath = request.getScheme ()+": //"+request.getServerName ()+":"+request.getServerport ()+path+"/"; %> <! docType html public "-// w3c // dtd html 4.01 Transitional // en"> <html> <head> <base href = "<%= basepath%>"> <title> 나의 jsp 'hello.jsp'시작 페이지 </title> <meta http-equiv = "no-cache" "no-cache" "pragma" http-equiv = "Cache-control"content = "no-cache"> <meta http-equiv = "chewors"content = "0"> <meta http-equiv = "keyword ="keyword1, keyword2, keyword2, keyword3 "> <meta http-equiv ="descript "> <" "rel rel rele"> type = "text/css"href = "styles.css"> -> -> </head> <hod> 현재 사용자 : $ {username} <c : if test = "$ {username! = null}"> <a href = "$ {pagecontext.request.contextpath} /logout.action.comaction. </body> </html> hellocontrol.java, 나는 그것을 Helloworld 형식으로 작성하고 프로젝트에 따라 수정해야합니다.
패키지 com.mvc.action; org.springframework.stereotyp.controller import; import org.springframework.ui.model; org.springframework.web.bind.annotation.requestmapping; //이 클래스를 핸들러 프로세서로 태그 @controller public class helloAction {@requestmapping ( "/hello") //이 컨트롤 클래스에 해당하는 URL 개발 공개 문자열 Hello (Model Model) {String Message = "SpringMvc"; // 모델 model.addattribute ( "message", message)에 대한 속성 추가; "안녕하세요"를 반환합니다. } // public modelandview handlerequest (httpservletrequest request, // httpservletResponse 응답) 예외 {// // // 페이지의 정보 줄을 프롬프트 // 문자열 메시지 = "Hello World!"; // // // 요청 객체를 통해 페이지의 정보를 표시 // //request.setattribe (”message ", message); // // ModelAndView ModelAndView = New ModelAndView (); // // request.setAttribute ()와 동일합니다. 페이지로 데이터를 전달하여 // // 모델 데이터 // modelandView.AdDoBject ( "message", message); // // set view // modelandView.setViewName ( "hello"); // // return modelandview; //}} 위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.