[Thực hành] Ứng dụng xem giờ hiện tại của các thành phố trên thế giới

2. Spring MVC

Mục tiêu

Luyện tập sử dụng Controller trong Spring MVC.

Điều kiện

Biết cách sử dụng Controller trong Spring MVC.

Mô tả

Trong phần này, chúng ta sẽ phát triển một ứng dụng cho phép hiển thị thời gian hiện tại của các thành phố lớn trên thế giới.

Ứng dụng hiển thị một danh sách các thành phố cho sẵn trong Combobox, cho phép người dùng chọn lựa một thành phố và sau đó hiển thị thời gian của thành phố được lựa chọn.

Hướng dẫn

Bước 1: Tạo project đặt tên spring-timezone.

Cấu hình project sử dụng Gradle như trong bài trước. Cấu trúc project như sau:

Bước 2: Tạo lớp TimeController để xử lý request của người dùng

package controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.TimeZone;

@Controller
public class TimeController {

@GetMapping("/worldclock")
public String getTimeByTimezone(ModelMap model, @RequestParam(name = "city", required = false, defaultValue = "Asia/Ho_Chi_Minh") String city) {

// codes below here

return "index";
}
}

Trong đó:

  • @RequestMapping(“worldclock”)  ánh xạ request lên phương thức xử lý.
  • @RequestParam(name = “city”, required = false, defaultValue = “Asia/Ho_Chi_Minh”)  khai báo tham số của phương thức xử lý, ràng buộc với tham số từ request.

Bước 3: Xử lý để lấy thời gian hiện tại của một thành phố trên thế giới

Thêm mã lệnh vào phương thức getTimeByTimezone() như sau:

Đầu tiên chúng ta sẽ lấy thời gian hiện tại và múi giờ của địa phương cùng với múi giờ của thành phố được chỉ định.

// Get current time at local
Date date = new Date();
// Get timezone by the local
TimeZone local = TimeZone.getDefault();
// Get timezone by the specified city
TimeZone locale = TimeZone.getTimeZone(city);

Xác định thời gian hiện tại của thành phố được chỉ định dựa trên sự chênh lệch về thời gian giữa các múi giờ và múi giờ chuẩn (UTC).
Hàm getRawOffset()trả về lượng thời gian tính bằng mili giây để thêm vào UTC để có thời gian chuẩn trong múi giờ này.

// Calculate the current time in the specified city
long locale_time = date.getTime() +
(locale.getRawOffset() - local.getRawOffset());
// Reset the date by locale_time
date.setTime(locale_time);

Bước 4: Chuyển dữ liệu về cho view

// Set the data sent to the view
model.addAttribute("city", city);
model.addAttribute("date", date);
return "index";

Bước 5: Tạo view index.jsp

Sử dụng form để gửi request lên server

<form id="locale" action="worldclock" method="get">

Sử dụng Expression  language (EL) để hiển thị dữ liệu từ controller chuyển đến

<span>Current time in ${city}: <strong>${date}</strong></span>

Toàn bộ file index.jsp như sau: 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>The World Clock</title>
<style type="text/css">
select {
width: 200px;
height: 20px;
}
</style>
</head>
<body>
<h2>Current Local Times Around the World</h2>
<span>Current time in ${city}: <strong>${date}</strong></span>
<form id="locale" action="worldclock" method="get">
<select name="city" onchange="document.getElementById('locale').submit()">
<option value="Asia/Ho_Chi_Minh">Select a city</option>
<option value="Asia/Ho_Chi_Minh" selected>Ho Chi Minh</option>
<option value="Singapore">Singapore</option>
<option value="Asia/Hong_Kong">Hong Kong</option>
<option value="Asia/Tokyo">Tokyo</option>
<option value="Asia/Seoul">Seoul</option>
<option value="Europe/London">London</option>
<option value="Europe/Madrid">Madrid</option>
<option value="America/New_York">New York</option>
<option value="Australia/Sydney">Sydney</option>
<option value="Argentina/Buenos_Aires">Buenos Aires</option>
</select>
</form>
</body>
</html>

Bước 6: Thực thi chương trình và quan sát kết quả

Mở trình duyệt với url: http://localhost:8080/worldclock

 Mã nguồn tham khảo tại: https://github.com/codegym-vn/spring-timezone

Leave a Reply

Your email address will not be published.