Spring in Action 5th edition Chapter 1 & 2

Chapter I & II

  • How to write a controller
  • How to write a template
  • How to add attributes to Model object
  • How to perform validation
  • How to write a “controller” which does simple things

How to write a controller

@Controller
@RequestMapping("/path")
public class MyCOntroller {
  
  @GetRequest
  public String getMapping(Model model) {
    model.addAttribute("...", ...); //How to add attributes to Model object
    ...
    return "templateName";
  }
  
  @PostRequest
  public String getMapping(@Valid @ModelAttribute('attrName') MyClass onject, Errors errors) {
    if (errors.hasErrors()) { // Perform validation
      //do something for the error
    }
    //do something (business logic)
    return "templateName";
  }
}

How to write a template

Example.

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Post Course</title>
</head>
<body>
    <form method="post" th:object="${course}">
        <h3>Enter course name: </h3>
        <input type="text" th:field="*{name}"/>
      
        <!--perform validation-->
        <span th:if="${#fields.hasErrors('name')}"
              th:errors="*{name}">Name Error</span>
      
        <h3>Enter lecture sections</h3>
        <textarea th:field="*{lecs}"></textarea>
        <h3>Enter tutorial sections</h3>
        <textarea th:field="*{tuts}"></textarea>
        <h3>Enter lab sections</h3>
        <textarea th:field="*{labs}"></textarea>
        <button>Submit your course</button>
    </form>
</body>
</html>

Key points

<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">

How to perform validation

Combine with the previous code, in model class add annotations:

@Data //@Data is lombok annotation which auto generates constructor, getters, and setters for the fields.
public class MyClass {
  @Size(min=3, message="error message") // there are other constrains, such as @Pattern...
  private String someInfo;
  ...
}

How to write a “controller” which does simple things.

@Configuration
public class WebConfig implements WebMvcConfigurer {
  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
 		registry.addViewController("/path").setViewName("viewName");
  }
}

Other

@Slf4j: is in lombok which provides a logger. (Simply log.info("info");)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章