Spring Boot中如何让HAL Explorer的POST表单显示password属性
解决Spring Data Rest中HAL Explorer POST表单不显示password字段的问题
你的核心矛盾是:既要让password字段在HAL Explorer的POST表单中可见(方便输入),又要保证它只接受写入、不被序列化返回。当前@Transient和@JsonProperty(WRITE_ONLY)的组合导致Spring Data Rest直接忽略了这个字段的元数据生成,所以表单里看不到。
以下是两种可行的解决方法:
方法一:给password字段添加@RestResource注解
保留@JsonProperty(WRITE_ONLY)确保返回时不序列化,同时用@RestResource(exported = true)强制Spring Data Rest将这个字段纳入HAL的元数据中,即使它是@Transient的:
@NotBlank(message = "Password is mandatory") @Pattern(regexp = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$", message = "Password must be at least 8 characters long and contain at least one lowercase letter, one uppercase letter, one digit, and one special character") @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) @Transient @RestResource(exported = true) // 添加这一行 private String password;
方法二:自定义RepositoryRestConfigurer全局配置
如果不想修改实体类,可以通过配置类手动指定要暴露的字段:
@Configuration public class RestConfig implements RepositoryRestConfigurer { @Override public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) { // 针对Organization实体,仅在创建资源时暴露password字段 config.getExposureConfiguration() .forDomainType(Organization.class) .withCreationExposure((metadata, props) -> props.add("password")); } }
这个配置的作用是:只在创建资源(POST请求)的表单中暴露password字段,查询(GET)时依然不会返回该字段。
验证效果
修改后重启服务,打开HAL Explorer的Organization POST表单,就能看到password字段的输入框,提交请求时字段会被正确接收,而GET请求返回的资源中不会包含password属性,同时原有的验证规则依然生效。
内容的提问来源于stack exchange,提问作者Sérgio Serra
相关产品推荐
相关产品推荐

