spring-mvc 의 차단기 응용 예
6853 단어 spring
Struts 2 와 마찬가지 로 Spring MVC 도 차단 기 를 사용 하여 요청 을 차단 처리 할 수 있 으 며,사용 자 는 사용자 정의 차단 기 를 사용 하여 특정한 기능 을 실현 할 수 있 으 며,사용자 정의 차단 기 는 Handler Interceptor 인 터 페 이 스 를 실현 해 야 한다.
[예시 23-9]Handler Interceptor 인터페이스의 코드 는 다음 과 같다.
package org.springframework.web.servlet;
import Javax.servlet.http.HttpServletRequest;
import Javax.servlet.http.HttpServletResponse;
public interface HandlerInterceptor {
// preHandle()
boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler)
throws Exception;
// postHandle()
void postHandle(
HttpServletRequest request, HttpServletResponse
response, Object
handler, ModelAndView modelAndView)
throws Exception;
// afterCompletion() DispatcherServlet
void afterCompletion(
HttpServletRequest request, HttpServletResponse
response, Object
handler, Exception ex)
throws Exception;
}
다음은 코드 중의 세 가지 방법 에 대해 설명 한다.
preHandle():이 방법 은 비 즈 니스 프로세서 처리 요청 전에 호출 되 었 으 며,이 방법 에서 사용자 요청 request 를 처리 합 니 다.프로그래머 가 이 차단 기 를 차단 처리 요청 후 다른 차단 기 를 호출 하거나 비 즈 니스 프로세서 로 처리 하기 로 결정 하면 true 로 돌아 갑 니 다.프로그래머 가 다른 구성 요 소 를 더 이상 호출 하지 않 아 도 된다 고 결정 하면 false 로 돌아 갑 니 다.
post Handle():이 방법 은 비 즈 니스 프로세서 에서 요청 을 처리 한 후 디 스 패 치 서버 가 클 라 이언 트 에 게 요청 을 되 돌려 주기 전에 호출 되 었 습 니 다.이 방법 에서 사용자 요청 request 를 처리 합 니 다.
after Complete():이 방법 은 Dispatcher Servlet 에서 요청 을 완전히 처리 한 후에 호출 되 었 습 니 다.이 방법 에서 자원 청 소 를 할 수 있 습 니 다.
스프링 MVC 프레임 의 차단 기 를 어떻게 사용 하 는 지 예 를 들 어 설명 한다.
[예제 23-10]작업 시간 에 없 는 모든 요청 을 차단 하고 이 요청 을 특정한 정적 페이지 로 전송 하 며 요청 을 처리 하지 않 습 니 다.
먼저 TimeInterceptor.Java 를 작성 합 니 다.코드 는 다음 과 같 습 니 다.
package com.examp.ch23;
import Java.util.Calendar;
import Javax.servlet.http.HttpServletRequest;
import Javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class TimeInterceptor extends HandlerInterceptorAdapter {
// HandlerInterceptorAdapter
private int openingTime; //openingTime
private int closingTime; //closingTime
private String outsideOfficeHoursPage;
//outsideOfficeHoursPage
URL
public void setOpeningTime(int openingTime) {
this.openingTime = openingTime;
}
public void setClosingTime(int closingTime) {
this.closingTime = closingTime;
}
public void setOutsideOfficeHoursPage(String outsideOfficeHoursPage) {
this.outsideOfficeHoursPage = outsideOfficeHoursPage;
}
// preHandle() ,
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler)
throws Exception {
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY); //
if (openingTime<=hour && hour<closingTime) { //
return true;
} else {
response.sendRedirect(outsideOfficeHoursPage); //
return false;
}
}
}
위의 코드 가 preHandle()방법 을 다시 불 러 왔 음 을 알 수 있 습 니 다.이 방법 은 비 즈 니스 프로세서 처리 요청 전에 호출 되 었 습 니 다.이 방법 에서 먼저 현재 시간 을 얻 고 openingTime 과 closingTime 사이 에 있 는 지 판단 합 니 다.만약 에 true 로 돌아 가면 업무 컨트롤 러 를 호출 하여 이 요청 을 처리 할 수 있 습 니 다.그렇지 않 으 면 정적 페이지 로 돌아 가 false 로 돌아 갑 니 다.이 요청 은 처리 되 지 않 습 니 다.
다음은 dispatcher Servlet-servlet.xml 에서 차단 기 를 설정 합 니 다.코드 는 다음 과 같 습 니 다.
<bean id="urlMapping" class="org.springframework.web.servlet.handler.Simple-
UrlHandlerMapping">
<property name="mappings">
<props>
<prop key="helloWorld.do">helloWorldAction</prop>
<prop key="login.do">loginController</prop>
</props>
</property>
<property name="interceptors">
<!-- interceptors -->
<list>
<ref bean="officeHoursInterceptor"/>
<!-- officeHoursInterceptor -->
</list>
</property>
</bean>
<!-- TimeInterceptor ,id officeHoursInterceptor -->
<bean id="officeHoursInterceptor"
class="com.examp.ch23.TimeInterceptor">
<!--openingTime -->
<property name="openingTime"><value>9</value></property>
<!--closingTime -->
<property name="closingTime"><value>18</value></property>
<!--outsideOfficeHoursPage URL-->
<property name="outsideOfficeHoursPage"><value>http://localhost:8080/
ch23/outsideOfficeHours.html</value></property>
</bean>
이 를 통 해 알 수 있 듯 이 위의 코드 는 bean 태그 로 TimeInterceptor 를 정의 하고 id 를 officeHoursInterceptor 로 지정 하 며 3 개의 속성 에 값 을 부여 합 니 다.url Mapping 에서
- 와
outside Office Hours.html 코드 는 간단 합 니 다.제시 어 만 출력 합 니 다.
프로그램 을 실행 하고 브 라 우 저 에서 한 페이지 를 마음대로 방문 합 니 다.요청 한 시간 이 9 시~18 시 사이 이면 이 요청 은 처리 할 수 있 습 니 다.그렇지 않 으 면 그림 23-5 와 같은 제시 어 를 되 돌려 줍 니 다.
(클릭 하여 큰 그림 보기)그림 23-5 차단 요청 효과 도
설명:제2 2 장 에서 반전 을 제어 하 는 것 이 Spring 프레임 워 크 의 핵심 사상 이 라 고 소개 했다.즉,하나의 인터페이스 로 조작 을 정의 하고 인터페이스의 실현 류 에서 이 조작 을 다시 쓴 다음 에 Spring 의 설정 파일 에서 이 인터페이스의 실현 류 를 해당 프레임 워 크 에 주입 하면 인 터 페 이 스 를 통 해 인터페이스의 실현 류 를 호출 할 수 있다.이 절 에서 말 하 는 차단 기 는 이러한 사상 을 나타 낸다.즉,Handler Interceptor Adapter 인 터 페 이 스 를 실현 하고 preHandle()방법 을 다시 쓰 며 설정 파일 에서 TimeInterceptor 의 주입 을 실현 하 는 것 이다.이렇게 하면 프레임 워 크 가 Handler InterceptorAdapter 를 호출 할 때 TimeInterceptor 류 의 preHandle()방법 으로 호출 할 수 있 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
thymeleaf로 HTML 페이지를 동적으로 만듭니다 (spring + gradle)지난번에는 에서 화면에 HTML을 표시했습니다. 이번에는 화면을 동적으로 움직여보고 싶기 때문에 입력한 문자를 화면에 표시시키고 싶습니다. 초보자의 비망록이므로 이상한 점 등 있으면 지적 받을 수 있으면 기쁩니다! ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.