【发布时间】:2014-06-21 18:20:21
【问题描述】:
我正在使用 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"
}
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
我知道 415 错误意味着 http 标头内容类型错误或请求数据格式无效。 我曾尝试强制更改 http 标头类型,但无法更改。我该如何解决? 您的回答将不胜感激。
【问题讨论】:
-
看一下:[link][1][1]:stackoverflow.com/questions/18102452/…希望对你有帮助
-
您似乎没有将 json 发送到服务器
Content-Type text/html;charset=utf-8 -
粉丝。谢谢,我认为这是一个类似的情况,但不是我的情况。 AngularJS 标头的默认内容类型是 json,我没有触及任何内容。
-
geoand.我试图更改标题但不能。 var http = $http.post('url_to_server', arg, {headers: {'Content-Type': 'application/json'}});另外,AngularJS 默认的 Content-Type 是 'application/json' $httpProvider.defaults.headers.post
标签: angularjs spring-mvc