19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

}<br />

}<br />

allLocale[i].getDisplayName() + "");<br />

}<br />

out.println("");<br />

// Fill in all time zones<br />

out.println("Time Zone");<br />

for (int i = 0; i < allTimeZone.length; i++) {<br />

out.println("" +<br />

allTimeZone[i] + "");<br />

}<br />

out.println("");<br />

out.println("");<br />

out.println("");<br />

out.println("");<br />

out.close(); // Close stream<br />

/** Process the HTTP Post request */<br />

public void doPost(HttpServletRequest request, HttpServletResponse<br />

response) throws ServletException, IOException {<br />

response.setContentType(CONTENT_TYPE);<br />

PrintWriter out = response.getWriter();<br />

out.println("");<br />

int localeIndex = Integer.parseInt(<br />

request.getParameter("locale"));<br />

String timeZoneID = request.getParameter("timezone");<br />

out.println("Current Time");<br />

out.println("");<br />

Calendar calendar =<br />

new GregorianCalendar(allLocale[localeIndex]);<br />

TimeZone timeZone = TimeZone.getTimeZone(timeZoneID);<br />

DateFormat dateFormat = DateFormat.getDateTimeInstance(<br />

DateFormat.FULL, DateFormat.FULL, allLocale[localeIndex]);<br />

dateFormat.setTimeZone(timeZone);<br />

out.println("Current time is " +<br />

dateFormat.format(calendar.getTime()) + "");<br />

out.println("");<br />

out.close(); // Close stream<br />

}<br />

When you run this servlet, the servlet TimeForm’s doGet method is<br />

invoked <strong>to</strong> generate the time form dynamically. The method of the form is<br />

POST, and the action invokes the same servlet, TimeForm. When the form<br />

is submitted <strong>to</strong> the server, the doPost method is invoked <strong>to</strong> process the<br />

request.<br />

The variables allLocale and allTimeZone (lines 11–12), respectively,<br />

hold all the available locales and time zone IDs. The names of the<br />

locales are displayed in the locale list. The values for the locales are<br />

the indexes of the locales in the array allLocale. The time zone IDs are<br />

strings. They are displayed in the time zone list. They are also the<br />

values for the list. The indexes of the locale and the time zone are<br />

passed <strong>to</strong> the servlet as parameters. The doPost method obtains the<br />

values of the parameters (lines 51–53) and finds the current time based<br />

on the locale and time zone.<br />

NOTE<br />

<br />

22

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!