自定义 spring mvc 拦截器(近期项目需求实现)

简介:           需求背景:特定文件夹下任何文件不经过登录,全部拦截强制跳转登录,并客户端禁止下载服务器定制文件夹文件           经过1天多时间的各种尝试,自定义式的强大拦截器实现了,废话不说了,直接贴代码啦。    demo:       1>   根目录下 index.html 内容:               <a href="html/inde

          需求背景:特定文件夹下任何文件不经过登录,全部拦截强制跳转登录,并客户端禁止下载服务器定制文件夹文件

          经过1天多时间的各种尝试,自定义式的强大拦截器实现了,废话不说了,直接贴代码啦。


   demo:

      1>   根目录下 index.html 内容:

              <a href="html/index.html">index</a><br/>
             <a href="html/login3.html">login3.html---</a><br/>
            <a href="html/xxx.xx">xxx.xx---</a><br/>

             <a href="html/1.jpg">1.jpg---</a><br/>

             <a href="html/1.src">1.src---</a><br/>

            <a href="html/1.zip">1.zip---</a><br/>

            。。。。。任何写啦

        

       2>  dispatcher-servlet.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.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/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!--
        使Spring支持自动检测组件,如注解的Controller
    -->
<context:component-scan base-package="com.yjde.web.controller" /><!--


 
    
 
<bean  
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/html/" p:suffix=".html" /> 

--><!--<bean  
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
-->

<mvc:interceptors>
<mvc:interceptor>
<!--设置拦截的路径:具体路径的拦截-->
<!--<mvc:mapping path="/*.*" />
<mvc:mapping path="/login1.do" />
<mvc:mapping path="/login2.do" />-->

<mvc:mapping path="/*.*" />

<bean class="com.yjde.web.interceptor.TimeInterceptor">
<!--openingTime 属性指定上班时间-->
<property name="openingTime">
<value>12</value>
</property>
<!--closingTime属性指定下班时间-->
<property name="closingTime">
<value>14</value>
</property>
<!--outsideOfficeHoursPage属性指定提示页面的URL-->
<property name="outsideOfficeHoursPage">
<value>http://localhost:8080/SpringMVCInterceptor/login/login.html
</value>
</property>
</bean>
</mvc:interceptor>
</mvc:interceptors><!--

 
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource"
p:basename="message" />
 
 
--></beans>


   3> web.xml

      <web-app version="2.5" xmlns="http://java.sun.com/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/web-app_2_5.xsd">


 
<welcome-file-list>
  <welcome-file>index.html</welcome-file>
  <welcome-file>index.jsp</welcome-file>
</welcome-file-list>


<servlet>
 
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc/*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
 
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/html/*</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
 
 
<!--处理从页面传递中文到后台而出现的中文乱码问题-->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<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>
</web-app>
 

    4> java 源码:

   package com.yjde.web.interceptor;


import java.util.Calendar;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.springframework.web.servlet.ModelAndView;
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


// 重写 preHandle()方法,在业务处理器处理请求之前对该请求进行拦截处理
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
Calendar cal = Calendar.getInstance();

System.out.println(">>"+request.getRequestURL());
System.out.println(request.getRequestURI());

int hour = cal.get(Calendar.HOUR_OF_DAY); // 获取当前时间
if (openingTime <= hour && hour < closingTime) { // 判断当前是否处于工作时间段内
return true;
} else {
response.sendRedirect(outsideOfficeHoursPage); // 返回提示页面
return false;
}
}


public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object o, ModelAndView mav)
throws Exception {
System.out.println("postHandle");
}


public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object o, Exception excptn)
throws Exception {
System.out.println("afterCompletion");
}


public int getOpeningTime() {
return openingTime;
}


public void setOpeningTime(int openingTime) {
this.openingTime = openingTime;
}


public int getClosingTime() {
return closingTime;
}


public void setClosingTime(int closingTime) {
this.closingTime = closingTime;
}


public String getOutsideOfficeHoursPage() {
return outsideOfficeHoursPage;
}


public void setOutsideOfficeHoursPage(String outsideOfficeHoursPage) {
this.outsideOfficeHoursPage = outsideOfficeHoursPage;
}


}
// 可以看出,上面的代码重载了preHandle()方法,该方法在业务处理器处理请求之前被调用。在该方法中,首先获得当前的时间,判断其是否在
// openingTime和closingTime之间,如果在,返回true,这样才会调用业务控制器去处理该请求;否则直接转向一个静态页面,返回
// false,这样该请求就不会被处理。


     5>java源码:


 package com.yjde.web.controller;


import java.io.PrintWriter;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;


@Controller
public class LoginController {


@RequestMapping(value="/{username}", method = RequestMethod.GET)
public String html(@PathVariable("username") String username,HttpServletRequest request) {
System.out.println("拦截成功:"+username);
return username;
}

}



目录
相关文章
|
2月前
|
SQL Java 数据库连接
对Spring、SpringMVC、MyBatis框架的介绍与解释
Spring 框架提供了全面的基础设施支持,Spring MVC 专注于 Web 层的开发,而 MyBatis 则是一个高效的持久层框架。这三个框架结合使用,可以显著提升 Java 企业级应用的开发效率和质量。通过理解它们的核心特性和使用方法,开发者可以更好地构建和维护复杂的应用程序。
139 29
|
1月前
|
网络协议 Java Shell
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
71 7
|
3月前
|
XML Java 数据格式
使用idea中的Live Templates自定义自动生成Spring所需的XML配置文件格式
本文介绍了在使用Spring框架时,如何通过创建`applicationContext.xml`配置文件来管理对象。首先,在resources目录下新建XML配置文件,并通过IDEA自动生成部分配置。为完善配置,特别是添加AOP支持,可以通过IDEA的Live Templates功能自定义XML模板。具体步骤包括:连续按两次Shift搜索Live Templates,配置模板内容,输入特定前缀(如spring)并按Tab键即可快速生成完整的Spring配置文件。这样可以大大提高开发效率,减少重复工作。
使用idea中的Live Templates自定义自动生成Spring所需的XML配置文件格式
|
3月前
|
设计模式 XML Java
【23种设计模式·全精解析 | 自定义Spring框架篇】Spring核心源码分析+自定义Spring的IOC功能,依赖注入功能
本文详细介绍了Spring框架的核心功能,并通过手写自定义Spring框架的方式,深入理解了Spring的IOC(控制反转)和DI(依赖注入)功能,并且学会实际运用设计模式到真实开发中。
【23种设计模式·全精解析 | 自定义Spring框架篇】Spring核心源码分析+自定义Spring的IOC功能,依赖注入功能
|
3月前
|
存储 JSON 前端开发
【Spring项目】表白墙,留言板项目的实现
本文主要介绍了表白墙项目的实现,包含前端和后端代码,以及测试
|
3月前
|
前端开发 Java 数据安全/隐私保护
【SpringMVC】用户登录器项目,加法计算器项目的实现
用户登录器的实现,加法计算器的实现
|
3月前
|
JSON 前端开发 Java
|
3月前
|
NoSQL Java Redis
Spring Boot 自动配置机制:从原理到自定义
Spring Boot 的自动配置机制通过 `spring.factories` 文件和 `@EnableAutoConfiguration` 注解,根据类路径中的依赖和条件注解自动配置所需的 Bean,大大简化了开发过程。本文深入探讨了自动配置的原理、条件化配置、自定义自动配置以及实际应用案例,帮助开发者更好地理解和利用这一强大特性。
232 14
|
3月前
|
缓存 前端开发 Java
【Spring】——SpringBoot项目创建
SpringBoot项目创建,SpringBootApplication启动类,target文件,web服务器,tomcat,访问服务器
|
3月前
|
设计模式 前端开发 Java
步步深入SpringMvc DispatcherServlet源码掌握springmvc全流程原理
通过对 `DispatcherServlet`源码的深入剖析,我们了解了SpringMVC请求处理的全流程。`DispatcherServlet`作为前端控制器,负责请求的接收和分发,处理器映射和适配负责将请求分派到具体的处理器方法,视图解析器负责生成和渲染视图。理解这些核心组件及其交互原理,有助于开发者更好地使用和扩展SpringMVC框架。
74 4