传智播客Java教程答案,Java中高级核心知识全面解析(2)_传智播客javaee高级技术理论知识考查

  • PUT :更新服务器上的资源(客户端提供更新后的整个资源)。举个例子: PUT /users/12 (更新编号为 12 的学生)
  • DELETE :从服务器删除特定的资源。举个例子: DELETE /users/12 (删除编号为 12 的学生)
  • PATCH :更新服务器上的资源(客户端提供更改的属性,可以看做作是部分更新),使用的比较少,这里就不举例子了。

1.GET 请求

@GetMapping("users")等价于@RequestMapping(value="/users",method=RequestMethod.GET)

@GetMapping("/users") 
public ResponseEntity<List<User>> getAllUsers() { 
	return userRepository.findAll(); 
}

2.POST 请求

@PostMapping("users") 等价于@RequestMapping(value="/users",method=RequestMethod.POST)

关于 @RequestBody 注解的使用,在下面的“前后端传值”这块会讲到。

@PostMapping("/users") 
public ResponseEntity<User> createUser(@Valid @RequestBody UserCreateRequest userCreateRequest) { 
	return userRespository.save(user); 
}

3.PUT 请求

@PutMapping("/users/{userId}") 等价于@RequestMapping(value="/users/{userId}",method=RequestMethod.PUT)

@PutMapping("/users/{userId}") 
public ResponseEntity<User> updateUser(@PathVariable(value = "userId") Long userId, 
	@Valid @RequestBody UserUpdateRequest userUpdateRequest) { 
		...... 
}

4.DELETE 请求

@DeleteMapping("/users/{userId}") 等价于@RequestMapping(value="/users/{userId}",method=RequestMethod.DELETE)

@DeleteMapping("/users/{userId}") 
public ResponseEntity deleteUser(@PathVariable(value = "userId") Long userId){ 
	...... 
}

5.PATCH 请求

一般实际项目中,我们都是 PUT 不够用了之后才用 PATCH 请求去更新数据。

@PatchMapping("/profile") 
public ResponseEntity updateStudent(@RequestBody StudentUpdateRequest studentUpdateRequest) { 
	studentRepository.updateDetail(studentUpdateRequest); 
	return ResponseEntity.ok().build(); 
}

四、前后端传值

掌握前后端传值的正确姿势,是你开始 CRUD 的第一步!

1.@PathVariable 和 @RequestParam

@PathVariable 用于获取路径参数, @RequestParam 用于获取查询参数。

举个简单的例子:

@GetMapping("/klasses/{klassId}/teachers") 
public List<Teacher> getKlassRelatedTeachers( 
	@PathVariable("klassId") Long klassId, 
	@RequestParam(value = "type", required = false) String type ) { 
... 
}

如果我们请求的 url 是:/klasses/{123456}/teachers?type=web

那么我们服务获取到的数据就是:klassId=123456,type=web

2.@RequestBody

用于读取 Request 请求(可能是 POST,PUT,DELETE,GET 请求)的 body 部分并且Content-Type 为 application/json 格式的数据,接收到数据之后会自动将数据绑定到 Java 对象上去。系统会使用 HttpMessageConverter 或者自定义的 HttpMessageConverter 将请求的 body 中的 json 字符串转换为 java 对象。

我用一个简单的例子来给演示一下基本使用!

我们有一个注册的接口:

@PostMapping("/sign-up") 
public ResponseEntity signUp(@RequestBody @Valid UserRegisterRequest userRegisterRequest) { 
	userService.save(userRegisterRequest); 
	return ResponseEntity.ok().build(); 
}

UserRegisterRequest 对象:

@Data 
@AllArgsConstructor 
@NoArgsConstructor 
public class UserRegisterRequest { 
	@NotBlank 
	private String userName; 
	@NotBlank 
	private String password; 
	@FullName 
	@NotBlank 
	private String fullName; 
}

我们发送 post 请求到这个接口,并且 body 携带 JSON 数据:

{"userName":"coder","fullName":"shuangkou","password":"123456"}

这样我们的后端就可以直接把 json 格式的数据映射到我们的 UserRegisterRequest 类上。
image
需要注意的是:一个请求方法只可以有一个 @RequestBody ,但是可以有多个 @RequestParam@PathVariable 。 如果你的方法必须要用两个 @RequestBody 来接受数据的话,大概率是你的数据库设计或者系统设计出问题了!

五、读取配置信息

很多时候我们需要将一些常用的配置信息比如阿里云 oss、发送短信、微信认证的相关配置信息等等放到配置文件中。

下面我们来看一下 Spring 为我们提供了哪些方式帮助我们从配置文件中读取这些配置信息。

我们的数据源 application.yml 内容如下:

wuhan2020: 2020年初武汉爆发了新型冠状病毒,疫情严重,但是,我相信一切都会过去!武汉加油!中国 加油! 

my-profile: 
	name: Java小菜 
	email: 2046136117@qq.com 
	
library: 
	location: 湖北武汉加油中国加油 
	books: 
		- name: 天才基本法 
		description: 二十二岁的林朝夕在父亲确诊阿尔茨海默病这天,得知自己暗恋多年的校园男神裴之 即将出国深造的消息——对方考取的学校,恰是父亲当年为她放弃的那所。 
		- name: 时间的秩序
		description: 为什么我们记得过去,而非未来?时间“流逝”意味着什么?是我们存在于时间之 内,还是时间存在于我们之中?卡洛·罗韦利用诗意的文字,邀请我们思考这一亘古难题——时间的本质。 
		- name: 了不起的我 
		description: 如何养成一个新习惯?如何让心智变得更成熟?如何拥有高质量的关系? 如何走出 人生的艰难时刻?

1.@value (常用)

使用 @Value("${property}") 读取比较简单的配置信息:

@Value("${wuhan2020}") 
String wuhan2020;

2.@ConfigurationProperties (常用)

通过 @ConfigurationProperties 读取配置信息并与 bean 绑定。

@Component 
@ConfigurationProperties(prefix = "library") 
class LibraryProperties { 
	@NotEmpty 
	private String location; 
	private List<Book> books; 
	
	@Setter 
	@Getter 
	@ToString 
	static class Book { 
		String name; 
		String description; 
	} 
	省略getter/setter 
	...... 
}

你可以像使用普通的 Spring bean 一样,将其注入到类中使用。

3.PropertySource (不常用)

@PropertySource 读取指定 properties 文件

@Component 
@PropertySource("classpath:website.properties") 

class WebSite { 
	@Value("${url}") 
	private String url; 
	
	省略getter/setter 
	...... 
}

六、参数校验

数据的校验的重要性就不用说了,即使在前端对数据进行校验的情况下,我们还是要对传入后端的数据再进行一遍校验,避免用户绕过浏览器直接通过一些 HTTP 工具直接向后端请求一些违法数据。

JSR(Java Specification Requests) 是一套 JavaBean 参数校验的标准,它定义了很多常用的校验注解,我们可以直接将这些注解加在我们 JavaBean 的属性上面,这样就可以在需要校验的时候进行校验了,非常方便!

校验的时候我们实际用的是 Hibernate Validator 框架。Hibernate Validator 是 Hibernate 团队最初的数据校验框架,Hibernate Validator 4.x 是 Bean Validation 1.0(JSR 303)的参考实现,Hibernate Validator 5.x 是 Bean Validation 1.1(JSR 349)的参考实现,目前最新版的 Hibernate Validator 6.x是 Bean Validation 2.0(JSR 380)的参考实现。

SpringBoot 项目的 spring-boot-starter-web 依赖中已经有 hibernate-validator 包,不需要引用相关依赖。如下图所示(通过 idea 插件—Maven Helper 生成):
image

需要注意的是: 所有的注解,推荐使用 JSR 注解,即 javax.validation.constraints ,而不是 org.hibernate.validator.constraints

1. 一些常用的字段验证的注解

  • @NotEmpty 被注释的字符串的不能为 null 也不能为空
  • @NotBlank 被注释的字符串非 null,并且必须包含一个非空白字符
  • @Null 被注释的元素必须为 null
  • @NotNull 被注释的元素必须不为 null
  • @AssertTrue 被注释的元素必须为 true
  • @AssertFalse 被注释的元素必须为 false
  • @Pattern(regex=,flag=) 被注释的元素必须符合指定的正则表达式
  • @Email 被注释的元素必须是 Email 格式。
  • @Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
  • @Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
  • @DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
  • @DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
  • @Size(max=, min=) 被注释的元素的大小必须在指定的范围内
  • @Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
  • @Past 被注释的元素必须是一个过去的日期
  • @Future 被注释的元素必须是一个将来的日期

2.验证请求体(RequestBody)

@Data 
@AllArgsConstructor 
@NoArgsConstructor 
public class Person { 

	@NotNull(message = "classId 不能为空") 
	private String classId; 
	
	@Size(max = 33) 
	@NotNull(message = "name 不能为空") 
	private String name; 
	
	@Pattern(regexp = "((^Man$|^Woman$|^UGM$))", message = "sex 值不在可选范围") 
	@NotNull(message = "sex 不能为空") 
	private String sex; 
	
	@Email(message = "email 格式不正确") 
	@NotNull(message = "email 不能为空") 
	private String email; 
}

我们在需要验证的参数上加上了 @Valid 注解,如果验证失败,它将抛出MethodArgumentNotValidException

@RestController 
@RequestMapping("/api") 
public class PersonController { 
	@PostMapping("/person") 
	public ResponseEntity<Person> getPerson(@RequestBody @Valid Person person) { 
		return ResponseEntity.ok().body(person); 
	} 
}

3.验证请求参数(Path Variables 和 Request Parameters)

一定一定不要忘记在类上加上 Validated 注解了,这个参数可以告诉 Spring 去校验方法参数。

@RestController 
@RequestMapping("/api") 
@Validated 
public class PersonController { 

	@GetMapping("/person/{id}") 
	public ResponseEntity<Integer> getPersonByID(@Valid @PathVariable("id") @Max(value = 5,message = "超过 id 的范围了") Integer id) { 
		return ResponseEntity.ok().body(id); 
	} 
}

七、全局处理 Controller 层异常

介绍一下我们 Spring 项目必备的全局处理 Controller 层异常。

相关注解:

  1. @ControllerAdvice :注解定义全局异常处理类
  2. @ExceptionHandler :注解声明异常处理方法

如何使用呢?拿我们在第 5 节参数校验这块来举例子。如果方法参数不对的话就会抛出 MethodArgumentNotValidException ,我们来处理这个异常。

@ControllerAdvice 
@ResponseBody 
public class GlobalExceptionHandler { 

	/\*\*
 \* 请求参数异常处理 
 \*/ 
	@ExceptionHandler(MethodArgumentNotValidException.class) 
	public ResponseEntity<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex, HttpServletRequest request) { 
		...... 
	} 
}

八、JPA 相关

1.创建表

@Entity 声明一个类对应一个数据库实体。

@Table 设置表明

@Entity 
@Table(name = "role") 
public class Role { 
	@Id 
	@GeneratedValue(strategy = GenerationType.IDENTITY) 
	private Long id; 
	private String name; 
	private String description; 
	省略getter/setter...... 
}


### 最后

金三银四到了,送上一个小福利!

![image.png](https://img-blog.csdnimg.cn/img_convert/43f32e1b9025a7218544af856b5d16bb.webp?x-oss-process=image/format,png)


![image.png](https://img-blog.csdnimg.cn/img_convert/a387e27c1c3fa679e17ca42e43309b1d.webp?x-oss-process=image/format,png)

![专题+大厂.jpg](https://img-blog.csdnimg.cn/img_convert/443a494dabc40e4fad2977cdeb75febc.webp?x-oss-process=image/format,png)

表


`@Entity` 声明一个类对应一个数据库实体。


`@Table` 设置表明



@Entity
@Table(name = “role”)
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
省略getter/setter…
}

最后

金三银四到了,送上一个小福利!

[外链图片转存中…(img-sPBLNQ9f-1714572009706)]

[外链图片转存中…(img-z9LE3S7b-1714572009708)]

[外链图片转存中…(img-OfgnnHns-1714572009708)]

本文已被CODING开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码】收录

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值