Thymeleaf Forms Sinhala Guide | ඔබේ Web App වලට Forms හදන්න - Sri Lanka

Thymeleaf Forms Sinhala Guide | ඔබේ Web App වලට Forms හදන්න - Sri Lanka

ආයුබෝවන් යාළුවනේ! ඉතින් කොහොමද ඔයාලට? අද අපි කතා කරන්න යන්නේ Web Development කරන අපිට ගොඩක්ම වැදගත් වෙන මාතෘකාවක් ගැන. ඒ තමයි Thymeleaf Forms. ඕනෑම Web Application එකක User Data ගන්න Form එකක් අනිවාර්යයෙන්ම තියෙන්න ඕනේ නේද? User Login එකක ඉඳන්, Product Order කරන තැනට, Feedback දෙන්න, Contact Details ගන්න වගේ හැම තැනටම Form අත්‍යවශ්‍යයි.

ඉතින් මේ Forms ලස්සනට, හරියට, පහසුවෙන් හදන්නේ කොහොමද කියන එක තමයි අද අපි Thymeleaf එක්ක බලන්න යන්නේ. ඔයාලා Spring Boot එක්ක වැඩ කරනවා නම්, Thymeleaf කියන්නේ Forms හදන්න තියෙන නියමම Templating Engine එකක්. ඒකෙන් අපිට Server-side rendering හරහා Dynamic web pages හදන්න පුළුවන්, ඒ වගේම Forms Manage කරන එකත් ගොඩක් පහසු කරනවා. එහෙනම් අපි පටන් ගමු!


Thymeleaf Forms කියන්නේ මොනවාද?

සරලවම කිව්වොත්, Thymeleaf කියන්නේ Java Web Applications වල View Layer එක හදන්න පාවිච්චි කරන Server-side templating engine එකක්. ඒක Spring Framework එකත් එක්ක ගොඩක් හොඳට Integrate වෙනවා. HTML, XML, JavaScript, CSS, Text වගේ Templates හදන්න Thymeleaf පාවිච්චි කරන්න පුළුවන්.

Forms සම්බන්ධයෙන් ගත්තොත්, Thymeleaf අපිට HTML Form Elements වලට Backend Data එක්ක බඳින්න (bind කරන්න) පුළුවන් විශේෂ Attributes (th:object, th:field වගේ) සපයනවා. මේකෙන් අපේ Code එක Clean වෙනවා වගේම, Form Data Handling එකත් ගොඩක් පහසු වෙනවා. ඒ වගේම, Thymeleaf වල Natural Templating නිසා, අපේ HTML Files Browser එකේ Directly Open කරලා බලන්න පුළුවන්, Backend එක Run කරන්නේ නැතුව වුණත්.

ඇයි Thymeleaf Forms පාවිච්චි කරන්න ඕනේ?

  • සරල බව: HTML එක්ක Direct වැඩ කරන්න පුළුවන් නිසා ඉගෙන ගන්න පහසුයි.
  • Spring Boot Integration: Spring Boot එක්ක ගොඩක් හොඳට වැඩ කරනවා.
  • Data Binding: Java Objects එක්ක Form Fields පහසුවෙන් බඳින්න පුළුවන්.
  • Validation Support: Form Data Validations Management පහසු කරනවා.
  • Error Handling: Forms වල Errors ලස්සනට පෙන්වන්න පුළුවන්.

Form එකක් හදමු: Student Registration Example

අපි හිතමු අපිට Student Registration Form එකක් හදන්න ඕනේ කියලා. මේකෙන් Student ගේ Name, Email, සහ Course එක ගන්නවා. මුලින්ම අපිට Student Data Store කරන්න Java Class එකක් ඕනේ. අපි ඒකට Student කියලා Class එකක් හදමු.

1. Model Class එක හදමු (Student.java)

package com.example.thymeleafdemo.model;

public class Student {

    private String name;
    private String email;
    private String course;

    // Default constructor is important for Spring/Thymeleaf
    public Student() {
    }

    // Constructor with fields (optional, but good for testing)
    public Student(String name, String email, String course) {
        this.name = name;
        this.email = email;
        this.course = course;
    }

    // Getters and Setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getCourse() {
        return course;
    }

    public void setCourse(String course) {
        this.course = course;
    }

    @Override
    public String toString() {
        return "Student{" +
               "name='" + name + '\'' +
               ", email='" + email + '\'' +
               ", course='" + course + '\'' +
               '}';
    }
}

2. Controller එක හදමු (StudentController.java)

දැන් අපිට Form එක Browser එකට පෙන්වන්න Controller එකක් ඕනේ. මේකේදී අපි GET Request එකක් Handle කරනවා.

package com.example.thymeleafdemo.controller;

import com.example.thymeleafdemo.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/students")
public class StudentController {

    @GetMapping("/register")
    public String showRegistrationForm(Model model) {
        // Create a new Student object to bind with the form
        model.addAttribute("student", new Student());
        return "registration-form"; // This will resolve to src/main/resources/templates/registration-form.html
    }
}

මෙහිදී අපි Model Object එකට හිස් Student Object එකක් "student" නමින් Add කරනවා. Form එකේ Data Bind වෙන්නේ මේ Object එකට තමයි.

3. Thymeleaf HTML Form එක හදමු (src/main/resources/templates/registration-form.html)

දැන් අපි Form එක හදමු. th:object, th:field, th:action වගේ Thymeleaf Attributes ගැන හොඳට අවධානය දෙන්න.

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Student Registration</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background-color: #f4f4f4; }
        .container { background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); max-width: 500px; margin: auto; }
        h1 { text-align: center; color: #333; }
        form div { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; }
        input[type="text"], input[type="email"], select { width: calc(100% - 22px); padding: 10px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
        button { background-color: #007bff; color: white; padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; }
        button:hover { background-color: #0056b3; }
    </style>
</head>
<body>
    <div class="container">
        <h1>Student Registration Form</h1>
        <!--
            th:action="@{/students/register}" defines the URL where the form data will be submitted.
            th:object="${student}" binds the form to the 'student' object passed from the controller.
        -->
        <form action="#" th:action="@{/students/register}" th:object="${student}" method="post">
            <div>
                <label for="name">Student Name:</label>
                <!--
                    th:field="*{name}" binds this input field to the 'name' property of the 'student' object.
                    The 'id' and 'name' attributes are automatically generated by Thymeleaf.
                -->
                <input type="text" id="name" th:field="*{name}" placeholder="Enter your name" required>
            </div>

            <div>
                <label for="email">Student Email:</label>
                <input type="email" id="email" th:field="*{email}" placeholder="Enter your email" required>
            </div>

            <div>
                <label for="course">Select Course:</label>
                <select id="course" th:field="*{course}" required>
                    <option value="">-- Select a Course --</option>
                    <option value="Computer Science">Computer Science</option>
                    <option value="Software Engineering">Software Engineering</option>
                    <option value="Data Science">Data Science</option>
                    <option value="Cyber Security">Cyber Security</option>
                </select>
            </div>

            <div>
                <button type="submit">Register</button>
            </div>
        </form>
    </div>
</body>
</html>

මේ Form එකේ වැදගත්ම කොටස් ටික තමයි:

  • <html xmlns:th="http://www.thymeleaf.org">: මේකෙන් Thymeleaf Namespace එක Declare කරනවා.
  • <form ... th:action="@{/students/register}" th:object="${student}" method="post">:
    • th:action="@{/students/register}": Form එක Submit වුණාම Request එක යවන්නේ /students/register URL එකට. @{...} කියන්නේ URL Expression එකක්, මේකෙන් Context Path එක Auto Handle වෙනවා.
    • th:object="${student}": Controller එකෙන් Model එකට Add කරපු student Object එක මේ Form එකට Bind කරනවා. මේකෙන් තමයි Form Field වලට අදාළ Properties අඳුරගන්නේ.
    • method="post": Form එක Submit වෙන්නේ POST Request එකක් විදිහට.
  • <input ... th:field="*{name}">: මේකෙන් Input Field එක th:object එකේ තියෙන name Property එකට Bind කරනවා. id සහ name Attributes Thymeleaf වලින් Auto Generate වෙනවා. *{} කියන්නේ Selection Expression එකක්.

Form එක Process කරමු: Data Save කිරීම

Form එක Submit වුණාම, Data Controller එකට එනවා. අපි ඒ Data අරගෙන Process කරන්නේ කොහොමද කියලා බලමු. ඒකට අපි Controller එකට තව Method එකක් Add කරනවා, ඒක POST Request Handle කරනවා.

StudentController.java එක Update කරමු

package com.example.thymeleafdemo.controller;

import com.example.thymeleafdemo.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/students")
public class StudentController {

    @GetMapping("/register")
    public String showRegistrationForm(Model model) {
        model.addAttribute("student", new Student());
        return "registration-form";
    }

    @PostMapping("/register")
    public String processRegistrationForm(@ModelAttribute("student") Student student, Model model) {
        // Here, 'student' object automatically contains the submitted form data
        System.out.println("Registered Student: " + student.toString());

        // In a real application, you would save this student object to a database
        // studentService.save(student);

        model.addAttribute("message", "Student <strong>" + student.getName() + "</strong> registered successfully!");
        return "registration-success"; // Display a success page
    }
}

අලුතෙන් Add කරපු processRegistrationForm Method එකේ වැදගත් දේවල්:

  • @PostMapping("/register"): මේකෙන් කියන්නේ මේ Method එක /students/register URL එකට එන POST Requests Handle කරනවා කියලා.
  • @ModelAttribute("student") Student student: මේක ගොඩක්ම වැදගත්. Form එකෙන් Submit වෙන Data, Student Class එකේ Properties වලට Map කරලා, Brand New Student Object එකක් විදිහට මේ Method එකට Inject කරනවා. ඒ කියන්නේ, Form එකේ දාපු Name, Email, Course ඔක්කොම මේ student Object එක ඇතුළේ තියෙනවා. අපිට ඒවා ගන්න Getters පාවිච්චි කරන්න පුළුවන්.
  • System.out.println("Registered Student: " + student.toString());: මෙතනදී අපි Data Console එකේ Print කරනවා. Real Application එකකදී මේ Data Database එකක Save කරන එක තමයි කරන්නේ.
  • return "registration-success";: Data Process කරාට පස්සේ, අපි User ට Success Message එකක් පෙන්වන්න registration-success.html කියන View එකට Redirect කරනවා.

4. Success Page එක හදමු (src/main/resources/templates/registration-success.html)

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Registration Success</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background-color: #f4f4f4; }
        .container { background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); max-width: 500px; margin: auto; text-align: center; }
        h1 { color: #28a745; }
        p { font-size: 1.1em; color: #333; }
        .back-link { display: inline-block; margin-top: 20px; padding: 10px 15px; background-color: #007bff; color: white; text-decoration: none; border-radius: 4px; }
        .back-link:hover { background-color: #0056b3; }
    </style>
</head>
<body>
    <div class="container">
        <h1>Registration Successful!</h1>
        <p th:utext="${message}">A default success message.</p>
        <p>Thank you for registering.</p>
        <a th:href="@{/students/register}" class="back-link">Register Another Student</a>
    </div>
</body>
</html>

මෙහිදී <p th:utext="${message}"> කියන එකෙන් Controller එකෙන් එවන message Display කරනවා. utext කියන්නේ HTML Tag වලට Support එකක් දෙනවා කියන එකයි (<strong> වගේ).


Validation සහ Error Handling (කෙටියෙන්)

Form එකක් හදනකොට Validation කියන්නේ අනිවාර්යයෙන්ම තියෙන්න ඕනේ දෙයක්. User වැරදි Data දැම්මොත් ඒක අඳුරගෙන ඒ ගැන User ට පෙන්වන එක ගොඩක් වැදගත්. Spring Boot සහ Thymeleaf එක්ක අපිට Bean Validation API (JSR 380) පාවිච්චි කරන්න පුළුවන්.

Student Class එකට අපි Annotations ටිකක් Add කරමු:

package com.example.thymeleafdemo.model;

import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;

public class Student {

    @NotBlank(message = "Name cannot be empty")
    @Size(min = 2, max = 50, message = "Name must be between 2 and 50 characters")
    private String name;

    @NotBlank(message = "Email cannot be empty")
    @Email(message = "Invalid email format")
    private String email;

    @NotBlank(message = "Please select a course")
    private String course;

    // Constructors, Getters, Setters, toString() - same as before
    // ...
}

දැන් Controller එකේ @ModelAttribute එකට @Valid එකතු කරලා, BindingResult Object එකක් Parameter එකක් විදිහට ගන්න ඕනේ:

@PostMapping("/register")
public String processRegistrationForm(@Valid @ModelAttribute("student") Student student, BindingResult bindingResult, Model model) {
    if (bindingResult.hasErrors()) {
        // If there are validation errors, return to the form page
        return "registration-form";
    }
    
    System.out.println("Registered Student: " + student.toString());
    model.addAttribute("message", "Student <strong>" + student.getName() + "</strong> registered successfully!");
    return "registration-success";
}

Form එකේ Errors පෙන්වන්න, අදාළ Input Field එකට යටින් <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></span> වගේ දෙයක් දාන්න පුළුවන්. මේකෙන් name Field එකට Error එකක් තියෙනවා නම්, ඒ Error Message එක Display වෙනවා.

<div>
    <label for="name">Student Name:</label>
    <input type="text" id="name" th:field="*{name}" placeholder="Enter your name" required>
    <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}" style="color: red;">Name Error</span>
</div>

මේ වගේම අනිත් Field වලටත් දාන්න පුළුවන්. #fields කියන්නේ Thymeleaf වල තියෙන Utility Object එකක්, ඒකෙන් Form Fields සහ Validation Errors Handle කරන්න පුළුවන්.


අවසානයට

හරි යාළුවනේ, අපි අද Thymeleaf පාවිච්චි කරලා Web Application එකකට Forms හදන හැටි මුල ඉඳන්ම ඉගෙන ගත්තා. Model Class එකක් හදපු හැටි, Controller එකේ GET සහ POST Request Handle කරපු හැටි, ඒ වගේම Thymeleaf HTML එකේ th:object, th:field, th:action වගේ Attributes පාවිච්චි කරලා Form එකක් හදපු හැටිත් අපි බැලුවා.

ඒ වගේම, Data Validation වල වැදගත්කම සහ ඒක Thymeleaf එක්ක Implement කරන හැටිත් අපි කෙටියෙන් සාකච්ඡා කළා. මේක ඔයාලගේ Web Development Journey එකට ගොඩක්ම වැදගත් වෙයි කියලා මම හිතනවා.

දැන් ඉතින් ඔයාලගේ වෙලාව! මේ Concepts ටික ඔයාලගේම Project එකකට Add කරලා බලන්න. පොඩි පොඩි Forms හදලා, Data Save කරලා, Validation දාලා බලන්න. මොනවා හරි ප්‍රශ්නයක් ආවොත් හෝ තව දැනගන්න ඕන දෙයක් තියෙනවා නම්, පහළින් Comment එකක් දාගෙන යන්න අමතක කරන්න එපා. අපි ඊළඟ Blog Post එකෙන් හමුවෙමු! Happy Coding!