当前仓库属于暂停状态,部分功能使用受限,详情请查阅 仓库状态说明
19 Star 31 Fork 4

drinkjava2 / jWebBox
暂停

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

(English version see README-English.md)

jWebBox

License: Apache 2.0

这是一个服务端(支持JSP和FreeMaker)页面布局工具,特点是简单,无XML,仅用500行源码实现了与Apache Tiles类似的页面布局功能。

目前一些服务端JSP页面布局工具的缺点:

  • Apache Tiles: 功能强大但过于臃肿,源码复杂,第三方库引用多,XML配置不方便,动态配置功能差。
  • Sitemesh: 采用装饰器模式,功能不如Apache Tiles灵活。
  • JSP Layout或Stripes等JSP布局工具:功能不够强,在布局的继承或参数传递上有问题。

JWebBox特点:

  1. 简单, 整个项目仅500行源码,易于学习和维护。
  2. 与jBeanBox和jSqlBox项目类似,用纯JAVA类代替XML配置(实际上前两个项目是受此项目启发),支持动态配置,配置可以在运行期动态生成和修改。
  3. 无侵入性,支持JSP和FreeMaker两种模板混用。可用于整个网站的服务端布局,也可用于编写页面局部零件。
  4. 支持静态方法、实例方法、URL引用三种数据准备方式。
  5. 可利用它搭建小巧的MVC架构,向复杂的Spring-MVC告别,详见jBooox项目。

使用方法:

在项目的pom.xml中添加如下内容:

  <dependency>  
    <groupId>com.github.drinkjava2</groupId>
    <artifactId>jwebbox</artifactId>  
    <version>2.1.2</version>  
  </dependency> 
  
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version> <!-- 或其它版本 -->
    <scope>provided</scope>
  </dependency>
  
   <dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.1</version> <!-- 或其它版本  -->
    <scope>provided</scope>
   </dependency>   

jWebBox运行于Java6或以上,依赖于javax.servlet-api和javax.servlet.jsp-api这两个运行期库(通常由Servlet容器提供)。

详细介绍

以下通过对示例的解释来详细说明jWebBox的使用,示例项目源码位于项目的jwebbox-demo目录下,在项目的根目录,也有一个打包好的jwebbox-demo.war文件,可直接扔到Tomcat或WebLogic里运行。

示例1 - 一个带菜单和底脚的左右布局

服务端代码如下:

  public static class demo1 extends WebBox {
    {   this.setPage("/WEB-INF/pages/homepage.jsp");
      this.setAttribute("menu",
          new WebBox("/WEB-INF/pages/menu.jsp").setAttribute("msg", "Demo1 - A basic layout"));
      this.setAttribute("body", new LeftRightLayout());
      this.setAttribute("footer", "/WEB-INF/pages/footer.jsp");
    }
  }

  public static class LeftRightLayout extends WebBox {
    {   this.setPage("/WEB-INF/pages/left_right_layout.jsp");
      ArrayList<Object> boxlist = new ArrayList<Object>();
      boxlist.add("/WEB-INF/pages/page1.jsp");
      boxlist.add("/WEB-INF/pages/page2.jsp");
      this.setAttribute("boxlist", boxlist);
    }
  }

其中homepage.jsp是主模板文件,主要内容如下:

<%@ taglib prefix="box" uri="http://github.com/drinkjava2/jwebbox"%> 
<html>
  <body>
    <div id="temp_content">
      <div id="temp_menu"> 
            <box:show attribute="menu" /> 
      </div>
             <box:show attribute="body" /> 
       <div id="temp_footer"> 
           <box:show attribute="footer" />  
      </div>  
    </div>
  </body>
</html>

left_right_layout.jsp是一个布局模板,内容如下(其它的JSP文件类似,此处略,详见示例):

<%@ taglib prefix="box" uri="http://github.com/drinkjava2/jwebbox"%> 
<div id="temp_left" style="margin: 10px; width: 430px; float: left; background-color:#CCFFCC;"> 
    <box:show target="${jwebbox.attributeMap.boxlist[0]}" />
</div>
<div id="temp_right"  style="margin: 10px; float: right; width: 430px;background-color:#FFFFCC;">
     <box:show target="${jwebbox.attributeMap.boxlist[1]}" />
</div>

解释:

  • setPage方法用于设定当前WebBox实例的目标页面(可选),WebBox构造器允许带一个页面参数。
  • setAttribute方法在WebBox的一个内部HashMap中暂存一个键值,值可以为任意Java对象类型,相应地取值用getAttribute方法,在JSP中可以用EL表达式${jwebbox.attributeMap.keyname}获取。
  • 在JSP页面中调用<box:show attribute="body" />标签来显示对应键值的页面,值只能是String、WebBox实例或它们的List。
  • show标签的另一个用法是<box:show target="xxx"/>, target只能是String、WebBox或List。如下5种写法在JSP中是等同的:
   <box:show attribute="menu" />                                                         
   <box:show target="${jwebbox.attributeMap.menu}" />   
   <% WebBox.showAttribute(pageContext,"menu");%>   
   <% WebBox.showTarget(pageContext, WebBox.getAttribute(pageContext,"menu"));%>           
   <% ((WebBox)WebBox.getAttribute(pageContext,"menu")).show(pageContext);%>  //仅当menu属性为WebBox对象时  

后三种写法不推荐,但有助于理解WebBox的运作机制。每个被WebBox调用的页面,都在request中存在一个WebBox实例,可以用request.getAttribute("jwebbox")或EL表达式${jwebbox}获取。

  • show标签使用时必须在JSP页面加入TagLib库的引用:<%@ taglib prefix="box" uri="http://github.com/drinkjava2/jwebbox"%>
  • 每个WebBox实例,可以设定一个可选的name属性,每个页面用只能获取属于自已的一个WebBox实例,但是可以用getFatherWebBox方法获取当前WebBox实例的调用者所在页面的WebBox实例(有点绕口)。
  • 在JSP和Servlet中,jWebBox支持在页面中动态生成WebBox实例并调用show方法显示,例如:<% new WebBox("/somepage.jsp").setPrepareStaticMethod("xxx").show(pageContext); %>
  • 本示例项目中运用了一个小技巧,利用一个Servlet将所有".htm"后缀的访问转化对WebBox的创建和显示,在web.xml中配置如下
  <servlet>
    <servlet-name>htm2box</servlet-name>
    <jsp-file>/htm2box.jsp</jsp-file>
  </servlet>

  <servlet-mapping>
    <servlet-name>htm2box</servlet-name>
    <url-pattern>*.htm</url-pattern>
  </servlet-mapping>

其中htm2box.jsp当作Servlet来使用,作用类似于Spring MVC中的DispatcherServlet:

<%@page import="org.apache.commons.lang.StringUtils"%><%@page import="com.github.drinkjava2.jwebbox.WebBox"%><%
  String uri=StringUtils.substringBefore(request.getRequestURI(),".");
  uri = StringUtils.substringAfterLast(uri, "/");
  if (uri == null || uri.length() == 0)
    uri = "demo1";
  WebBox box = (WebBox) Class.forName("com.github.drinkjava2.jwebboxdemo.DemoBoxConfig$" + uri).newInstance();
  box.show(pageContext);
%>

示例1的输出: image

示例2 - 布局的继承

服务端代码:

  public static class demo2 extends demo1 {
    {  ((WebBox) this.getAttribute("menu")).setAttribute("msg", "Demo2 - Change body layout");
      this.setAttribute("body", new TopDownLayout());
    }
  }

  public static class TopDownLayout extends LeftRightLayout {
    {  this.setPage("/WEB-INF/pages/top_down_layout.jsp");
    }
  }

demo2继承于demo1类,将"body"属性改成了一个上下布局top_down_layout.jsp模板(源码见示例)。

示例2的输出:
image

示例3 - 数据准备

服务端代码:

  public static class demo3 extends demo1 {
    {  setPrepareStaticMethod(DemoBoxConfig.class.getName() + ".changeMenu");
      setAttribute("body", new WebBox().setText("<div style=\"width:900px\"> This is body text </div>")
          .setPrepareURL("/WEB-INF/pages/prepare.jsp").setPrepareBean(new Printer()));
      setAttribute("footer", new WebBox("/WEB-INF/pages/footer.jsp").setPrepareBean(new Printer())
          .setPrepareBeanMethod("print"));
    }
  }

  public static void changeMenu(PageContext pageContext, WebBox callerBox) throws IOException {
    ((WebBox) callerBox.getAttribute("menu")).setAttribute("msg",
        "Demo3 - Prepare methods <br/>This is modified by \"changeMenu\" static method");
  }

  public static class Printer {
    public void prepare(PageContext pageContext, WebBox callerBox) throws IOException {
      pageContext.getOut().write("This is printed by Printer's default \"prepare\" method <br/>");
    }

    public void print(PageContext pageContext, WebBox callerBox) throws IOException {
      pageContext.getOut().write("This is printed by Printer's \"print\" method <br/>");
      pageContext.getOut().write((String) pageContext.getRequest().getAttribute("urlPrepare"));
    }
  }

相比与普通的Include指令,Apache Tiles和jWebBox这类布局工具的优势之一在于可以在各个子页面加载之前进行数据准备工作,从而达到模块式开发的目的。jWebBox有三种数据准备方式:

  • setPrepareStaticMethod方法指定一个静态方法用于数据准备。
  • setPrepareBean方法指定一个对象实例用于数据准备,用setPrepareBeanMethod来指定对象的方法名,如果不指定方法名,将缺省使用"prepare"作为方法名。
  • setPrepareURL方法将调用一个URL来作为数据谁备,这是一个服务端的URL引用,可以访问/WEB-INF目录下的内容。
  • setText方法可以额外设置一小段文本,将直接作为HTML代码片段插入到子页面前面。

各个准备方法及页面输出的顺序如下:
prepareStaticMethod -> prepareBeanMethod -> PrepareURL -> text output -> page

示例3输出:
image

示例4 - 列表

服务端代码:

  public static class demo4 extends demo1 {
    {
      ((WebBox) this.getAttribute("menu")).setAttribute("msg", "Demo4 - List");
      ArrayList<Object> child = new ArrayList<Object>();
      for (int i = 1; i <= 3; i++)
        child.add(new WebBox("/WEB-INF/pages/page" + i + ".jsp").setText("&nbsp;&nbsp;&nbsp;&nbsp;"));
      ArrayList<Object> mainList = new ArrayList<Object>();
      for (int i = 1; i <= 3; i++) {
        mainList.add("/WEB-INF/pages/page" + i + ".jsp");
        if (i == 2)
          mainList.add(child);
      }
      this.setAttribute("body", mainList);
    }
  }

如果属性是一个列表,当JSP页面中调用<box:show attribute="xxx" />方法时,如果值是一个List,将假定List中属性为页面或WebBox实例并依次显示。
示例4输出:
image

示例5 - FreeMaker模板支持

从2.1版起,jWebBox开始支持FreeMaker,且可以与JSP混用,例如如下配置:

  public static class demo5 extends WebBox {
    {  this.setPage("/WEB-INF/pages/homepage.ftl");
      this.setAttribute("menu",
          new WebBox("/WEB-INF/pages/menu.jsp").setAttribute("msg", "Demo5 - Freemaker demo"));
      this.setAttribute("body", new FreemakerLeftRightLayout());
      this.setAttribute("footer", new WebBox("/WEB-INF/pages/footer.jsp"));
    }
  }

FreeMaker不支持直接在页面嵌入Java代码,语法也与JSP不同,引入标签要写成<#assign box=JspTaglibs["http://github.com/drinkjava2/jwebbox"] />, show标签要写成<@box.show attribute="menu" />
使用FreeMaker,需要在web.xml中添加如下配置:

  <servlet>
    <servlet-name>freemarker</servlet-name>
    <servlet-class>freemarker.ext.servlet.FreemarkerServlet</servlet-class>
    <init-param>
      <param-name>TemplatePath</param-name>
      <param-value>/</param-value>
    </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>freemarker</servlet-name>
    <url-pattern>*.ftl</url-pattern>
  </servlet-mapping>

并在pom.xml中添加对FreeMaker库的依赖:

 <dependency>
     <groupId>org.freemarker</groupId>
     <artifactId>freemarker</artifactId>
     <version>2.3.23</version> <!--或更新版-->
  </dependency>
   

示例5输出:
image

示例6 - 表格和分页演示

这个例子展示了利用WebBox配置的继承功能来创建表格和分页条组件,输出两个表格和分页条,并处理表单提交数据。因篇幅较长,此处只摘录布局部分代码:

  public static class demo6 extends demo1 {
    {
      setAttribute("menu",
          ((WebBox) this.getAttribute("menu")).setAttribute("msg", "Demo6 - Table & Pagination"));
      List<WebBox> bodyList = new ArrayList<WebBox>();
      bodyList.add(new TableBox());
      bodyList.add(new TablePaginBarBox());
      bodyList.add(new WebBox().setText(
          "<br/>-----------------------------------------------------------------------------------"));
      bodyList.add(new CommentBox());
      bodyList.add(new CommentPaginBarBox());
      bodyList.add(new WebBox("/WEB-INF/pages/commentform.jsp"));
      this.setPrepareStaticMethod(DemoBoxConfig.class.getName() + ".receiveCommentPost");
      this.setAttribute("body", bodyList);
    }

    class TableBox extends WebBox {
      {
        this.setPrepareBean(new PrepareForDemo6()).setPrepareBeanMethod("prepareTable");
        setPage("/WEB-INF/pages/page_table.jsp");
        setAttribute("pageId", "table");
        setAttribute("targetList", tableDummyData);
        setAttribute("row", 3).setAttribute("col", 4);
        setAttribute("render", new WebBox("/WEB-INF/pages/render_table.jsp"));
      }
    }

    class TablePaginBarBox extends TableBox {
      {
        this.setPrepareBean(new PrepareForDemo6()).setPrepareBeanMethod("preparePaginBar");
        setPage("/WEB-INF/pages/pagin_bar.jsp");
      }
    }

    class CommentBox extends TableBox {
      {
        setAttribute("pageId", "comment");
        setAttribute("targetList", commentDummyData);
        setAttribute("row", 3).setAttribute("col", 1);
        setAttribute("render", new WebBox("/WEB-INF/pages/render_comment.jsp"));
      }
    }

    class CommentPaginBarBox extends CommentBox {
      {
        this.setPrepareBean(new PrepareForDemo6()).setPrepareBeanMethod("preparePaginBar");
        setPage("/WEB-INF/pages/pagin_bar.jsp");
      }
    }
  }

示例6截图:
image

以上即为jWebBox的全部说明文档,如有不清楚处,可以查看项目源码或示例项目的源码。

附录-版本更新记录:

jWebBox2.1 添加FreeMaker模板支持;增加一个JSP标签;添加了表格、分页、表单处理的演示;更正WebLogic不能运行的bug。
jWebBox2.1.1 添加了beforeShow、beforeexecute、execute、afterExecute、afterShow、afterPrepared几个空方法作为回调函数给子类用。示例详见jBooox项目。
jWebBox2.1.2 show()方法原来为void类型,现改为WebBox实例,便方便使用。

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

这是一个服务端页面布局工具,支持HTML/JSP/FreeMaker等 展开 收起
Java 等 3 种语言
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Java
1
https://gitee.com/drinkjava2/jWebBox.git
git@gitee.com:drinkjava2/jWebBox.git
drinkjava2
jWebBox
jWebBox
master

搜索帮助