实现功能:
所有接口经过过滤器,获取每个接口的自定义头部(token)
判断如果是app访问,则给头部设置cookie,值为自定义token的值。
即:使用过滤器实现修改请求头headers
实现步骤:
1.自定义过滤器 ModifyParametersFilter.java 并继承 OncePerRequestFilter
package com.mobile.web.common; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*; /**
* 自定义的过滤器,
* Created by Administrator on 2017/6/19 0019.
*/
public class ModifyParametersFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
// 修改cookie
ModifyHttpServletRequestWrapper mParametersWrapper = new ModifyHttpServletRequestWrapper(request);
String token = request.getHeader("token");
if (token != null && !"".equals(token)) {
mParametersWrapper.putCookie("JSESSIONID", token);
}
// finish
filterChain.doFilter(mParametersWrapper, response);
} /**
* 修改cookie信息
*/
private class ModifyHttpServletRequestWrapper extends HttpServletRequestWrapper {
private Map<String, String> mapCookies;
ModifyHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
this.mapCookies = new HashMap<>();
}
void putCookie(String name, String value) {
this.mapCookies.put(name, value);
}
public Cookie[] getCookies() {
HttpServletRequest request = (HttpServletRequest) getRequest();
Cookie[] cookies = request.getCookies();
if (mapCookies == null || mapCookies.isEmpty()) {
return cookies;
}
if (cookies == null || cookies.length == 0) {
List<Cookie> cookieList = new LinkedList<>();
for (Map.Entry<String, String> entry : mapCookies.entrySet()) {
String key = entry.getKey();
if (key != null && !"".equals(key)) {
cookieList.add(new Cookie(key, entry.getValue()));
}
}
if (cookieList.isEmpty()) {
return cookies;
}
return cookieList.toArray(new Cookie[cookieList.size()]);
} else {
List<Cookie> cookieList = new ArrayList<>(Arrays.asList(cookies));
for (Map.Entry<String, String> entry : mapCookies.entrySet()) {
String key = entry.getKey();
if (key != null && !"".equals(key)) {
for (int i = 0; i < cookieList.size(); i++) {
if(cookieList.get(i).getName().equals(key)){
cookieList.remove(i);
}
}
cookieList.add(new Cookie(key, entry.getValue()));
}
}
return cookieList.toArray(new Cookie[cookieList.size()]);
}
}
}
}
2.在web.xml中注册该过滤器:
<filter>
<filter-name>ModifyParametersFilter</filter-name>
<filter-class>com.xiyinli.web.common.ModifyParametersFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ModifyParametersFilter</filter-name>
<url-pattern>/*</url-pattern>
<!-- 直接从客户端过来的请求以及通过forward过来的请求都要经过该过滤器 -->
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
如:
参考文章:
继承HttpServletRequestWrapper以实现在Filter中修改HttpServletRequest的参数