一聚教程网:一个值得你收藏的教程网站

热门教程

JSP 构架-2种方式:Model I和Model II

时间:2022-07-02 17:50:19 编辑:袖梨 来源:一聚教程网

作者:Lance Lavandowska 编译:blueski
如果你经常去Servlet或JSP的新闻组或者邮件列表,那么一定会看到不少关于Model I 和Model II 方法的讨论。究竟采用哪一种,这取决于你的个人喜好、团队工作策略以及是否采用正统的OOP。
简单地说,Model I将事务逻辑(business logic)和表示代码(presentation code)融合在一起(如在HTML中);Model II则提倡最大限度地将所有的代码放到内容表示之外。
Model I: 简单的单层次应用
如果是在一个人人都精通Java和HTML的环境中,或者你独自做着所有的工作,假如每个人都有清晰的编程结构和思路,那么这种方法会很有效,不过这样的假设不在本文讨论范围之内。这种方法的第一个优点是如果你的应用改变了,你只需维护一个文件。而最大的缺陷是可读性!除非十分小心,否则你的HTML和Java代码会相互混杂,从而难以维护。
在下面这个例子中,我们将增加一个 TimeZone 元素,从而使它变成JSP文件,它会返回基于时间的所期待的TimeZone。如果没有提交 TimeZone,那么缺省的是服务器的缺省时间。
======================================================================

Time JSP


<jsp:scriptlet>
//the parameter "zone" shall be equal to a number between 0 and 24 (inclusive)
TimeZone timeZone = TimeZone.getDefault(); //returns the default TimeZone for the server
if (request.getParameterValues("zone") != null)
{
String timeZoneArg = request.getParameterValues("zone")[0];
timeZone = TimeZone.getTimeZone("GMT+" + timeZoneArg + ":00");
// gets a TimeZone. For this example we´re just going to assume
// its a positive argument, not a negative one.
}
//since we´re basing our time from GMT, we´ll set our Locale to Brittania, and get a Calendar.
Calendar myCalendar = Calendar.getInstance(timeZone, Locale.UK);

<%= myCalendar.get(Calendar.HOUR_OF_DAY) %>:
<%= myCalendar.get(Calendar.MINUTE) %>:
<%= myCalendar.get(Calendar.SECOND) %>

热门栏目