Commit 5c0c75a1 by Patryk Czarnik

Spring wersja poprzednia

parent fcd3d5a1
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
plugins {
id 'java'
id 'org.springframework.boot' version '3.0.6'
id 'io.spring.dependency-management' version '1.1.0'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
rootProject.name = 'PC26-Spring'
package com.example.demo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HistoriaKalkulatoraJSON {
@Autowired
private LogikaKalkulatora logika;
@GetMapping("/historia.json")
public List<String> pokazHistorie() {
return logika.getHistoriaDzialan();
}
}
package com.example.demo;
import java.util.List;
// @Component("inna") i potem za pomocą Qualifier wskazać w miejscu użycia (podczas wstrzykiwania)
// albo można za pomocą @Primary wskazać, że teraz ten komponent ma być wybrany
public class InnaLogika implements LogikaKalkulatora {
@Override
public long oblicz(long liczba1, long liczba2, String operacja) {
long wynik = switch(operacja) {
case "+" -> liczba1 + liczba2 + 1000;
case "-" -> liczba1 - liczba2 + 1000;
case "*" -> liczba1 * liczba2 + 1000;
case "/" -> liczba1 / liczba2 + 1000;
default -> 0L;
};
return wynik;
}
@Override
public List<String> getHistoriaDzialan() {
return List.of("Ala", "Ola", "Ela");
}
}
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/kalkulator")
public class KalkulatorController {
//@Qualifier("inna")
@Autowired
private LogikaKalkulatora logikaKalkulatora;
@GetMapping
public String kalkulatorGet() {
return "kalkulator.html";
}
@PostMapping
public String kalkulatorPost(Long liczba1, Long liczba2, String operacja, Model model) {
if(liczba1 != null && liczba2 != null && operacja != null) {
Long wynik = logikaKalkulatora.oblicz(liczba1, liczba2, operacja);
model.addAttribute("wynik", wynik);
model.addAttribute("historia", logikaKalkulatora.getHistoriaDzialan());
}
return "kalkulator.html";
}
}
package com.example.demo;
import java.util.List;
public interface LogikaKalkulatora {
long oblicz(long liczba1, long liczba2, String operacja);
List<String> getHistoriaDzialan();
}
\ No newline at end of file
package com.example.demo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.stereotype.Component;
/* LogikaKalkulatora jest przykładem "komponentu".
* Podczas startu aplikacji Spring tworzy jeden obiekt tej klasy (tzw. singleton) i zapamiętuje go jako "bean".
* W starszych wersjach Springa tego typu klasy należało zadeklarować w pliku beans.xml.
* Obecnie używa się raczej adnotacji. Takie działanie mają adnotacje: @Component, @Service, @Repository, @Controller.
*
* Inny sposób tworzenia beanów/kompomentów: klasa fabryczna z metodami oznaczonymi @Bean (będą inne przykłady).
*/
@Component
public class LogikaKalkulatoraImpl implements LogikaKalkulatora {
private final List<String> historiaDzialan = Collections.synchronizedList(new ArrayList<>());
@Override
public long oblicz(long liczba1, long liczba2, String operacja) {
long wynik = switch(operacja) {
case "+" -> liczba1 + liczba2;
case "-" -> liczba1 - liczba2;
case "*" -> liczba1 * liczba2;
case "/" -> liczba1 / liczba2;
default -> 0L;
};
historiaDzialan.add(String.format("%d %s %d = %d", liczba1, operacja, liczba2, wynik));
return wynik;
}
@Override
public List<String> getHistoriaDzialan() {
return Collections.unmodifiableList(historiaDzialan);
}
}
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/parametry")
public class ParametryController {
// Najprostsze podejście, aby odczytać wartość parametru zapytania:
// zadeklarować parametr o takiej samej nazwie w metodzie kontrolera.
// "Spring nam to przekaże".
// Podejście polegające na tym, że framework wywołuje "naszą metodę",
// a gdy my czegoś potrzebujemy, to dodajemy odp. parametr do tej metody,
// nazywa się "inversion of control (IoC)".
@GetMapping("/witaj")
@ResponseBody
public String witaj(String imie) {
return "Witaj " + imie;
}
// Dzięki adnotacji @RequestParam mamy większą kontrolę nad szczegółami parametru.
// Można m.in. podać inną nazwę niż nazw zmiennej w Javie, może podać wartość domyślną.
// http://localhost:8080/parametry/powtorz?tekst=Ala%20ma%20kota&n=10
@GetMapping(path="/powtorz", produces="text/plain;charset=utf-8")
@ResponseBody
public String powtorz(
@RequestParam(defaultValue="") String tekst,
@RequestParam(name="n", defaultValue="1") int ileRazy) {
return (tekst + "\n").repeat(ileRazy);
}
// Parametry bez adnotacji są opcjonalne - w razie braku Spring wywoła metodę i wstawi nulla.
// Parametry z adnotacją @RequestParam są domyślnie obowiązkowe. Aby był opcjonalny,
// trzeba wpisać required=false (wtedy brak parametru = null)
// lub podać defaultValue.
}
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Pc26SpringApplication {
public static void main(String[] args) {
SpringApplication.run(Pc26SpringApplication.class, args);
}
}
package com.example.demo;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import jakarta.servlet.http.HttpServletRequest;
@Controller
public class PierwszyController {
// Gdy metoda w kontrolerze zwraca napis, a nie osiada adnotacji @ResponseBody,
// to ten napis jest traktowany jak nazwa szablonu (lub ścieżka do szablonu),
// który ma być użyty do wygenerowania odpowiedzi.
@RequestMapping("/")
public String index() {
return "index.html";
}
// Gdy metoda posiada adnotację @ResponseBody, to, co zwraca returnem, jest odsyłane jako treść odpowiedzi.
@RequestMapping("/hello")
@ResponseBody
public String hello() {
return "Hello world";
}
@RequestMapping("/ping")
public String ping(HttpServletRequest request, Model model) {
// Do metod w kontrolerze można dodawać parametry różnych typów,
// które "Spring zna" i gdy taki parametr się pojawia, to Spring
// wywołując metodę przekazuje nam w tym parametrze odpowiedni obiekt.
// To się nazywa wstrzykiwanie parametrów / parameter injection.
// A ogólnie to podejście, że nie my wywołuemy metodę, aby coś odczytać,
// tylko spring wywołuje NASZĄ metodę i Spring NAM przekazuje wymagane parametry,
// nazywa się "inversion of control" (IoC).
// Przykładowo tutaj dodaliśmy do metody parametr HttpServletRequest
// i Spring przekazuje nam tu techniczne informacje o zapytaniu (to samo, co
// było w serwletach).
// Do modelu można też dodać słownik / mapę.
// Odczyt wartości wygląda później np. tak ${clientInfo.userAgent}
String ip = request.getRemoteAddr();
String host = request.getRemoteHost();
System.out.println("Zapytanie z adresu " + ip);
model.addAttribute("clientInfo", Map.of("userAgent", request.getHeader("User-Agent"), "ip", ip, "host", host));
return "ping.html";
}
}
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ProstyKalkulator {
@RequestMapping("/moj_kalkulator")
public String dzialaj(Long liczba1, Long liczba2, String operacja, Model model) {
if(liczba1 != null && liczba2 != null && operacja != null) {
Long wynik = switch(operacja) {
case "+" -> liczba1 + liczba2;
case "-" -> liczba1 - liczba2;
case "*" -> liczba1 * liczba2;
case "/" -> liczba1 / liczba2;
default -> 0L;
};
model.addAttribute("wynik", wynik);
}
return "moj_kalkulator.html";
}
}
package com.example.demo;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class TimeController {
@RequestMapping("/time1")
@ResponseBody
public LocalTime time1() {
// 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.
return LocalTime.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 LocalTime.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));
}
// 2. Tworzymy odpowiedź za pomocą "szablonu" z wykorzystaniem dodatkowej technologii,
// tutaj jest to Thymeleaf, ale może być coś innego: JSP, Velocity, FreeMarker, Mustache, ...
// Gdy metoda w kontrolerze w wyniku zwraca String, a nie posiada adnotacji @ResponseBody,
// to Spring traktuje zwracaną wartość jak nazwę szablonu,
// w odp. miejscu szuka pliku z szablonem i generuje wynik za pomocą tego szablonu.
// Gdy do szablonu chcemy przekazać jakieś dane, to dodajemy je jako atrybuty do modelu.
// Najprościej zrobić to poprzez parametr model.
@RequestMapping("/time5")
public String time5(Model model) { // IoC inversion of control
LocalDateTime dateTime = LocalDateTime.now();
model.addAttribute("dt", dateTime);
return "wyswietl_czas5.html";
}
@RequestMapping("/time6")
public String time6(Model model) {
LocalDateTime dt = LocalDateTime.now();
model.addAttribute("dt", dt);
List<LocalDate> dates = new ArrayList<>();
LocalDate date = dt.toLocalDate();
for(int i = 0; i <= 5; i++) {
dates.add(date.plusWeeks(i));
}
model.addAttribute("futureWeeks", dates);
return "wyswietl_czas6.html";
}
}
package com.example.demo;
import java.util.stream.Collectors;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class WstrzykiwaniePrzezKonstruktor {
private LogikaKalkulatora logikaKalkulatora;
// Jeśli jedynym dostępnym konstruktorem jest taki, który wymaga parametrów,
// Spring wywoła własnie ten konstruktor i przekaże wymagane parametry, o ile uda mu się takie obiekty znaleźć.
// To też jest forma wstrzykiwania zależności.
// Zauważmy, że działa bez żadnej adnotacji przed tym konstruktorem.
public WstrzykiwaniePrzezKonstruktor(LogikaKalkulatora logikaKalkulatora) {
this.logikaKalkulatora = logikaKalkulatora;
}
// public WstrzykiwaniePrzezKonstruktor(@Qualifier("inna") LogikaKalkulatora logikaKalkulatora) {
// this.logikaKalkulatora = logikaKalkulatora;
// }
@GetMapping(path="/liczenie", produces="text/plain")
@ResponseBody
public String liczenie(Long liczba1, Long liczba2, String operacja) {
return String.valueOf(logikaKalkulatora.oblicz(liczba1, liczba2, operacja));
}
@GetMapping(path="/historia.txt", produces="text/plain")
@ResponseBody
public String dajHistorie() {
return logikaKalkulatora.getHistoriaDzialan()
.stream()
.map(s -> " → " + s)
.collect(Collectors.joining("\n"));
}
}
body {
background-color: #FFFFCC;
font-family: 'Arial', sans-serif;
}
h1 {
color: green;
text-align: center;
}
form {
margin: 30px auto;
padding: 20px;
width: 800px;
border: 4px solid blue;
background-color: #AAEEFF;
}
.wynik {
background-color: #FFFFFF;
border: 3px solid green;
margin: 20px auto;
width: 800px;
padding: 10px;
color: green;
}
.error {
background-color: #FFFFFF;
border: 6px double red;
margin: 20px auto;
padding: 10px;
width: 800px;
color: red;
font-weight: bold;
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Spis treści</title>
<link rel="stylesheet" type="text/css" th:href="@{/styl.css}">
</head>
<body>
<h1>Spis treści</h1>
<h2>Przykłady pisane bezpośrednio w Controllerze</h2>
<ul>
<li><a th:href="@{/hello}">Hello</a></li>
<li><a th:href="@{/ping}">Ping</a></li>
<li><a th:href="@{/time1}">Czas obiektowo</a> (json)</li>
<li><a th:href="@{/time2}">Czas tekstowo</a></li>
<li><a th:href="@{/time3}">Czas tekstowo</a> (text/plain)</li>
<li><a th:href="@{/time4}">Czas HTML w Javie</a></li>
</ul>
<h2>Przykłady z szablonami</h2>
<ul>
<li><a th:href="@{/time5}">Czas szablon prosty</a></li>
<li><a th:href="@{/time6}">Czas szablon rozbudowany</a></li>
</ul>
<h2>Przykład Parametry</h2>
<ul>
<li><a th:href="@{/parametry/witaj}">witaj</a></li>
<li><a th:href="@{/parametry/witaj(imie='Ala')}">witaj?imie=Ala</a></li>
<li><a th:href="@{/parametry/powtorz}">powtorz</a></li>
<li><a th:href="@{/parametry/powtorz(tekst='Ola ma psa')}">powtorz</a> n = 1</li>
<li><a th:href="@{/parametry/powtorz(tekst='Ala ma kota',n=10)}">powtorz</a> n = 10</li>
</ul>
<h2>Przykłady formularzy</h2>
<ul>
<li><a th:href="@{/moj_kalkulator}">Prosty Kalkulator</a> - wersja z zajęć</li>
<li><a th:href="@{/kalkulator}">Kalkulator</a> (formlularz)</li>
<li><a th:href="@{/kalkulator/historia}">Historia Kalkulatora HTML</a></li>
<li><a th:href="@{/historia.json}">Historia Kalkulatora JSON</a></li>
<li><a th:href="@{/historia.txt}">Historia tekstowo</a></li>
<li><a th:href="@{liczenie(liczba1=211,liczba2=303,operacja='*')}">Liczenie bezpośrednie</a> w parametrami URL</li>
</ul>
</body>
</html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Kalkulator</title>
<link rel="stylesheet" type="text/css" th:href="@{/styl.css}">
</head>
<body>
<h1>Kalkulator</h1>
<form method="post" class="kalkulator">
<input type="number" name="liczba1" th:value="${param.liczba1}">
<select name="operacja">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="number" name="liczba2" th:value="${param.liczba2}">
<br>
<button>Oblicz</button>
</form>
<div th:if="${wynik != null}" class="wynik">
<span th:text="${param.liczba1}">2</span>
<span th:text="${param.operacja}">+</span>
<span th:text="${param.liczba2}">3</span>
=
<strong th:text="${wynik}">5</strong>
</div>
<section th:if="${historia != null and !historia.isEmpty()}">
<h2>Historia działań</h2>
<ul>
<li th:each="element: ${historia}" th:text="${element}">2 + 2 = 4</li>
</ul>
</section>
<div><a th:href="@{/historia.json}">historia JSON</a></div>
<div><a th:href="@{/historia.txt}">historia TXT</a></div>
<div><a th:href="@{/}">wróć do strony głównej</a></div>
</body>
</html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Kalkulator</title>
<link rel="stylesheet" type="text/css" th:href="@{/styl.css}">
</head>
<body>
<h1>Kalkulator</h1>
<form class="kalkulator">
<input type="number" name="liczba1" th:value="${param.liczba1}">
<select name="operacja">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="number" name="liczba2" th:value="${param.liczba2}">
<br>
<button>Oblicz</button>
</form>
<div class="wynik">
[[${wynik}]]
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="pl" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Ping</title>
<link rel="stylesheet" type="text/css" th:href="@{/styl.css}" href="../static/styl.css">
</head>
<body>
<h2>Informacje o kliencie</h2>
<ul>
<li>Adres: <strong th:text="${clientInfo.ip}">1.2.3.4</strong> (<span th:text="${clientInfo.host}">abc.com</span>)</li>
<li>Przeglądarka: <strong th:text="${clientInfo.userAgent}">IE</strong></li>
</ul>
</body>
</html>
<!DOCTYPE html>
<html lang="pl" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Która godzina</title>
</head>
<body>
<p>Data i czas: [[${dt}]].</p>
<p>Dzisiaj mamy [[${dt.dayOfYear}]] dzień roku [[${dt.year}]].</p>
<hr>
<p>Data i czas: <strong th:text="${dt}">2023-03-03T13:13:14.123123</strong>.</p>
<p>Dzisiaj mamy <span th:text="${dt.dayOfYear}">12</span> dzień roku <span th:text="${dt.year}">2020</span>.</p>
</body>
</html>
<!DOCTYPE html>
<html lang="pl" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Show Time 6</title>
<link rel="stylesheet" type="text/css" th:href="@{/styl.css}" href="../static/styl.css">
</head>
<body>
<h1>Data i czas</h1>
<h3>Trzy sposoby wstawiania wartości atrybutu w Thymeleaf</h3>
<ul>
<!-- th:text oraz data-th-text to są przykłady podejścia "natural template",
czyli że plik jest poprawnym składniowo dokumentem HTML, a dodatkowe magiczne atrybuty powodują specjalne działanie"
gdy ten plik jest przetwarzany przez "silnik thymeleaf".
-->
<!-- Najbardziej zalecane podejście: dodatkowa przestrzeń nazw th
Aby to zadziałało, w HTMLu (najczęściej na samym początku) musi byś zadeklarowana przestrzeń nazw.
"Tekst, który znajduje się wewnątrz znacznika, zastąp wartością zmiennej dt"
-->
<li th:text="${dt}">jakaś godzina 1</li>
<!-- atrybuty "data" wprowadzone w HTML 5
Normalnie takich atrybutów używają skrypty JS, aby w dokumencie zapamiętywać dane,
a tutaj Thymeleaf używa w innym celu.
-->
<li data-th-text="${dt}">jakaś godzina 2</li>
<!-- zagnieżdżone wyrażenia / inline expressions - podejście podobne do JSP, tutaj mniej zalecane -->
<li>to jest wynik: [[${dt}]]</li>
</ul>
<h3>Odwołania do elementów zagnieżdżonych</h3>
<ul>
<!-- tak naprawdę wywołanie dt.getYear() -->
<li>rok: <strong th:text="${dt.year}">1997</strong></li>
<li>dzień roku: <strong th:text="${dt.dayOfYear}">100</strong></li>
<li>dzień tygodnia: <strong th:text="${dt.dayOfWeek}">MONDAY</strong></li>
<li>sekunda: <strong th:text="${dt.second}">33</strong></li>
<!-- Można też wywołać metodę, która coś odczyta, nawet jeśli nie nazywa się getXXX() -->
<li>data: <strong th:text="${dt.toLocalDate()}">2020-04-05</strong></li>
<li>czas: <strong th:text="${dt.toLocalTime()}">10:44:22</strong></li>
</ul>
<h3>Odczyt elementów listy</h3>
<p>Ten sam dzień w kolejnych tygodniach:</p>
<ol start="0">
<li th:each="date : ${futureWeeks}" th:text="${date}">2022-08-01</li>
</ol>
</body>
</html>
package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class Pc26SpringApplicationTests {
@Test
void contextLoads() {
}
}
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