Perdelerin arkasında Spring MVC
Spring MVC'nin Bileşenleri
- UI (arayüz) elemanlarını düzenlemek için birkaç web sayfası.
- Spring beanları (controllers,services,repositories...)
- 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.
- Model objects
- View templates
- Controller classes
oluşturacağız.
- 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
- Model bizim backend tarafından aldığımız (db,webservice) veriyi içerir. Data Java nesnesi yada collectionu olabilir.
- 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)
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;
}
}@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>