How is annotations support in jsp implemented in sitebricks?

那年仲夏 提交于 2019-12-25 03:47:16

问题


Here is an example from the SiteBricks user guide:

<html>
<body>
    @ShowIf(true)     <----- I'm impressed with this line
    <p>${message} from Sitebricks!</p>
</body>
</html>

I'm curious how is it implemented? (I mean how and at which entry point sitebricks creators managed to enhance transforming jsp to servlet?)

Thanks for any ideas!


回答1:


There is no filter doing this. We have our own templating logic that uses what is known as a recursive descent parser.

It's actually a non-trivial problem to accomplish this kind of annotation parsing. What we do first is to slurp the entire HTML as a DOM-like tree using Jsoup. Jsoup takes care of normalizing the HTML into an XML-like structure (not exactly, though).

We then descend this tree and build a parallel tree of "Renderers" as Java objects. Each renderer has the ability to do something specific, i.e. spit out HTML, Show If the value is true etc. Given that the renderer tree matches the HTML tree, if ShowIf returns false, we elide the entire branch below it too.

There are some more complex things going on under the hood for page-embedding and so on, but this is the gist of it. Thanks for the kind words!

Dhanji, creator, Sitebricks & Guice Servlet.




回答2:


It's probably not JSP, but its own template language. The framework must parse the template as structured xml + annotations; then it's translated into java code, which gets compiled on the fly.




回答3:


It's possible to intercept on what's been written to the response body and then decorate it accordingly and modify the final response body with help of a Filter and a HttpServletResponseWrapper wherein at least the getWriter() is been overridden so that it returns a custom implementation.

E.g.

chain.doFilter(request, new FooResponse((HttpServletResponse) response));

with

public class FooResponse extends HttpServletResponseWrapper {

    public FooResponse(HttpServletResponse response) {
        super(response);
    }

    public Writer getWriter() throws IOException {
        // ... Here a custom one is returned.
    }

}

That writer would for example buffer the response line by line, parse the written characters, scan for lines containing the characters @Foo and so on and then take action accordingly for the next lines.



来源:https://stackoverflow.com/questions/6722681/how-is-annotations-support-in-jsp-implemented-in-sitebricks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!