简体   繁体   English

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

[英]AngularJS + Spring3.2 415 Unsupported Media Type error

I am using AngualrJS and Spring MVC3.2. 我正在使用AngualrJS和Spring MVC3.2。 I am trying to post simple object shown below to the server but I am getting '415 Unspported Media Type error'. 我正在尝试将下面显示的简单对象发布到服务器,但出现“ 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 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);
                }
            });
        };

JSON in the JSP page 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 header in firebug Firebug中的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

I know that 415 error means that http header content-type is wrong or request data format is invalid. 我知道415错误意味着http标头内容类型错误或请求数据格式无效。 I have tried to change http header type forcefully but I could not change it. 我试图强制更改http标头类型,但无法更改。 How do I fix this? 我该如何解决? Your answer would be appreciated. 您的回答将不胜感激。

Indeed the default Content-Type is application/json, however you're sending text/html. 确实,默认的Content-Type是application / json,但是您正在发送text / html。 Nothing new to you so far, I know. 我知道到目前为止您还没有什么新鲜事。

Since version 1.1.1 (if I'm not mistaken) you can enforce the content type at the $resource definition. 从1.1.1版开始(如果我没记错的话),您可以在$ resource定义中强制使用内容类型。

Can you try to define your $resource like this: 您可以尝试这样定义$ 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'}
       }
} )

then, instead of Question.save(), use Question.post(...). 然后,使用Question.post(...)代替Question.save()。 I have created the post method just so you don't lose the save() default behavior...but you could configure the save method exactly like I've configured the post method. 我创建了post方法只是为了您不会丢失save()默认行为...但是您可以完全像配置了post方法一样配置save方法。

PS: This code is untested. PS:此代码未经测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM