filter代码在pujia12345提供的代码上改的;
成都创新互联是专业的宝丰网站建设公司,宝丰接单;提供成都做网站、网站建设、外贸营销网站建设,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行宝丰网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!
jsp页面的编码你设成你自己的,我用的是utf-8。
input.jsp输入后,正常跳转到handle.jsp,而禁词已经被过滤。
filter:
package test;
import java.io.*;
import javax.servlet.*;
import java.util.*;
public class MyFilter implements Filter
{
private ListString unString;
public void init(FilterConfig filterConfig) throws ServletException
{
unString = new ArrayListString();
unString.add("日");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
String content = request.getParameter("content");//需要过滤的参数
if(content!=null){
for (int i = 0; i unString.size(); i++)
{
String strIllegal = unString.get(i);
if (content.indexOf(strIllegal) = 0)
{
content = content.replaceAll(strIllegal, "");//非法字符替换成空
}
request.setAttribute("content", content);//为request设置属性保存修改后的值
}
}
chain.doFilter(request, response);
}
public void destroy()
{
//System.out.println("过滤器销毁");
}
}
//---------------------------//
web.xml:
filter
filter-namemyfilter/filter-name
filter-classtest.MyFilter/filter-class
/filter
filter-mapping
filter-namemyfilter/filter-name
url-pattern/*/url-pattern
/filter-mapping
//---------------------------//
输入页面input.jsp:
%@page contentType="text/html;charset=utf-8"%
!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""
html xmlns=""
head
titleinput.jsp/title
/head
body
form action="handle.jsp" method="post"
input type="text" name="content" /
input type="submit" value=" 提交 " /
/form
/body
/html
//---------------------------//
input提交的页面handle.jsp:
%@page contentType="text/html;charset=utf-8"%
!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""
html xmlns=""
head
title handle.jsp /title
/head
body
%
String content = (String)request.getAttribute("content");
out.println(content);
%
/body
/html
在Java的服务端开发当中,拦截器是很常见的业务场景,这里对Java开发当中几种常见的拦截器的实现方式进行记录和分析。案例说明基于Spring Boot环境。
一:实现javax.servlet.Filter接口(使用过滤器方式拦截请求)
import org.springframework.stereotype.Component;import javax.servlet.*;import java.io.IOException;import java.util.Date;@Componentpublic class TimeInterceptor implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {System.out.println("time filter init");}@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {System.out.println("time filter start");long start = new Date().getTime();filterChain.doFilter(servletRequest, servletResponse);System.out.println("time filter 耗时:"+(new Date().getTime()-start));System.out.println("time filter finish");}@Overridepublic void destroy() {System.out.println("time filter destroy");}}
如使用@Compent注解声明不需要加入其它配置即可使得拦截器生效,但是默认拦截/*,会拦截所有请求。
二:使用@Bean注入自定义拦截器,依然上面的代码,去掉@Compent注解,创建TimeWebConfig配置类:
import org.springframework.boot.web.servlet.FilterRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import java.util.ArrayList;import java.util.List;@Configurationpublic class TimeWebConfig {@Beanpublic FilterRegistrationBean timeFilter(){FilterRegistrationBean registrationBean = new FilterRegistrationBean();TimeInterceptor interceptor = new TimeInterceptor();registrationBean.setFilter(interceptor);ListString urls = new ArrayList();urls.add("/user/*");registrationBean.setUrlPatterns(urls);return registrationBean;}}
上面这两种拦截请求的实现是基于JavaEE提供的Filter接口实现的,缺点在于,该拦截器实际上是一个过滤器,执行代码的方法doFilter只提供了request,response等参数,当请求进入被过滤器拦截的时候,我们并不知道这个请求是由哪个控制器的哪个方法来执行的。
三:使用springMVC提供的拦截器,实现org.springframework.web.servlet.HandlerInterceptor接口:
创建自定义的拦截器:
import org.springframework.stereotype.Component;import org.springframework.web.method.HandlerMethod;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.util.Date;@Componentpublic class MyInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {System.out.println("preHandler");System.out.println(((HandlerMethod) handler).getBean().getClass().getName());System.out.println(((HandlerMethod) handler).getMethod().getName());httpServletRequest.setAttribute("start", new Date().getTime());return true;}@Overridepublic void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {System.out.println("postHandler");Long start = (Long) httpServletRequest.getAttribute("start");System.out.println("time interceptor 耗时:"+(new Date().getTime()-start));}@Overridepublic void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {System.out.println("afterCompletion");Long start = (Long) httpServletRequest.getAttribute("start");System.out.println("time interceptor 耗时:"+(new Date().getTime()-start));System.out.println("ex is:"+e);}}
创建配置类:
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@Configurationpublic class WebConfig extends WebMvcConfigurerAdapter {@Autowiredprivate MyInterceptor interceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(interceptor).addPathPatterns("/user/*").excludePathPatterns("/blog/*");}}
此种方式的拦截器当中我们能够获取拦截的请求对应的类和方法的相关信息,缺点在于该handler对象无法获取具体执行方法的参数信息。
四:利用Spring的切面(AOP)实现拦截器:
引入jar包:
!-- --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-aop/artifactId/dependency
创建切片类:
import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.springframework.stereotype.Component;import java.util.Date;@Aspect@Componentpublic class TimeAspect {@Around("execution(* com.qinker.controller.UserController.*(..))")public Object handlerControllerMethod(ProceedingJoinPoint point) throws Throwable {System.out.println("time aspect start");long start = new Date().getTime();Object[] args = point.getArgs();for (Object obj : args) {System.out.println("arg is:"+obj);}Object obj = point.proceed();//具体方法的返回值System.out.println("aspect 耗时:"+(new Date().getTime()-start));System.out.println("time aspect end");return obj;}}
aspectj基于AOP实现的拦截器功能十分强大,具体详解请参考spring官网网站的文档。
把弹出的网址添加到瑞星防火墙黑名单,再用瑞星卡卡清除恶意软件,修复IE!
售后响应及时
7×24小时客服热线数据备份
更安全、更高效、更稳定价格公道精准
项目经理精准报价不弄虚作假合作无风险
重合同讲信誉,无效全额退款