信息展示实例
创建domain
*domain层: *通常用于放置在系统中,与数据库中的表对应起来的JavaBean
@Data //lombok注解: 自动生成constructor getter/setter tostring方法 @RequiredArgsConstructor //lombok注解 public class Ingredient { private final String id; private final String name; private final Color color; public static enum Color{ RED,ORANGE,YELLOW,GREEN,CYAN,BLUE,PURPLE } }
*lombok: * 通过注解可以帮助我们在编译时自动生成constructor丶getter/setter丶toString丶I/O关闭等
//maven引入,另外开发工具需要安装lombok插件再进行配置 <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
创建controller(控制层处理请求)
方式一: 通过@Controller注解
@Slf4j //日志注解 @Controller @RequestMapping("/design") //请求路径为/design的请求会交给此类处理 public class DesignTacoController { //与@slf4j注解等价 private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(DesignTacoController.class); @GetMapping //处理/design的get请求 public String showDesignForm(Model model) { List<Ingredient> list = Arrays.asList( new Ingredient("1","RED", Ingredient.Color.RED), new Ingredient("2","YELLOW", Ingredient.Color.YELLOW), new Ingredient("3","BLUE", Ingredient.Color.BLUE) ); model.addAttribute("list",list); //添加属性 model.addAttribute("color","PINK"); return "design"; return "design"; //将数据(model对象)返回给模版design.html处理 } }
方式二: 通过实现WebMvcConfigurer接口
/** * 直接通过实现 WebMvcConfigurer 接口方式实现Controller * addViewControllers方法添加一个Controller * ViewControllerRegistry Controller注册请求路径和对应页面 */ @Configuration public class HomeConfigController implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { //注册Controller求路径和对应页面 registry.addViewController("/home").setViewName("home"); } }
注解:请求
Annotation(注解) Description(描述) @RequestMapping 通用的请求处理 @GetMapping 处理GET请求 @PostMapping 处理POST请求 @PutMapping 处理PUT请求 @DeleteMapping 处理DELETE请求 @PatchMapping 处理PATCH请求
创建view
此处采用thymeleaf
//maven依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
*创建thymeleaf模版文件: * design.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Design</title> </head> <body> <form action="" method="post"> <div th:each="item : ${list}"> <input type="radio" name="id" th:value="*{item.id}"> <span th:text="*{item.color}"></span> </div> <span th:text="${color}"></span> <div> <select name="color" id="type"> <option th:each="e : ${list}" th:value="*{e.name}" th:text="*{e.color}"></option> </select> </div> <input type="text" name="name" th:value="${color}"> <input type="submit" value="提交"> </form> </body> </html>
表单校验
先在JavaBean中声明验证规则
@Data public class Order { @NotNull @NotBlank(message = "不能为空") private String id; @Size(min = 3,message = "名称最小为三个字符") private String name; @CreditCardNumber(message = "不是有效信用卡号码") private String ccNumber; @Pattern(regexp = "(0|1(01*0)*1)*",message = "正则校验失败") private String ccExpression; @Digits(integer=3, fraction=0, message="验证整数部分为三个数字,小数部分为0个失败") private String digit; @Size(min = 1,message = "最少有一个元素") private List<Ingredient> ingredients; }
进行校验
/** * GET提交时获取页面 * POST提交时会进行校验 */ @Controller @RequestMapping("/order") public class OrderController { @GetMapping public String show(Order order){ //校验需要: order参数和post提交一致 return "order"; } /** * @Valid 表示提交时要校验order对象,具体校验规则在Order类中定义 * 使用@Valid注解在表单提交后执行processOrder方法之前进行校验 * errors对象保存校验的信息 */ @PostMapping public String get(@Valid Order order, Errors errors){ if(errors.hasErrors()){ return "order"; } return "home"; } }
显示验证错误信息(Thymeleaf方式)
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Order</title> </head> <body> <form action="/order" method="post" th:object="${order}"> <span>id #:</span> <input id="id" type="text" th:field="*{id}"/> <!--验证id字段--> <span th:if="${#fields.hasErrors('id')}" th:errors="*{id}">CC Num Error</span> <br/> <label for="name">name #: </label> <input id="name" type="text" th:field="*{name}"/> <!--验证name字段--> <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}">CC Num Error</span> <br/> <input type="submit" value="提交"/> </form> </body> </html>
模版选择
常见的模版选项
Template dependency FreeMarker spring-boot-starter-freemarker Groovy Templates spring-boot-starter-groovy-templates JavaServer Pages (JSP) None (provided by Tomcat or Jetty) Mustache spring-boot-starter-mustache Thymeleaf spring-boot-starter-thymeleaf <!-- Thymeleaf依赖配置 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- Mustache依赖配置 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mustache</artifactId> </dependency>
模版缓存
模版第一次使用时会将编译后的结果缓存起来,以此提高性能,在生产环境是很好的特性,但在开发环境下会导致无法正常刷新
关闭模版缓存: ** 在application.properties** 配置文件中配置,生产环境要重新启用
Template Cache enable property FreeMarker spring.freemarker.cache Groovy Templates spring.groovy.template.cache Mustache spring.mustache.cache Thymeleaf spring.thymeleaf.cache <!--如禁用Thymeleaf模版缓存--> spring.thymeleaf.cache=false
- 推荐: ** 使用Spring Boot’s DevTools** 禁用模版缓存,在部署时会禁用自身,因此模版缓存会重新启用