SpringMvc中动态添加JS内容

package io.purewind.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.Resource;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.resource.ResourceTransformerChain;
import org.springframework.web.servlet.resource.ResourceTransformerSupport;
import org.springframework.web.servlet.resource.TransformedResource;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.Charset;

public class JsPatchResourceTransformer extends ResourceTransformerSupport {

    private static final Log logger = LogFactory.getLog(JsPatchResourceTransformer.class);

    private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");


    @Override
    public Resource transform(HttpServletRequest request, Resource resource, ResourceTransformerChain transformerChain) throws IOException {
        resource = transformerChain.transform(request, resource);

        String filename = resource.getFilename();
        if (!"js".equals(StringUtils.getFilenameExtension(filename))) {
            return resource;
        }

        if (logger.isTraceEnabled()) {
            logger.trace("Transforming resource: " + resource);
        }

        byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
        String content = new String(bytes, DEFAULT_CHARSET);
        StringWriter writer = new StringWriter();

        String append = ";window.console && console.log('添加成功');";

        writer.write(content);
        writer.write(append);

        return new TransformedResource(resource, writer.toString().getBytes(DEFAULT_CHARSET));

    }
}

在spring-servlet.xml中配置资源的转换器

    <mvc:resources location="static/" mapping="/assets/**">
        <mvc:resource-chain resource-cache="false">
            <mvc:transformers>
                <bean class="io.purewind.web.JsPatchResourceTransformer"/>
            </mvc:transformers>
        </mvc:resource-chain>
    </mvc:resources>

SpringMvc中动态添加JS内容
Share this