开发者社区> 问答> 正文

mongodb + springboot。如何进行广泛过滤?

我的account.java是这个

import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString @Document(collection="Account") public class Account { @Id private String id; private String username; private String password; private String role; } 我的repo 是这样的

import org.springframework.data.mongodb.repository.MongoRepository; public interface AccountRepository extends MongoRepository<Account, Integer> {

} 最后。对于我的控制器(尚未完成)

@PutMapping("/createAccount") public void createAccount(@RequestBody Account account) {

} 我想要以下内容

如果我要在请求正文中发送json,例如

{ "username": "Tom", "password": "123456", "role": "Employee" } 然后,它将在Account集合中创建一个具有该属性的对象,可以轻松地通过repository.insert(account)完成此操作。但是我需要检查某些过滤器

所有三个对象都需要设置 角色必须是“雇员”,“管理员”或“客户” 最后,用户尚未在数据库中 否则发送响应400

如何使用springboot实现此目的?

展开
收起
小六码奴 2019-10-10 17:21:14 2023 0
1 条回答
写回答
取消 提交回答
  • 您可以在Controller中使用@Valid Annotation,然后可以在Model类中放置@NotNull或@NotEmpty或@NotBlank。参考:https : //www.baeldung.com/spring-boot-bean-validation public void createAccount(@Valid @RequestBodyAccount account){

    }

    public class Account {

    @Id
    @NotNull
    private String id;
    @NotNull
    private String username;
    @NotNull
    private String password;
    @NotNull
    private String role;
    

    } 您可以使用Spring Security Expressions。参考:https : //www.baeldung.com/spring-security-expressions-basic

    @PreAuthorize(“ hasRole('ROLE_ADMIN')”)

    @PutMapping(“ / createAccount”)

    public void createAccount(@RequestBodyAccount account){

    }

    2019-10-10 17:21:53
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Data as a Service - 数据即服务 -- MongoDB⾼级应⽤模式 立即下载
MongoDB多数据中心的方案选型之路 立即下载
饿了么高级架构师陈东明:MongoDB是如何逐步提高可靠性的 立即下载