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