我正在尝试为我们的web门户创建一个模拟,并需要添加自定义http头。我假设用户已经过身份验证,这些头只是用来存储用户信息(即,“test header:role=user;oem=blahblah;id=123;”)。
我已经设置了一个过滤器来提取头信息,但是找不到注入头信息的方法。他们不希望将其存储在cookies中,也许他们希望设置一个全局筛选器,以包括每个页面上的标题;是否可以使用筛选器接口或通过任何其他方法执行类似的操作?
最佳答案
或许你可以在会话中存储这些信息:
import java.io.IOException;
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 javax.servlet.http.HttpServletResponse;
/**
* @author rodrigoap
*
*/
public class UserInfoFilter implements Filter {
/**
* @see javax.servlet.Filter#destroy()
*/
public void destroy() {
// TODO
}
/**
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
* javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
if (!(request instanceof HttpServletRequest))
throw new ServletException("Can only process HttpServletRequest");
if (!(response instanceof HttpServletResponse))
throw new ServletException("Can only process HttpServletResponse");
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpRequest.getSession().setAttribute("role", "user");
httpRequest.getSession().setAttribute("id", "123");
filterChain.doFilter(request, response);
}
/**
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig filterConfig) throws ServletException {
// TODO
}
}