18 Nisan 2018 Çarşamba

SpringMVC @ModelAttribute Anotasyonu - Form Nesnesini Java Nesnesine Çevirir

Giriş
Şu satırı dahil ederiz.
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
Açıklaması şöyle. Yani @ModelAttribute 
1. Metodun üzerinde veya
2. Metodun parametresi seviyesinde kullanılabilir.
The @ModelAttribute annotation can be used at method and at argument level. At method level, it can be used to configure model attributes before any @RequestMapping method is used. At argument level, it can be used to filter specific properties from a form
1. Method Seviyesinde
Açıklaması şöyle. Burada dikkatli olmak lazım çünkü metodumuz bir çok kez çağrılacaktır
Methods annotated with @ModelAttribute are invoked PRIOR TO every @RequestMapping method that is invoked in the same controller class. This is generally used for populating read-only components for a form – eg the values for a select list.
Açıklaması şöyle
When applied to a method, the method's return value is automatically added to the model. This is useful for scenarios where you need to make sure some default attributes are always available in the model.
Örnek - Data Pre-loading
Şöyle yaparız. Burada Model nesnesine genres isimli bir attribute ekleniyor
@ModelAttribute("genres")
public List<String> populateGenres() {
    return Arrays.asList("Science Fiction", "Drama", "Mystery", "Horror");
}
Açıklaması şöyle
This annotated method ensures that a list of genres is always available in the model, which can be helpful if you have multiple views requiring this information.
Örnek - Dynamic Data Initialization
Şöyle yaparız. Burada Model nesnesine feature isimli bir attribute koşul tutarsa ekleniyor
@ModelAttribute
public void loadDynamicData(@RequestParam("type") String type, Model model) {
  if ("premium".equals(type)) {
    model.addAttribute("features", getPremiumFeatures());
  }
}
2. Metod Parametresi Seviyesinde - Form İçindeki Belirli Bir Nesneyi Java Nesnesine Çevirir
Örnek - Binding
Şöyle yaparız. Post isteği ile gönderilen Form içindeki nesneyi Java nesnesine çeviriyor
@RequestMapping("/new-item")
public String newVideo(@ModelAttribute Item newItem) {
  // process the new item
  return "redirect:/";
}
Açıklaması şöyle.. 
This uses the same @PostMapping annotation. But the input argument is instead marked up with Spring MVC’s @ModelAttribute annotation. This is designed to handle forms bounds to Java objects.

This method also shows that after processing the new Item, it will then issue a redirect back to the home page using “redirect:/”.
Örnek - Binding
Açıklaması şöyle.. Post isteği ile gönderilen Form içindeki nesneyi Java nesnesine çeviriyor
When used as a method argument, it indicates the argument should be retrieved from the model. When not present, it should be first instantiated and then added to the model and once present in the model, the arguments fields should be populated from all request parameters that have matching names.
In the code snippet that follows the employee model attribute is populated with data from a form submitted to the addEmployee endpoint. Spring MVC does this behind the scenes before invoking the submit method:
Şöyle yaparız
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String submit(@ModelAttribute("employee") Employee employee) {
  // Code that uses the employee object

  return "employeeView";
}
Örnek - Binding Nested Properties
Elimizde şöyle bir kod olsun. Spring Book formda person.street gibi bir değerini çözümleyebiliyor
public class Person {
  private String name;
  private Address address;
  // Getters and setters
}

public class Address {
  private String street;
  private String city;
  // Getters and setters
}
Form şöyle
<form action="/addPerson" method="post">
  <input type="text" name="name" placeholder="Name">
  <input type="text" name="address.street" placeholder="Street">
  <input type="text" name="address.city" placeholder="City">
  <button type="submit">Add</button>
</form>

Örnek - Binding + addAttribute
Şöyle yaparız. Burada Student nesnesi Model nesnesine student attribute olarak ekleniyor
@Controller
public class StudentController {
  @PostMapping("/registerStudent")
  public String register(@ModelAttribute Student student, Model model) {
    // Business logic for student registration
    model.addAttribute("student", student);
    return "registrationSuccess";
  }
}
Form şöyle
<form action="/registerStudent" method="post">
  <input type="text" name="name" placeholder="Name">
  <input type="number" name="age" placeholder="Age">
  <input type="email" name="email" placeholder="Email">
  <button type="submit">Register</button>
</form>

Örnek - @Valid
Gerekiyorsa @Valid ve @BindingResult ile beraber kullanılır. Şöyle yaparız.
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addEmployee(@Valid @ModelAttribute("userFrom")User user,
  BindingResult result) {
  if(result.hasErrors()){
    return "User";
  }

  return "success";
}

Hiç yorum yok:

Yorum Gönder