如何在Spring Boot中修改静态资源index.html?

时间:2016-07-14 13:08:34

标签: spring spring-mvc spring-boot

我做了一个小型的webapp,我想在索引页面的底部添加信用笔记。从WAR文件中的html页面中删除注释很容易。所以我认为我可以这样修改资源'index.html':

public class MainPageTransformer implements ResourceTransformer {
    @Override
    public Resource transform(HttpServletRequest request, Resource resource, ResourceTransformerChain transformerChain) throws IOException {
        String html = IOUtils.toString(resource.getInputStream(), UTF_8);
        html = html.replace("</body>", "<div style=\"position: absolute; bottom: 5px;\">Autor</div>\n</body>");
        return new ByteArrayResource(html.getBytes());
    }
}

......和:

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/client/index.html")
                .addResourceLocations("classpath:/static/client")
                .resourceChain(false)
                .addTransformer(new MainPageTransformer());
    }
}

执行MainPageTransformer.transform方法后,它会抛出异常:

java.io.FileNotFoundException: Byte array resource [resource loaded from byte array] cannot be resolved to absolute file path
at org.springframework.core.io.AbstractResource.getFile(AbstractResource.java:114)
at org.springframework.core.io.AbstractResource.getFileForLastModifiedCheck(AbstractResource.java:169)
at org.springframework.core.io.AbstractResource.lastModified(AbstractResource.java:153)
at org.springframework.web.servlet.resource.ResourceHttpRequestHandler.handleRequest(ResourceHttpRequestHandler.java:240)
at org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter.handle(HttpRequestHandlerAdapter.java:51)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:859)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)

我做错了什么?有没有更好的方法来实现我的目标?非常感谢!

1 个答案:

答案 0 :(得分:4)

今天我遇到了这个问题,尝试使用org.springframework.web.servlet.resource.TransformedResource

public class MainPageTransformer implements ResourceTransformer {
 @Override
 public Resource transform(HttpServletRequest request, Resource resource, ResourceTransformerChain transformerChain) throws IOException {
   String html = IOUtils.toString(resource.getInputStream(), UTF_8);
   html = html.replace("</body>", "<div style=\"position: absolute; bottom: 5px;\">Autor</div>\n</body>");
   return new TransformedResource(resource, html.getBytes());
  }
}