我正试图添加一个授权头到我的请求作为一个临时的解决办法,而我们正在切换环境。我试图在扩展HandlerInterceptorAdapter的拦截器中处理它。我使用了here中的MutableHttpServletRequest类,以便能够将头添加到请求中,但似乎没有任何方法可以实际修改拦截器中返回的请求。有什么想法吗编辑:或者我必须在过滤器中这样做?
qyyhg6bp1#
HttpServletRequest类型的对象是只读的,要做到这一点,你应该:->创建一个扩展HttpServletRequestWrapper的类(添加一些行为,装饰模式)
final public class MutableHttpServletRequest extends HttpServletRequestWrapper { private final Map<String, String> customHeaders; public MutableHttpServletRequest(HttpServletRequest request){ super(request); this.customHeaders = new HashMap<String, String>(); } public void putHeader(String name, String value){ this.customHeaders.put(name, value); } public String getHeader(String name) { String headerValue = customHeaders.get(name); if (headerValue != null){ return headerValue; } return ((HttpServletRequest) getRequest()).getHeader(name); } public Enumeration<String> getHeaderNames() { Set<String> set = new HashSet<String>(customHeaders.keySet()); @SuppressWarnings("unchecked") Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaderNames(); while (e.hasMoreElements()) { String n = e.nextElement(); set.add(n); } return Collections.enumeration(set); } }
字符串->创建过滤器类
public class CustomGatewayFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(req); mutableRequest.putHeader("referer", "custom value"); chain.doFilter(mutableRequest, response); } }
型->并在config类中添加
.and().addFilterAfter(new CustomGatewayFilter(), ConcurrentSessionFilter.class)
型
nafvub8i2#
来自http://wilddiary.com/adding-custom-headers-java-httpservletrequest/的示例似乎不适合我使用Tomcat 9。我知道它进入了过滤器,因为我发送了我想要的值,我知道如果我注解了chain.doFilter行,那么页面是空白的,因为我没有写出任何标题。
bprjcwpo3#
public class YourInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { SomeModel model = new SomeModel(); request.setAttribute("someValue", model ); request.addHeader("xxx","asecret"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { //... response.addHeader("dummy-header, "dummy-value"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { SomeModel model = (Long) request.getAttribute("someValue"); } }
字符串
3条答案
按热度按时间qyyhg6bp1#
HttpServletRequest类型的对象是只读的,要做到这一点,你应该:
->创建一个扩展HttpServletRequestWrapper的类(添加一些行为,装饰模式)
字符串
->创建过滤器类
型
->并在config类中添加
型
nafvub8i2#
来自http://wilddiary.com/adding-custom-headers-java-httpservletrequest/的示例似乎不适合我使用Tomcat 9。我知道它进入了过滤器,因为我发送了我想要的值,我知道如果我注解了chain.doFilter行,那么页面是空白的,因为我没有写出任何标题。
bprjcwpo3#
字符串