- 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;
- }
- }
- }
配置文件
- <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>