我正在使用Servlet 3.0,并希望将我现有的web.xml文件转换为java配置。 配置 servlet/过滤器等似乎非常简单。 我不知道如何转换以下哑剧映射。 谁能帮我?
<mime-mapping>
<extension>xsd</extension>
<mime-type>text/xml</mime-type>
</mime-mapping>
我在Spring Boot应用程序中遇到了这个问题。我的解决方案是创建一个实现org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer
的类,如下所示:
@Configuration
public class MyMimeMapper implements EmbeddedServletContainerCustomizer {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
mappings.add("xsd", "text/xml; charset=utf-8");
container.setMimeMappings(mappings);
}
}
只需编写一个Filter
. 例如,用于 web.xml 中的 mime 映射:
<mime-mapping>
<extension>mht</extension>
<mime-type>message/rfc822</mime-type>
</mime-mapping>
我们可以编写一个过滤器:
@WebFilter("*.mht")
public class Rfc822Filter implements Filter {
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
resp.setContentType("message/rfc822");
chain.doFilter(req, resp);
}
...
}
使用Spring MVC,这种方法对我有用。
在网络上下文中,添加以下内容:
public class WebContext implements WebMvcConfigurer {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.mediaType("xsd", MediaType.TEXT_XML);
}
}
据我所知,您无法在 Java 配置中设置它们。只能在 Web 应用程序的部署描述符或 serlvet 容器中执行此操作。
ServletContext#getMimeType(String)
的javadoc暗示了这一点
MIME 类型由 servlet 的配置决定 容器,并且可以在 Web 应用程序部署中指定 描述符。