需要返回Boolean @ResponseBody。现在得到HTTP 406错误 [英] Need to return Boolean @ResponseBody. Now getting HTTP 406 error

查看:852
本文介绍了需要返回Boolean @ResponseBody。现在得到HTTP 406错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Web应用程序(REST,Spring,JPA Hibernate)中返回一个布尔值作为HTTP响应。这是代码:

I am trying to return a boolean as a HTTP Response in a web application (REST, Spring, JPA Hibernate). Here's the code:

@ResponseBody
@RequestMapping(value="/movieTheater", method=RequestMethod.GET)
public boolean getCustomerInput(Map<String, Double> input) {
    return transactionService.addTransaction(input);
}

现在,我想这不允许我返回一个布尔值,但期待别的。当我尝试在浏览器中访问以下内容时:

Now, I guess this is not allowing me to return a boolean, but expecting something else. When I am trying to access in the browser the following:

http://localhost:8081/SpringMVCMerchant/movieTheater.htm

我收到以下错误:

HTTP Status 406 -

type Status report

message

description The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.

您能否告诉我一种将布尔值作为回复发送的方法?如果没有,我还能做什么?
提前致谢!

Can you please tell me a way to send boolean as a response? If not, what else can I do? Thanks in advance!

推荐答案

第1步:创建枚举

public enum ResponseStatus {
    SUCCESS("true"),
    FAILED("false");
    private final String status;

    private ResponseStatus(String status) {
       this.status = status;
    }

    public String getStatus() {
       return status;
    }
}

第2步:创建一个类,用于返回响应详细信息

step 2: create a class for returning the response details

public class ResponseText {
    private String message;

    public String getMessage() {
        return message;
    }

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

第3步:修改代码如下

@ResponseBody
@RequestMapping(value="/movieTheater", method=RequestMethod.GET)
public ResponseText getCustomerInput(Map<String, Double> input) {
    ResponseText result = new ResponseText();
    if(transactionService.addTransaction(input))
        result.setMessage(ResponseStatus.SUCCESS.getStatus());
    else
        result.setMessage(ResponseStatus.FAILED.getStatus());
    return result;
}

现在你可以得到像这样的输出JSON

now you can get output JSON like this

{[
    message:"true"
]}

这篇关于需要返回Boolean @ResponseBody。现在得到HTTP 406错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆