Spring in Action 5th edition Chapter 1 & 2

3 篇文章 0 订阅

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");)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值