题记部分
一、Web 入门
SpringBoot将传统Web开发的mvc、json、tomcat等框架整合,提供了spring-boot-starter-web组件,简化了Web应用配置。创建SpringBoot项目勾选SpringWeb选项后,会自动将spring-boot-starter-web组件加入到项目中。spring-boot-starter-web启动器主要包括web、webmvc、json、tomcat等基础依赖组件,作用是提供Web开发场景所需的所有底层依赖。webmvc为Web开发的基础框架,json为JSON数据解析组件,tomcat为自带的容器依赖。
<!-- 指定父级项目,子项目的依赖包可以使用父级项目的依赖包版本 -->
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.5.4</version>
</parent>
<properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!-- WEB依赖: Tomcat,dispatcherServlet.xml -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
二、控制器
SpringBoot 提供了@Controller
和@RestController
两种注解来标识此类负责接收和处理HTTP请求。如果请求的是页面和数据,使用@Controller
注解即可;如果只是请求数据,则可以使用@RestController
注解。
三、@Controller的用法
(1)返回hello页面和name的数据,在前端页面可以通过${name}
参数获取后台返回的数据并显示。
(2)@Controller
通常与Thymeleaf模板引擎结合使用。
package com.harley.controller;import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;@Controller
public class HelloController {@RequestMapping("/hello")public String index(ModelMap map){map.addAttribute("name","Harley");return "hello";}}
四、@RestController
的用法
默认情况下,@RestController注解会将返回的对象数据转换为JSON格式。
package com.harley.controller;import com.harley.entity.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class HelloController {@RequestMapping("/hello")public User getUser(){User user = new User();user.setUsername("Harley");user.setPassword("!QAZ2wsx");return user;}
}
五、路由映射
@RequestMapping
注解主要负责URL的路由映射。它可以添加在Controller类或者具体的方法上。如果添加在Controller上,则这个Controller中所有路由映射都将会加上此映射规则,如果添加在方法上,则只对当前方法生效。
@RequestMapping
注解包含很多属性参数来定义HTTP的请求映射规则。常用的属性参数如下:
(1)value:请求的URL路径,支持URL
(2)method:HTTP请求方法
(3)consumes:请求的媒体类型(Content-Type),如application/json
(4)produces:响应的媒体类型
(5)params,headers:请求的参数及请求头的值
@RequestMapping
的value属性用于匹配URL映射,value支持简单表达式。@RequestMapping
支持使用通配符匹配URL,用于统一映射某些URL规则类的请求:@RequestMapping("/getJson/*.json")
,当在浏览器中请求/getJson/a.json或者/getJson/b.json时都会匹配到后台的Json方法。@RequestMapping
的通配符匹配非常简单实用,支持"*" "?" "**"等通配符。符号"*"匹配任意字符,符号"**"匹配任意路径,符号"?"匹配单个字符。有通配符的优先级低于没有通配符的,比如/user/add.json比/user/*.json优先匹配。有"**"通配符的优先级低于有"*"通配符的。
— 业精于勤荒于嬉,行成于思毁于随 —