2017-02-02 5 views
0

私は(ちょうど私自身のサイトのバックエンドのために、パブリックない)RESTのAPIを構築していると私は、新しいユーザーを登録するためのコントローラを持っている:POSTを使用してユーザーを登録する - ResponseEntityを正しく使用する方法

// CREATE A USER 
@PostMapping("/register") 
public ResponseEntity<?> createUser(
     @RequestBody User user 
) { 
    if (userService.userExists(user)) { 
     return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("User with that username already exists."); 
    } 
    return ResponseEntity.ok(userService.saveUser(user)); 
} 

ユーザ名がすでにあるとき、私は私のResponseEntityにその文字列を好きではありません取られた - それらの事柄を処理する正しい方法は何ですか?私は私のすべてのコントローラからJSONを返すべきであることを知っていますが、そのメソッドでJSONを実装する方法はわかりません。

はまた、JSONに、このコントローラでユーザー名のみの罰金を返して:

// DELETE YOUR ACCOUNT - deletes logged in user 
@DeleteMapping("/delete") 
public ResponseEntity<?> deleteUser(Principal principal) { 
    userService.deleteUser(principal); 
    return ResponseEntity.ok(principal.getName()); 
} 

私はまだRESTコントローラに返すかについて非常に困惑している - すべてが(私は私を知っているだけJSONsする必要がありませんXMLも使用できますが、JSONを選択した状態コード+ステータスコードも使用できますか?そのwebappのフロントエンドを構築しようとすると、これは使いやすいでしょうか?

+1

DELETEやUPDATEが削除または更新された行数を返すことができ - あなたのケースでは1または0を。 – StanislavL

+0

私はEntitiesとdbで作業しています - 削除された行はどういう意味ですか?私はそれが実装上の正しい方法でどのように行われるべきなのか不思議です。 – doublemc

答えて

1

ただ、これはoptionalでそれを行うには任意の助け

// CREATE A USER 
@PostMapping("/register") 
public @ResponseBody ResponseEntity<JSONObject> createUser(@RequestBody User user) { 

    JSONObject responseJson = new JSONObject(); 

    if (userService.userExists(user)) { 

     responseJson.put("status", "User with that username already exists."); 

     return new ResponseEntity<JSONObject>(responseJson, HttpStatus.BAD_REQUEST); 
    } 

    responseJson.put("status", "User created."); 

    return new ResponseEntity<JSONObject>(responseJson, HttpStatus.OK); 
} 
0

便利なアプローチすることができ試してみてください。

@PostMapping("/register") 
    /* */ 
    Optional<User> optionalUser = userService.findUserById(userId); 
    // or userService.findUserByName(username); 
    return Optional.ofNullable(optionalUser) 
     .map(u -> { 
       return getBadRequestResponse(Sting.format("User with name : %s already exists", username)); 
      } 
     ).orElse(getSuccessfulResponse(
        new userService.addUser(user))); 

[...] 

    protected ResponseEntity getSuccessfulResponse(Object result) { 
    return new ResponseEntity(result, HttpStatus.OK); 
    } 

    protected ResponseEntity getBadRequestResponse(String message) { 
    return new ResponseEntity(new RestErrorResponse(message), HttpStatus.BAD_REQUEST); 
    } 
関連する問題