在泽西拦截器中缩小html和js

时间:2016-04-09 10:39:58

标签: java web-services jsp jersey jax-rs

使用了jersey mvc和jsp,所有对html或js文件的请求都是通过@Template或Viewable完成的。 例子;

  @GET
  @Path(JS_URL + "{type}")
  @Template(name = "grid")
  @Produces("application/javascript")
  public Response buildJSGrid(@DefaultValue("") @PathParam("type") String type) {
     Grid grid = new Grid(type);
....
     return Response.ok(grid).build();
  }

其中grid是grid.jsp文件,里面有纯粹的javascript

<%@ page contentType="application/javascript;charset=UTF-8" language="java" %>

.....

也可能使用html和js的其他变体,例如;

@GET
  @Path(FORM_URL + "{type}")
  @Template(name = "form")
  @Produces(MediaType.TEXT_HTML)
  public Response buildAccountForm(@DefaultValue("") @PathParam("type") String type) {
     Form form = new Form(type);
....
     return Response.ok(form).build();
  }

其中form是form.jsp,其中html和js位于<script>内。</script>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

...

我需要在发送到客户端之前缩小结果js和html / js,我尝试使用https://code.google.com/archive/p/htmlcompressor/ lib,但是需要将String传递给htmlCompressor.compress(输入);

尝试使用WriterInterceptor

public class MinifyJsInterceptor implements WriterInterceptor {
  @Override
  public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
final OutputStream outputStream = context.getOutputStream();
// here need to convert outputStream to InputStream and after to String ?
// result string to htmlCompressor.compress(resultString);
// after that convert result minify string back to resultOutputStream and set to context ?
context.setOutputStream(new GZIPOutputStream(resultOutputStream));

这是正确的方法吗?我不能将该输出流转换为字符串 感谢

- 更新

回答问题; html + js意味着在某些jsp中是html标记和js代码

    <div id="form" style="width: 500px; display: none">
      <div class="w2ui-page page-0">
        <div class="w2ui-field">
    </div>....

    <script type="text/javascript">
      var uiElement = (function () {
        var config = {
            onOpen: function (event) {
      event.onComplete = function () {
        $('#formContainer').w2render('form');
      }
     ...
    }());
    </script>

在客户端上

请求的文件
         $('#tempContainer').load('that file name - also dynamic', function (data, status, xhr) {
           uiElement.init();
           w2ui[layout].content(layout_main, w2ui[uiElement.name]);
         });

你真的在资源方法中返回js文件吗?

        some js and html + js files are dynamic build, example;
        grid.jsp contains inside

<%@ page contentType="application/javascript;charset=UTF-8" language="java" %>

          var uiElement = (function () {
            var config = {
              grid: {
                name: ${it.name},
                listUrl:'${it.entityListUrl}',
                formUrl:'${it.entityFormUrl}',
                columns: ${it.columns},
                records: ${it.records},           
}}

来自el表达式的$ {it ..}值和资源方法

中的设置
@GET
      @Path(JS_URL + "{type}")
      @Template(name = "grid")
      @Produces("application/javascript")
      public Response buildJSGrid(@DefaultValue("") @PathParam("type") String type) {
         Grid grid = new Grid(type);
    ....
         return Response.ok(grid).build();
      }}

来自客户,js&#39; file&#39;由

召集
         $.getScript('dynamic js file name' - it is dynamic too).done(function (script, status, xhr) {
           //console.log(xhr.responseText);
           uiElement.init();
           w2ui[layout].content(layout_main, w2ui[uiElement.name]);
         });



       also some html blocks build dynamic


{ 
     <c:if test="${it.recid != 0}">
          <div class="w2ui-field">
            <label>active:</label>
            <div>
              <input name="active" type="checkbox"/>
            </div>
          </div>
            </c:if>
}

- 更新说明,  网格构建器;

一个资源和一个用于构建任何网格的模板,

  @GET
  @Path(GRID + "{type}")
  @Template(name = W2UI_VIEW_PREFIX + "grid/grid")
  @Produces(MEDIA_TYPE_APPLICATION_JAVASCRIPT)
  public Response buildGrid(@DefaultValue("") @PathParam("type") String type) {
    for (W2UI ui : W2UI.values()) {
      if (type.equals(ui.getName())) {
        W2UIElement grid = ui.getUI();
        return Response.ok(grid).build();
      }
    }
    return Response.noContent().build();
  }

也可以通过Viewable(模板,模型)

创建不同的模板(jsp文件)

在menu.jsp模板的菜单构建器中的某处

List<MenuItem> items..
MenuItem item1 = new MenuItem(W2UI.TASK_GRID, W2UIService.GRID);
items.add(item1);

其中

W2UIService.GRID is string url for client js request and for server method resource @Path() anno.

public enum W2UI {
  TASK_GRID("task_grid", "tasks", Type.SCRIPT){
    @Override
    public W2UIElement getUI() {
      return new TaskGrid(getName());
    }
  },
.....
}

TaskGrid是带有js代码的grid.jsp模板的填充模型,因此很容易添加具有不同数据和按钮组的任何类型的网格。

客户端上的组件类型(Type.SCRIPT)由$ .getScript()处理,Type.HTML由$(&#39; #tempContainer&#39;)处理.load()

---更新工厂和供应商;

@Provider
@Priority(200)
@HtmlMinify
public class HtmlMinifyInterceptor implements WriterInterceptor {
  @Inject private HtmlCompressor compressor;

...

public class HtmlMinifierFactory implements Factory<HtmlCompressor> {
  private HtmlCompressor compressor;

  @Override
  public HtmlCompressor provide() {
    if (null == compressor) compressor = new HtmlCompressor();
    ClosureJavaScriptCompressor jsCompressor = new ClosureJavaScriptCompressor();
    jsCompressor.setCompilationLevel(CompilationLevel.SIMPLE_OPTIMIZATIONS);

...

@ApplicationPath("/")
public class MainRsConfig extends ResourceConfig {
  public MainRsConfig() {
..
    register(new AbstractBinder() {
      @Override
      protected void configure() {
        bindFactory(HtmlMinifierFactory.class).to(HtmlCompressor.class).in(Singleton.class);
      }
    });
..

0 个答案:

没有答案