1.最近在开发一个项目 ,需要进行一个全局拦截器的处理,进行拦截所有的get、post请求的操作;避免所有的方法都进行该用户名、工号的赋值,减少重复工作,这个找了许多的案例,最后还是调试出来了,现在做一个分享,避免相关小伙伴遇到同样的问题。
代码语言:javascript复制@Component
public class HttpServletFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
Map<String, String[]> m = new HashMap<String, String[]>(request.getParameterMap());
if(((HttpServletRequest) request).getMethod().toUpperCase().equals("GET"))
{
}
ParameterRequestWrapper parameterRequestWrapper = new ParameterRequestWrapper((HttpServletRequest) request, m);
//继续向后传递修改后的request,拦截器不能实现。
chain.doFilter(parameterRequestWrapper, response);
}
@Override
public void destroy() {
}
代码语言:javascript复制/**
* 读取body的值
*
* @param request
*/
private void renewBody(HttpServletRequest request) {
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
以上是关键代码的处理,如果有调试不过的小伙伴可以留言一起来探讨一下。