Commit e9a247f0 by Patryk Czarnik

Przykład Parametry

parent 5d23f733
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/* Gdy adres (w adnotacji RequestMapping albo GetMapping)
* jest podany na poziomie klasy, a potem na poziomie metody,
* to prawdziwy adres, pod którym działa metoda, jest połączeniem tych dwóch fragmentów.
*
* http://localhost:8080/parametry/witaj?imie=Ala
*/
@Controller
@RequestMapping("/parametry")
public class ParametryController {
@RequestMapping("/witaj")
@ResponseBody
// 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śc potrzebujemy, to dodajemy odp. parametr do tej metody,
// nazywa się "inversion of control (IoC)".
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
@RequestMapping(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);
}
}
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