1. 自定义一个filter,并将这个filter定义在spring的filter之前,或者所有的filter之前
AuthenticationFilter
com.elong.xxx.AuthenticationFilter
AuthenticationFilter
/*
2. AuthenticationFilter的实现
public class AuthenticationFilterimplements Filter {
/**
* Default constructor.
*/
public CharChangeFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// perform request filtering
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
AuthenticationRequestWrapperrequestWrapper = new AuthenticationRequestWrapper(httpServletRequest);
// continue the filter chain
chain.doFilter(requestWrapper, response);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
}
}
3. AuthenticationRequestWrapper的实现
public class AuthenticationRequestWrapper extends HttpServletRequestWrapper {
private final String payload;
public AuthenticationRequestWrapper(HttpServletRequest request)
throws AuthenticationException {
super(request);
// read the original payload into the payload variable
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
// read the payload into the StringBuilder
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);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
throw new AuthenticationException(
"Error reading the request payload", ex);
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException iox) {
// ignore
}
}
}
payload = stringBuilder.toString();
// 这个地方写上你的加解密的逻辑即可
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
payload.getBytes());
ServletInputStream inputStream = new ServletInputStream() {
public int read() throws IOException {
return byteArrayInputStream.read();
}
};
return inputStream;
}
}
阅读(2402) | 评论(0) | 转发(0) |