Is there a way to add a filter/interceptor to static resources served from META-INF/resources
?
I seem have tried all the possible options: @ServerResponseFilter
, ContainerResponseFilter
,WriterInterceptor
however all these functions are called only for @Path
or @Route
...
Is there anything similar to @RouteFilter but for response?
There seem to be nothing built-in to modify the response of a static content for now but nothing stops you from serving content in a dynamic way:
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
@Path("/")
@Produces(MediaType.TEXT_HTML)
public class FrontendController {
@GET
public Response index() throws IOException {
try (var index = getClass().getResourceAsStream(FrontendConstants.INDEX_RESOURCE)) {
if (index == null) {
throw new IOException("index.html file does not exist");
}
//modify index
return Response
.ok(index)
.cacheControl(FrontendConstants.NO_CACHE)
.build();
}
}
@GET
@Path("/{fileName:.+}")
public Response staticFile(@PathParam("fileName") String fileName) throws IOException {
try (var file = FrontendController.class.getResourceAsStream(FrontendConstants.FRONTEND_DIR + "/" + fileName)) {
if (file == null) {
return index();
}
var contentType = URLConnection.guessContentTypeFromStream(file);
return Response
.ok(
new String(file.readAllBytes(), StandardCharsets.UTF_8),
contentType == null ? MediaType.TEXT_PLAIN : contentType
)
.cacheControl(FrontendConstants.NO_CACHE)
.build();
}
}
}