Commit cba8a466 by Patryk Czarnik

time1 - time4

parent f898136a
package alx;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
@Controller
public class TimeController {
// Gdy metoda zwraca jakiś obiekt (klasy innej niż String i niektóre inne "magiczne" klasy samego Springa),
// a metoda posiada adnotację @ResponseBody, to dane odsyłane są w odpowiedzi w formacie JSON.
@RequestMapping("/time1")
@ResponseBody
public LocalDateTime time1() {
return LocalDateTime.now();
}
@RequestMapping("/time2")
@ResponseBody
public String time2() {
// Gdy metoda zwraca String i posiada adnotację @ResponseBody, to dane odsyłane są w odpowiedzi jako HTML.
// (tzn. są oznaczone jako text/html, ale nie są automatycznie formatowane).
return LocalDateTime.now().toString();
}
private static final DateTimeFormatter FORMAT_DATY = DateTimeFormatter
.ofPattern("EEEE, dd.MM.YYYY, 'godzina' HH:mm:ss", new Locale("pl", "PL"));
// Aby powiedzieć wprost, jaki jest format (content-type) odpowiedzi zwracanej przez metdę, można uzyć parametru produces
@RequestMapping(path="/time3", produces="text/plain")
@ResponseBody
public String time3() {
return LocalDateTime.now().format(FORMAT_DATY);
}
// Jak wysłać w odpowiedzi HTML?
// 1. Utworzyć bezpośrednio w kodzie Javy... - słabe
@RequestMapping(path="/time4", produces="text/html")
@ResponseBody
public String time4() {
LocalDateTime dt = LocalDateTime.now();
return String.format(
"<html><body><h1>Data i czas</h1>"
+ "<p>Teraz jest godzina <strong style='color:purple'>%s</strong></p>"
+ "<p>Dzisiejsza data: <strong style='color:blue'>%s</strong></p>"
+ "<p style='color: green'>%s</p>"
+ "</body></html>",
dt.toLocalTime(), dt.toLocalDate(), dt.format(FORMAT_DATY));
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment