JSP 构架-2种方式:Model I和Model II__教程 |
|
日期:2007-5-20 1:18:54 人气:165 [大 中 小] |
|
|
|
{ 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. } TimeBean timeBean = new TimeBean(); timeBean.setHours = myCalendar.get(Calendar.HOUR_OF_DAY); timeBean.setMinutes = myCalendar.get(Calendar.MINUTE); timeBean.setSeconds = myCalendar.get(Calendar.SECOND); HttpSession mySession = request.getSession(); mySession.putValue("tempTimeBean", timeBean);
====================================================================== View: displayTime.jsp Again, the view can be either a servlet or a jsp file. Here we´ll get the Bean from the Session, and display its values. We´ll actually do this twice, to illustrate again how Beans are used.
======================================================================
Time JSP : :
HttpSession mySession = request.getSession(); TimeBean timeBean = mySession.getValue("tempTimeBean"); if (timeBean != null) { // check to make sure its not null, to avoid NullPointerExceptions out.print(timeBean.getHours()); out.print(":"); out.print(timeBean.getMinutes()); out.print(":"); out.print(timeBean.getSeconds()); } else { out.println("Press your Back button and select a TimeZone"); } ====================================================================== The second method (using code inside) may be more cumbersome, but allows the developer to ensure against ugly output (such as "null:null:null null") if the Session bean has not been instantiated & had its values set. This would likely only happen if the client somehow called the View page directly. The point is that using scriptlets allows for greater control. If you are certain you can control url access, the bean approach certainly eases development, and makes the View page easier for HTML designers to work with.
The above is the "traditional" Model II design. You´ll note that all the variables are wrapped up and placed into the Session object. This has two weaknesses: 1) no Session is availabe because the client has refused to participate, 2) unless the Session variable is explicitly removed it will continue to exist until the Session is destroyed or expires.
The first case is most likely to happen when cookies are used as the State mechanism and the developers have failed to provide for the alternative form of State maintenance, URL rewriting. |
|
出处:本站原创 作者:佚名 |
|
|