在Jetty 6.1中设置HTTP标头(基于文件名模式)的最佳方法是什么?是否可以通过jetty.xml(或jetty-web.xml)?或者我是否必须修改web.xml?
答案 0 :(得分:9)
我的问题的一般答案当然是:
<web-app>
<filter>
<filter-name>headersFilter</filter-name>
<filter-class>com.example.MyHeadersFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>headersFilter</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
...
</web-app>
public class MyHeadersFilter implements Filter {
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException,
ServletException {
final HttpServletRequest httpRequest = (HttpServletRequest) request;
final HttpServletResponse httpResponse = (HttpServletResponse) response;
final String requestUri = httpRequest.getRequestURI();
if (requestUri.matches(...)) {
httpResponse.addHeader(...);
}
chain.doFilter(request, response);
}
}
这应该可以在任何JavaEE Web容器中使用(并且可以使用<init-param>
s进行更多配置。)
但是,有没有办法在Jetty中以纯粹的声明方式做到这一点?
答案 1 :(得分:9)
您可以按配置添加标头。在jetty.xml中,输入以下示例:
<New id="RewriteHandler" class="org.eclipse.jetty.rewrite.handler.RewriteHandler">
<Set name="rules">
<Array type="org.eclipse.jetty.rewrite.handler.Rule">
<Item>
<New id="header" class="org.eclipse.jetty.rewrite.handler.HeaderPatternRule">
<Set name="pattern">*.jsp</Set>
<Set name="name">myheader</Set>
<Set name="value">the value of myheader</Set>
</New>
</Item>
</Array>
</Set>
</New>
<Set name="handler">
<New id="Handlers" class="org.eclipse.jetty.server.handler.HandlerCollection">
<Set name="handlers">
<Array type="org.eclipse.jetty.server.Handler">
<Item>
<Ref id="RewriteHandler"/>
</Item>
</Array>
</Set>
</New>
</Set>
有关可行内容的更多示例,请参阅RewriteHandler api(Jetty 6 RewriteHandler已提供)
有关信息,这是我的jetty插件的maven配置:
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>8.1.5.v20120716</version>
<configuration>
<jettyXml>${basedir}/src/main/etc/jetty.xml</jettyXml>
</configuration>
<dependencies>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-http</artifactId>
<version>8.1.5.v20120716</version>
<type>jar</type>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-rewrite</artifactId>
<version>8.1.5.v20120716</version>
<type>jar</type>
<scope>runtime</scope>
</dependency>
</dependencies>
</plugin>
答案 2 :(得分:0)
有一种方法可以在jetty中添加标题。 使用java.lang.instrument和javassist。有关详细信息,请参阅以下链接:
http://hunmr.blogspot.com/2012/12/mock-jetty-behavior-adding-customized.html