我正在使用Java和Spring MVC,在该应用程序的第一个版本中,我使用ResponseEntity<String>进行了响应,在遇到错误的地方我返回了return new ResponseEntity<String>(httpErrors.toString(), responseHeaders, HttpStatus.BAD_REQUEST);之类的内容,而当一切正确时,则返回了return new ResponseEntity<String>(loginResponse.toString(), responseHeaders, HttpStatus.OK);之类的内容。但是现在我相信,有一种更好的方法可以执行此操作,而无需使用toString()方法,根据如下情况返回特定对象:

@RestController
@RequestMapping("/user")
public class LoginController {

    /** The login service to validate the user. */
    @Autowired
    LoginService loginService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public @ResponseBody ResponseEntity<?> validate(@RequestBody final UserLog login) {

        WebUser webUser = loginService.getUserDetails(login.getLogin(), login.getPassword());
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);

        if (webUser == null) {
            HttpErrors httpErrors = new HttpErrors(ApiCommonResources.ERROR_402, "error" + "." + ApiCommonResources.ERROR_402, ApiCommonResources.ERROR_402_TEXT);
            return new ResponseEntity<HttpErrors>(httpErrors, responseHeaders, HttpStatus.BAD_REQUEST);
        }

        List<Account> userAccounts = loginService.getMerchantAccounts(webUser.getMerchantId());

        // Json Web Token builder
        token = "b7d22951486d713f92221bb987347777";

        LoginResponse loginResponse = new LoginResponse(ApiCommonResources.SUCCESS_REQUEST_CODE, token);

        return new ResponseEntity<LoginResponse>(loginResponse, responseHeaders, HttpStatus.OK);

    }

}


问题是如何创建一个可以包装LoginResponseHttpErrors对象类型的类,并将其作为ResponseEntity中的返回对象在?中发送:

LoginResponse类:

public class LoginResponse{

    public LoginResponse(Integer statusCode, String token){
        this.setStatusCode(statusCode);
        this.setToken(token);
    }

    private String token;
    private Integer statusCode;

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public Integer getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(Integer statusCode) {
        this.statusCode = statusCode;
    }

    @Override
    public String toString() {

        StringBuilder jsonResponse = new StringBuilder();

        jsonResponse.append("{");
        jsonResponse.append("\"statusCode\":");
        jsonResponse.append("\"" + statusCode + "\",");
        jsonResponse.append("\"token\":");
        jsonResponse.append("\"" + token + "\"");
        jsonResponse.append("}");

        return jsonResponse.toString();
    }

}


和HttpErrors类:

public class HttpErrors {

    public HttpErrors(){
    }

    public HttpErrors(String errorCode, String errorKey, String errorMessage) {
        super();
        this.errorCode = errorCode;
        this.errorKey = errorKey;
        this.errorMessage = errorMessage;
    }

    private String errorCode;
    private String errorKey;
    private String errorMessage;

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorKey() {
        return errorKey;
    }

    public void setErrorKey(String errorKey) {
        this.errorKey = errorKey;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    @Override
    public String toString() {

        StringBuilder jsonError = new StringBuilder();

        jsonError.append("{");
        jsonError.append("\"errorCode\":");
        jsonError.append("\"" + errorCode + "\",");
        jsonError.append("\"errorKey\":");
        jsonError.append("\"" + errorKey + "\",");
        jsonError.append("\"errorMessage\":");
        jsonError.append("\"" + errorMessage + "\"");
        jsonError.append("}");

        return jsonError.toString();
    }

}

最佳答案

public class Response<T> {

   private int httpStatus;
   private T data;

   //getter and setter consructor

    eg constructors
    public RestResponse(T data){
    this(HTTP_OK,data)
    }

    public RestResponse(int httpStatus,T data){
    this.httpStatus = httpStaus;
    this.data = data;

  }


现在,对所有响应对象都使用此模板(repsone对象也可以是POJO)

return new RestEntity<LoginResponse>(loginResponse,statusCode) //loginResponse object


LoginResponse在哪里

public class LoginResponse {
private String token;
//getter and setter and constructors.
}


您应该花一些时间来建立REST合同(使用google进行阅读:)),然后继续使用此基本逻辑。 Java和spring在一起是不可思议的。
玩得开心。

10-07 20:28