从api返回success作为true或false om spring rest api

xlpyo6sf  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(664)

我对springboot还很陌生。如何配置springbootapi以从登录或注册端点返回下面的json响应?。我怎样才能得到真正成功的回应?例如,如果在代码处理过程中出现代码异常,如何将false作为success json响应返回?

{
  'message': "user created successfully",
  'success' : true or false depending on the state of the request
}

到目前为止我所拥有的: My login API ```
@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {

    if (!userRepository.existsByUsername(loginRequest.getUsername()) {
        return ResponseEntity
                .badRequest()
                .body(new MessageResponse("Invalid Login credentials!"));
    }else{
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));

        SecurityContextHolder.getContext().setAuthentication(authentication);
        String jwt = jwtUtils.generateJwtToken(authentication);

        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        List<String> roles = userDetails.getAuthorities().stream()
                .map(item -> item.getAuthority())
                .collect(Collectors.toList());

        return ResponseEntity.ok(new JwtResponse(jwt,
                userDetails.getId(),
                userDetails.getUsername(),
                userDetails.getEmail(),
                roles));  
    }

}

``` My Signup API :

@PostMapping("/signup")
    public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) {

        if (userRepository.existsByUsername(signUpRequest.getUsername())) {
            return ResponseEntity
                    .badRequest()
                    .body(new MessageResponse("Email is already in use!"));
        }

        if (userRepository.existsByEmail(signUpRequest.getEmail())) {
            return ResponseEntity
                    .badRequest()
                    .body(new MessageResponse("Email is already in use!"));
        }

        // Create new user's account
        User user = new User(signUpRequest.getUsername(), signUpRequest.getEmail(),
                             encoder.encode(signUpRequest.getPassword()),signUpRequest.getFirstname(),
                signUpRequest.getSurname(),signUpRequest.getTelephoneno(),
                signUpRequest.getWhatsappno());

        Set<String> strRoles = signUpRequest.getRole();
        Set<Role> roles = new HashSet<>();

        if (strRoles == null) {
            Role userRole = roleRepository.findByName(ERole.ROLE_USER)
                    .orElseThrow(() -> new RuntimeException("Role is not found."));
            roles.add(userRole);
        } else {
            strRoles.forEach(role -> {
                switch (role) {
                case "admin":
                    Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
                            .orElseThrow(() -> new RuntimeException("Role is not found."));
                    roles.add(adminRole);

                    break;
                case "mod":
                    Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
                            .orElseThrow(() -> new RuntimeException("Role is not found."));
                    roles.add(modRole);

                    break;
                default:
                    Role userRole = roleRepository.findByName(ERole.ROLE_USER)
                            .orElseThrow(() -> new RuntimeException("Role is not found."));
                    roles.add(userRole);
                }
            });
        }

        user.setRoles(roles);
        userRepository.save(user);

        return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
        //return ResponseEntity.ok(jwt);
    }
}

消息响应类

public class MessageResponse {
    private String message;

    public MessageResponse(String message) {
        this.message = message;
      }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}
oo7oh9g9

oo7oh9g91#

您没有发布messageresponse的代码,因此如果它是您的类,您可以向它添加布尔字段,responseentity Package 器可以 Package 这个有2个字段的对象。另一个选择是使用@responsebody注解而不是responseentity。请在这里阅读更多

相关问题