如何使用filter过滤器对入参进行处理(完整版)
编程微刊
共 11932字,需浏览 24分钟
·
2022-02-17 07:43
阅读本文大概需要 9 分钟。
来自:blog.csdn.net/Muscleheng/article/details/80067772
遇见的问题:
设计方案:
解决方案:
普通的表单、ajax请求; json格式的报文请求。(三步搞定)
1.普通的表单、ajax请求;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* 重写 HttpServletRequestWrapper
* 处理表单、ajax请求
* @author zhaoheng
*
*/
public class MyHttpServletRequestWrapper1 extends HttpServletRequestWrapper{
// 用于存储请求参数
private Mapparams = new HashMap ();
// 构造方法
public MyHttpServletRequestWrapper1(HttpServletRequest request) throws IOException {
super(request);
// 把请求参数添加到我们自己的map当中
this.params.putAll(request.getParameterMap());
}
/**
* 添加参数到map中
* @param extraParams
*/
public void setParameterMap(MapextraParams) {
for (Map.Entryentry : extraParams.entrySet()) {
setParameter(entry.getKey(), entry.getValue());
}
}
/**
* 添加参数到map中
* @param name
* @param value
*/
public void setParameter(String name, Object value) {
if (value != null) {
System.out.println(value);
if (value instanceof String[]) {
params.put(name, (String[]) value);
} else if (value instanceof String) {
params.put(name, new String[]{(String) value});
} else {
params.put(name, new String[]{String.valueOf(value)});
}
}
}
/**
* 重写getParameter,代表参数从当前类中的map获取
* @param name
* @return
*/
@Override
public String getParameter(String name) {
String[]values = params.get(name);
if(values == null || values.length == 0) {
return null;
}
return values[0];
}
/**
* 重写getParameterValues方法,从当前类的 map中取值
* @param name
* @return
*/
@Override
public String[] getParameterValues(String name) {
return params.get(name);
}
}
package com.zhh.filter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import com.zhh.util.request.MyHttpServletRequestWrapper1;
/**
* 参数处理验过滤器(针对ajax、表单等请求) 1.获取请求参数;2.对获取到的请求参数进行处理(解密、字符串替、请求参数分类截取等等);3.把处理后的参数放回到请求列表里面
*
* @author zhaoheng
*
*/
public class ValidatorFilter1 implements Filter {
private static final Logger log = Logger.getLogger(ValidatorFilter1.class);
/**
* 需要过滤的地址
*/
private static ListurlList = Arrays.asList("/pastOrder/filterCsF");
/**
* 是否不需要过滤
*
* @param requestUrl
* 请求的url
* @return
*/
public boolean isPast(String requestUrl) {
for (String url : urlList) {
if (requestUrl.equals(url)) {
return true;
}
}
return false;
}
@Override
public void destroy() {
}
@SuppressWarnings("unchecked")
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
log.info("过滤器2执行开始");
String url = ((HttpServletRequest) request).getRequestURI().substring(((HttpServletRequest)request).getContextPath().length());
//通过地址对特定的请求进行处理,如果不需要可以不用,如果不用,就会对使用的请求进行过滤
if (isPast(url)) {
MyHttpServletRequestWrapper1 requestWrapper1 = new MyHttpServletRequestWrapper1(
(HttpServletRequest) request);
// 1.获取需要处理的参数
String email = requestWrapper1.getParameter("email");
// 2.把处理后的参数放回去(这里是大小转小写处理)
requestWrapper1.setParameter("email", email.toLowerCase());
// 3.放行,把我们的requestWrapper1放到方法当中
chain.doFilter(requestWrapper1, response);
} else {
chain.doFilter(request, response);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
<filter>
<filter-name>ValidatorFilter1filter-name>
<filter-class>com.zhh.filter.ValidatorFilter1filter-class>
filter>
<filter-mapping>
<filter-name>ValidatorFilter1filter-name>
<url-pattern>/*url-pattern>
filter-mapping>
@Configuration
public class WebFileterConfig {
/**
* 配置过滤器
* order属性:控制过滤器加载顺序:数字越小,加载越早
* @return
*/
@Bean
public FilterRegistrationBean ValidatorFilterRegistration() {
//新建过滤器注册类
FilterRegistrationBean registration = new FilterRegistrationBean();
// 添加我们写好的过滤器
registration.setFilter( new ValidatorFilter1());
// 设置过滤器的URL模式
registration.addUrlPatterns("/*");
registration.setOrder(Integer.MAX_VALUE-10);
return registration;
}
}
/**
* 过滤方法测试
*/
@RequestMapping("/filterCsF2")
public void filterCs22(String email,String userName){
System.out.println("处理后的参数:"+userName+" "+email);
}
html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>请求demotitle>
head>
<body>
<form id="userForm" action="#" method="post">
username:<input type="text" id ="userName" name="userName" value="21088888"/><br/><br>
email:<input type="text" id ="email" name="email" value="zhaoHENG@163.com"/><br/><br/>
age:<input type="text" id ="age" name="age" value="18"/><br/><br/>
<input type="reset" value="重置"/>
<input type="button" id ="sub" value="提交">
form>
body>
<script src="jquery.min.js">script>
<script type="text/javascript">
$("#sub").click(
function(){
var userName = $("#userName").val();
var email = $("#email").val();
var age = $("#age").val();
$.ajax({
type : "POST",
url:'http://127.0.0.1:8080/merchant_wap/pastOrder/filterCsF2',
dataType : "json",
data : {
"userName":userName,
"age":age,
"email":email
},
success : function(data) {
alert("33");
},
error : function(data) {
alert("cccc"+data.email);
}
});
}
);
script>
html>
处理后的参数:21088888 zhaoheng@163.com
2.json格式的报文请求;
package com.zhh.util.request;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import jodd.io.StreamUtil;
/**
* 重写 HttpServletRequestWrapper
* 处理json报文请求
* @author zhaoheng
*
*/
public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper{
private byte[] body; //用于保存读取body中数据
public MyHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
//读取请求的数据保存到本类当中
body = StreamUtil.readBytes(request.getReader(), "UTF-8");
}
//覆盖(重写)父类的方法
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
//覆盖(重写)父类的方法
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public int read() throws IOException {
return bais.read();
}
};
}
/**
* 获取body中的数据
* @return
*/
public byte[] getBody() {
return body;
}
/**
* 把处理后的参数放到body里面
* @param body
*/
public void setBody(byte[] body) {
this.body = body;
}
}
package com.zhh.filter;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhh.util.request.MyHttpServletRequestWrapper;
/**
* 参数校验过滤器(针对json报文请求) 1.获取请求参数;2.对获取到的请求参数进行处理(解密、字符串替、请求参数分类截取等等);3.把处理后的参数放回到请求列表里面
*
* @author zhaoheng
*
*/
public class ValidatorFilter implements Filter {
private static final Logger log = Logger.getLogger(ValidatorFilter.class);
/**
* 需要过滤的地址
*/
private static ListurlList = Arrays.asList("/pastOrder/filterCs");
/**
* 是否需要过滤
*
* @param requestUrl
* 请求的url
* @return
*/
public boolean isPast(String requestUrl) {
for (String url : urlList) {
if (requestUrl.equals(url)) {
return true;
}
}
return false;
}
@Override
public void destroy() {
log.info("过滤器执行结束");
}
@SuppressWarnings("unchecked")
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
log.info("过滤器1执行开始");
String url0 = ((HttpServletRequest) request).getRequestURI();
String url1 = ((HttpServletRequest) request).getContextPath();
System.out.println("完整地址:"+url0);
System.out.println("返回当前页面所在的应用的名字:"+url1);
System.out.println("返回当前页面所在的应用的名字长度:"+url1.length());
// 获取请求地址
String url = ((HttpServletRequest) request).getRequestURI().substring(((HttpServletRequest)request).getContextPath().length());
System.out.println("截取后的地址:"+url);
if (isPast(url)) {
//处理json报文请求
MyHttpServletRequestWrapper requestWrapper = new MyHttpServletRequestWrapper(
(HttpServletRequest) request);
// 读取请求内容
BufferedReader br;
br = requestWrapper.getReader();
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
// 将json字符串转换为json对象
JSONObject jsonObject = JSONObject.parseObject(sb.toString());
Mapmap = new HashMap ();
// 把json对象转换为Map集合
map = JSON.toJavaObject(jsonObject, Map.class);
for (Entryentry : map.entrySet()) {
// 把邮箱地址转换为小写
if (entry.getKey().equals("email")) {
map.put(entry.getKey(), entry.getValue().toString()
.toLowerCase());
}
}
// 把参数转换之后放到我们的body里面
String json = JSON.toJSONString(map);
requestWrapper.setBody(json.getBytes("UTF-8"));
// 放行
chain.doFilter(requestWrapper, response);
} else {
chain.doFilter(request, response);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
<filter>
<filter-name>ValidatorFilterfilter-name>
<filter-class>com.zhh.filter.ValidatorFilterfilter-class>
filter>
<filter-mapping>
<filter-name>ValidatorFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
@Configuration
public class WebFileterConfig {
/**
* 配置过滤器
* order属性:控制过滤器加载顺序:数字越小,加载越早
* @return
*/
@Bean
public FilterRegistrationBean ValidatorFilterRegistration() {
//新建过滤器注册类
FilterRegistrationBean registration = new FilterRegistrationBean();
// 添加我们写好的过滤器
registration.setFilter( new ValidatorFilter());
// 设置过滤器的URL模式
registration.addUrlPatterns("/*");
registration.setOrder(Integer.MAX_VALUE-10);
return registration;
}
}
/**
* 过滤方法测试
* @RequestBody User user 该注解用于接收json请求的参数
* @return
*/
@ResponseBody
@RequestMapping(value = "/filterCs")
public User filterCs(@RequestBody User user){
System.out.println(user.toString());
return user;
}
{
"email": "zhaoHENG@163.com",
"userName":"20181100",
"age":"18"
}
{
"email": "zhaoheng@163.com",
"userName":"20181100",
"age":"18"
}
往期干货:
26个经典微信小程序+35套微信小程序源码+微信小程序合集源码下载(免费)
干货~~~2021最新前端学习视频~~速度领取
前端书籍-前端290本高清pdf电子书打包下载
点赞和在看就是最大的支持❤️
评论