Search code examples
javascriptjavamavenjspwebjars

Remove webjars version from url


We are using webjars with maven in our project. So we have hundreds of JSPs with code like this:

<%--JSP CODE--%>
<script src="<c:url value="/webjars/jquery/2.2.0/jquery.min.js" />" type="text/javascript"></script>
<script src="<c:url value="/webjars/bootstrap/3.3.6/js/bootstrap.min.js" />" type="text/javascript"></script>
......... 

And as you can guess it's a cumbersome work to update to newer versions of webjars. So I'm looking for the solution which will allow me to import scripts like this:

<%--JSP CODE--%>
<script src="<c:url value="/webjars/jquery/jquery.min.js" />" type="text/javascript"></script>
<script src="<c:url value="/webjars/bootstrap/js/bootstrap.min.js" />" type="text/javascript"></script>
......... 

Basically I want to remove a webjar version from url. Can you propose nice and simple solution for this problem?

So far I come up with resource servlet which can guess which file to return by the url. But this solution involves full resource scanning at the start of an application.


Solution

  • Take a look at webjars-locator project, you can use it to create proper request controller.

    In case of using Spring MVC this would be:

    @ResponseBody
    @RequestMapping("/webjarslocator/{webjar}/**")
    public ResponseEntity locateWebjarAsset(@PathVariable String webjar, HttpServletRequest request) {
        try {
            String mvcPrefix = "/webjarslocator/" + webjar + "/"; // This prefix must match the mapping path!
            String mvcPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
            String fullPath = assetLocator.getFullPath(webjar, mvcPath.substring(mvcPrefix.length()));
            return new ResponseEntity(new ClassPathResource(fullPath), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
    

    Disclaimer: This is the code from WebJars documentation (section Making dependencies version agnostic).

    In this case you can ask for js libraries in following way:

    <link rel='stylesheet' href='/webjarslocator/bootstrap/css/bootstrap.min.css'>
    

    Please note that there's no version in this url.

    You can also try to optimize this requests (and consequently - filesystem scans) by using cache, but I am almost sure that some kind of cache is already involved in webjars-locator (I haven't checked that).