Filter过滤器进行统一参数处理demo

Filter过滤器进行统一参数处理demo

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class ReplaceStreamFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(ReplaceStreamFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("StreamFilter初始化...");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        //获取请求中的流,将取出来的字符串,再次转换成流,然后把它放入到新request对象中,
        if (request instanceof HttpServletRequest) {
            log.info(">>>ChangeStudentNameRequestWrapper");
            requestWrapper = new ChangeStudentNameRequestWrapper((HttpServletRequest) request);
        }
        // 在chain.doFiler方法中传递新的request对象
        if (requestWrapper == null) {
            chain.doFilter(request, response);
        } else {
            log.info(">>>chain.doFilter requestWrapper");
            chain.doFilter(requestWrapper, response);
        }
    }

    @Override
    public void destroy() {
        log.info("StreamFilter销毁...");
    }
}



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.mytester.entity.Student;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.Charset;

public class ChangeStudentNameRequestWrapper extends HttpServletRequestWrapper {
    /**
     * 存储body数据的容器
     */
    private byte[] body;

    /**
     * 构造函数
     * @param request
     * @throws IOException
     */
    public ChangeStudentNameRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        //接下来的request使用这个
        String bodyStr = getBodyString(request);
        body = bodyStr.getBytes(Charset.defaultCharset());
    }

    /**
     * 获取请求Body
     *
     * @param request request
     * @return String
     */
    public String getBodyString(final ServletRequest request) {
        try {
            return inputStream2String(request.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取请求Body
     *
     * @return String
     */
//    public String getBodyString() {
//        final InputStream inputStream = new ByteArrayInputStream(body);
//        return inputStream2String(inputStream);
//    }

    /**
     * 将inputStream里的数据读取出来并转换成字符串
     *
     * @param inputStream inputStream
     * @return String
     */
    private String inputStream2String(InputStream inputStream) {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.defaultCharset()));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        JSONObject jsonObject = JSONObject.parseObject(sb.toString());
        if (jsonObject != null) {
            System.out.println("json=" + jsonObject.toString());

            Student student = JSONObject.parseObject(jsonObject.toString(), Student.class);

            System.out.println("修改之前的学生名称为:" + student.getName());
            student.setName("amd-modify");  //改变值
            return JSON.toJSONString(student);
        }
        return sb.toString();
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }
    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream inputStream = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return inputStream.read();
            }
            @Override
            public boolean isFinished() {
                return false;
            }
            @Override
            public boolean isReady() {
                return false;
            }
            @Override
            public void setReadListener(ReadListener readListener) {
            }
        };
    }
}


import java.io.Serializable;

public class Student implements Serializable{
    
    private static final long serialVersionUID = -339516038496531943L;
    private String sno;
    private String name;
    private String sex;
    public String getSno() {
        return sno;
    }
    public void setSno(String sno) {
        this.sno = sno;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sno='" + sno + '\'' +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }
}

//注册
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;

@Configuration
public class MyFilterConfig {
    /**
     * 注册过滤器
     * 未设置addUrlPatterns,默认是全部的拦截
     * @return FilterRegistrationBean
     */
    @Bean
    public FilterRegistrationBean someFilterRegistration() {
        FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
        registration.setFilter(replaceStreamFilter());
        registration.addUrlPatterns("/changeStudentName");
        registration.setName("replaceStreamFilter");
        return registration;
    }

    /**
     * 实例化StreamFilter
     *
     * @return Filter
     */
    @Bean(name = "replaceStreamFilter")
    public Filter replaceStreamFilter() {
        return new ReplaceStreamFilter();
    }
}


//测试
@RestController
public class TestController {
    /**
     * http://localhost:8080/changeStudentName
     * 参数:{"sno":"1112","name":"xiaoming","sex":"man"}
     * 返回:
     * Student{sno='1112', name='amd-modify', sex='man'}
     *
     * @param student
     * @return
     */
    @RequestMapping(value = "/changeStudentName", method = RequestMethod.POST)
    public String changeStudentName(@RequestBody Student student, HttpServletRequest request) {
        return student.toString();
    }
}

 

posted on 2022-10-11 16:03  oktokeep  阅读(102)  评论(1编辑  收藏  举报