Perdelerin arkasında Spring MVC

Spring MVC'nin Bileşenleri

  1. UI (arayüz) elemanlarını düzenlemek için birkaç web sayfası.
  2. Spring beanları (controllers,services,repositories...)
  3. Spring configuration (XML,Annotations,Java)

Front Controler DispatcherServlet olarak bilinir ve Spring Developer ekibi tarafından geliştirilmiş Spring frameworkün bir parçasıdır.

  1. Model objects
  2. View templates
  3. Controller classes

oluşturacağız.

  1. Controller (@Controller) bizim oluşturduğumuz ve business logic (istekleri alır işler, datayı alır depolar, datayı modele yerleştirir) içeren koddur ve daha sonrasında view templatesine gönderir
  2. Model bizim backend tarafından aldığımız (db,webservice) veriyi içerir. Data Java nesnesi yada collectionu olabilir.
  3. View template developer tarafından oluşturulmuş ve datayı gösteren bir templatedir.

Spring MVC tarafından en çok kullanılan HTTP Methodları 2 tanedir:

GET -> Kaynaktan veriyi istemek için kullanılır. @RequestMapping(path="/path",method=RequestMethod.GET)

POST -> Veriyi kaynağa yollar. @RequestMapping(path="/path",method=RequestMethod.POST)


Teacher.java

public class Teacher {
 
    private Long id;
    private String firstName;
    private String lastName;
 
    public Long getId() {
        return id;
    }
 
    public void setId(Long id) {
        this.id = id;
    }
 
    public String getFirstName() {
        return firstName;
    }
 
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
 
    public String getLastName() {
        return lastName;
    }
 
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}


TeacherController.java

@Controller
public class TeacherController {
    @RequestMapping(path = "/showForm", method = RequestMethod.GET)
    public String getForm(Model theModel) {
        Teacher teacher = new Teacher();
        theModel.addAttribute("teacher", teacher);
        return "show-form";
    }
 
    @RequestMapping(path = "/sendForm", method = RequestMethod.POST)
    public String sendForm(@ModelAttribute("teacher") Teacher teacher, Model theModel) {
        System.out.println("Öğretmen : " + teacher.getFirstName());
        theModel.addAttribute("message", "Öğretmen eklendi");
        return "show-form";
    }
}



show-form.html

<!DOCTYPE html>
<html xmlns:th='http://www.thymeleaf.org'>
    <head>
        <title>Show Form</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <p th:text='${message}'/>
        <form action="#" th:action='@{/sendForm}' method="POST" th:object='${teacher}'>
            <label>İsim </label><br/>
            <input type='text' th:field='*{firstName}'/><br/>
            <label>Soyisim </label><br/>
            <input type='text' th:field='*{lastName}'/>
            <input type='submit' value='Kaydet'/>
        </form>
    </body>
</html>