Commit 5d23f733 by Patryk Czarnik

kalkulator - wszystko w kontrolerze

parent 7dbee03e
package com.example.demo;
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 Kalkulator {
@GetMapping
public String kalkulatorGet() {
return "kalkulator.html";
}
@PostMapping
public String kalkulatorPost(Model model, long liczba1, long liczba2, String operacja) {
long wynik = switch(operacja) {
case "+" -> liczba1 + liczba2;
case "-" -> liczba1 - liczba2;
case "*" -> liczba1 * liczba2;
case "/" -> liczba1 / liczba2;
case "%" -> liczba1 % liczba2;
default -> 0;
};
model.addAttribute("wynik", wynik);
return "kalkulator.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}" href="../static/styl.css">
</head>
<body>
<h1>Kalkulator</h1>
<form class="kalkulator" method="post">
<input type="number" name="liczba1" th:value="${param.liczba1}">
<select name="operacja">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">×</option>
<option value="/">÷</option>
<option value="%">mod</option>
</select>
<input type="number" name="liczba2" th:value="${param.liczba2}">
<button>Oblicz</button>
</form>
<div class="wynik" th:if="${wynik != null}">
<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>
<div class="error" th:if="${error != null}" th:text="${error}">
Straszny błąd!
</div>
</body>
</html>
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