虽然目前工作时的页面开发一直在用Velocity,但其实我的心是属于JSP的,毕竟那是我第一次接触web开发使用的页面模版技术。JSP很多地方都不错:Eclipse支持得很好;JSTL用起来顺手;还能强大的直接调用Java代码(当然,不鼓励这么干);能自定义各种功能强大的标签等等。
这里要有但是了!但是,没有直接提供类似Velocity的layout功能!这导致写页面的时候,很难避免重复的页面代码。对于一个有代码洁癖和强迫症的程序员来说,不能忍!
后来发现了@红薯 曾经写过一个实现该功能的“软件”:http://www.oschina.net/p/jsplayout
看了之后,启发很大。既然有源码,那就可以拿过来改!我改成了一个静态方法,直接调用即可,感觉使用更简单了。代码很少,就不像红薯那么“厚颜无耻”,发布成一个软件了。先上代码。
public class TemplateUtil { private static final String WWW_TPL_PATH = "/WEB-INF/template/www/"; private static final String LAYOUT_PATH = "/WEB-INF/layout/"; private static final String SCREEN_CONTENT = "screen_content"; public static void wwwForward(String layout, String template, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { BufferedResponse my_res = new BufferedResponse(resp); req.getRequestDispatcher(WWW_TPL_PATH + template).include(req, my_res); String screenContent = my_res.getScreenContent(); req.setAttribute(SCREEN_CONTENT, screenContent); req.getRequestDispatcher(LAYOUT_PATH + layout).forward(req, resp); } public static void wwwForward(String template, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getRequestDispatcher(WWW_TPL_PATH + template).forward(req, resp); } } /** * Response封装 */ class BufferedResponse extends HttpServletResponseWrapper { StringWriter sout; PrintWriter pout; public BufferedResponse(HttpServletResponse res) { super(res); sout = new StringWriter(); pout = new PrintWriter(sout); } @Override public PrintWriter getWriter() throws IOException { return pout; } protected String getScreenContent() { return sout.toString(); } }
首先有三个常量:WWW_TPL_PATH,LAYOUT_PATH,SCREEN_CONTENT,分别对应页面文件夹,布局文件夹,页面内容变量名。
接着把这么一个layout功能封装成了一个静态方法 wwwForward(String layout, String template, HttpServletRequest req, HttpServletResponse resp)。传入布局文件名,页面文件名,request,response。
然后我们再看下布局文件的例子,命名为layout.jsp。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!doctype html> <html> <head> <meta charset="utf-8"> </head> <body> <div>我是头部</div> ${screen_content} <div>我是尾部</div> </body> </html>
这里的${screen_content}对应上面提到的SCREEN_CONTENT,布局文件的路径记得要跟上面定义的LAYOUT_PATH一致。
接着再看下页面怎么写,页面命名为index.jsp,路径在上面提到的WWW_TPL_PATH下。
<p>Hello, World</p>
是的,就是这么简单。
最后,看看servlet怎么写。
public class IndexServlet extends HttpServlet{ private static final long serialVersionUID = -1703574459593330679L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { TemplateUtil.wwwForward("layout.jsp", "index.jsp", req, resp); } }
部署项目,运行,访问下这个servlet看看效果!
希望对一样喜欢用JSP开发的程序员有所帮助:-),Enjoy it.