[英]How get jwt 'user_name' inside @ExceptionHandler class ResponseEntity using WebRequest (Spring)?
[英]Registering a user using POST - how to correctly use ResponseEntity?
我正在構建REST API(不公開,僅用於我自己網站的后端),並且具有用於注冊新用戶的Controller:
// 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格式返回僅該控制器中的用戶名正確:
// DELETE YOUR ACCOUNT - deletes logged in user
@DeleteMapping("/delete")
public ResponseEntity<?> deleteUser(Principal principal) {
userService.deleteUser(principal);
return ResponseEntity.ok(principal.getName());
}
我仍然對REST控制器中返回的內容感到非常困惑-一切都必須僅僅是JSON(我知道我也可以使用XML(和其他一些XML,但選擇了JSON)+狀態代碼)嗎? 當我嘗試為該Web應用程序構建前端時,這將易於使用嗎?
只是嘗試這可以有任何幫助
// 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);
}
可選的便捷方法:
@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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.