AngularJS + Spring3.2 415不支持的媒体类型错误

时间:2014-05-05 12:36:23

标签: angularjs spring-mvc

我正在使用AngualrJS和Spring MVC3.2。我试图将下面显示的简单对象发布到服务器,但我得到'415 Unspported Media Type error'。

@Entity
@Table(name="Question")
public class Question implements Serializable  {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id = 0;
    private String statement;
    private int frequency;
    private int difficulty;
    private String comment;
    private String reference;
    @Temporal(TemporalType.TIMESTAMP)
    protected Date regTime;
    @Temporal(TemporalType.TIMESTAMP)
    protected Date updTime;

    @OneToMany(mappedBy="question", fetch=FetchType.EAGER)
    @NotFound(action=NotFoundAction.IGNORE)
    private List<Answer> answers = new ArrayList<Answer>();

        //Getters and setters
}


@Entity
@Table(name="Answer")
public class Answer implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id = 0;
    private String answer;
    @Column(name="correct", columnDefinition="INT(1)")
    private boolean correct;

    @ManyToOne
    @JoinColumn(name="questionId", referencedColumnName="id")
    @NotFound(action=NotFoundAction.IGNORE)
    @JsonIgnore
    private Question question;

       //Getters and setters
}


@Controller
@RequestMapping("/question")
public class QuestionController {

  @RequestMapping(method=RequestMethod.POST)
    public @ResponseBody HttpResult submit(@RequestBody Question question) {

        HttpResult result = new HttpResult();

        //Do something here

        return result;
    }


}

services.js

$scope.submit = function(entity){
            $scope.formshow = false;
            var obj = angular.copy(entity);
            Question.save(obj, function(data){
                if (data.ok == true){
                    Question.add('success', 'Data has been saved successfully.');
                    $scope.loadData();
                } else {
                    Question.add('danger', data.msg);
                }
            });
        };

JSP页面中的JSON

{
    "id":0,
    "answers":[
        {
            "id":0,
            "answer":"a",
            "correct":false
        },
        {
            "id":0,
            "answer":"b",
            "correct":true
        },
        {}
    ],
    "statement":"test question",
    "frequency":0,
    "difficulty":0,
    "comment":"comment",
    "reference":"ref"
}

萤火虫中的Http标题

Response Headers
Content-Length  1048
Content-Type    text/html;charset=utf-8
Date    Mon, 05 May 2014 12:29:56 GMT
Server  Apache-Coyote/1.1
Request Headers
Accept  application/json, text/plain, */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5

我知道415错误意味着http标头内容类型错误或请求数据格式无效。 我试图强制更改http标头类型,但我无法更改它。我该如何解决? 您的回答将不胜感激。

1 个答案:

答案 0 :(得分:1)

确实默认的Content-Type是application / json,但是你发送的是text / html。我知道,到目前为止,你没什么新鲜的。

从版本1.1.1开始(如果我没记错的话),您可以在$ resource定义中强制执行内容类型。

您可以尝试像这样定义您的$资源:

    var Question = $resource('your/resource/url',{your params if any, otherwise send this as an empty object},{
       post: {
           method:'POST',
           isArray: false,
           headers: {'Content-Type': 'application/json;charset=UTF-8'}
       }
} )

然后,使用Question.post(...)而不是Question.save()。我已经创建了post方法,所以你不会丢失save()默认行为......但是你可以像我配置post方法一样配置save方法。

P.S。:此代码未经测试。