Spring第一章开发web应用

  1. mvnw和mvnw.cmd : 这是maven包装器脚本 借助这些脚本即使没有maven也能构建项目

  1. Spring Boot DevTools 热部署:

再 src/main下面的文件变更后不需要重启

但在添加和移除依赖的时候需要重启

操作方式:只需要在pom.xml文件中添加下面依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>
  1. Spring MVC中所有请求映射的注解

@RequestMappong

通过的请求处理

@GetMapping

处理HTTP GET请求

@PostMapping

处理HTTP POST请求

@PutMapping

处理HTTP PUT请求

@DeleteMapping

处理HTTP delete请求

通常我们在类级别上使用RequstMapping 以便于指定基本路径 而在类中的每个处理器方法上 勇更具体的@getMapping @PostMapping等注解

  1. Thymeleaf模板 就是增加一些额外元素属性的html

pom.xml

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  1. 在表单绑定的时候指定校验

@Data
public class Taco {
  @NotNull    //name属性不为空 且长度至少要有五个字符
  @Size(min=5, message="Name must be at least 5 characters long")
  // tag::allButValidation[]
  private String name;
  // end::allButValidation[]
  @Size(min=1, message="You must choose at least 1 ingredient")
  // tag::allButValidation[]
  private List<String> ingredients;
}
  1. 在处理表单请求的时候执行校验

其中 @Valid注解会告诉SpringMVC对提交的order对象进行校验 如果存在错误则会捕捉到Errors对象中

 @PostMapping
  public String processOrder(@Valid Order order, Errors errors) {
    if (errors.hasErrors()) {
      return "orderForm";
    }
    
    log.info("Order submitted: " + order);
    return "redirect:/";
  }
  1. 前端展示校验错误信息 thymeleaf

  <span class="validationError"
         th:if="${#fields.hasErrors('state')}"
         th:errors="*{state}">State Error</span>
  1. 使用视图控制器:和控制器类不用 只将请求转发到视图不做其他事情的控制器 实现WebMvcConfigurer接口 并重写其中的addViewController方法

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("home");
  }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值