24 Şubat 2019 Pazar

SpringMVC @ResponseStatus Anotasyonu

Metod İle Kullanım
Açıklaması şöyle.
@ResponseStatus isn't very flexible. It marks the entire method so you have to be sure that your handler method will always behave the same way. And you still can't set the headers. You'd need the HttpServletResponse or a HttpHeaders parameter.
Örnek - OK
Şöyle yaparız.
@RequestMapping(value = "/patchdetails", method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.OK)
public String patchDetail() {
  return "patchDetails";
}
Örnek - Created
Şöyle yaparız.
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.CREATED)
public void registerUser(RequestParam(required = true)) {...}
Exception Sınıfı İle Kullanım
Bu anotasyon daha çok exception'lar ile kullanmak için uygun.
reason Alanı
Şöyle yaparız.
@ResponseStatus(value = HttpStatus.UNAUTHORIZED, reason = "Invalid authorization")
public class AuthorizationException extends RuntimeException {}
value Alanı
Örnek
Elimizde şöyle bir kod olsun.
@ResponseStatus(HttpStatus.NOT_FOUND)
public class UserNotFoundException extends RuntimeException {
  public UserNotFoundException(String message) {
    super(message);
  }
}
Şöyle yaparız.
@Service
public class UserServiceImpl implements UserService {

  @Autowired
  private UserDAO userDAO;

  @Override
  public User getById(Long id) {
    return userDAO.findById(id)
      .orElseThrow(() -> new UserNotFoundException("No user with id = " + id));
  }
}
Örnek
Şöyle yaparız.
@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException {

  private final int errorId;

  public NotFoundException(String errorMsg) {
    super("-1," + errorMsg);
    this.errorId = -1;
  }

  public NotFoundException(int errorId, String errorMsg) {
    super(errorId + "," + errorMsg);
    this.errorId = errorId;
  }

  public int getErrorId() {
    return errorId;
  }
}

Hiç yorum yok:

Yorum Gönder