Here is my angular js call
var req = {
method: 'POST',
url: newMessageUrl+"/plain",
headers: {
'Content-Type': "text/plain"
},
data: {'title':'aaaaa'}//$scope.pubmFormModel
};
$http(req).then(function(d){
msgSuccess();
}, function(e){
});
Here is my request
Request Header
Accept:application/json, text/plain, */*
Content-Type:text/plain
Origin:file://
Request Pauload
title: "aaaaa"
Here is my spring handler:
@RequestMapping(method = RequestMethod.POST, value = "/newmessage/plain")
public ResponseEntity<?> publishMessage(HttpServletRequest request) throws Exception
{
Here if i do request.getParameter("title")
its null
data: {'title':'aaaaa'}
means: transform this JavaScript object into JSON, and send the result as the body of the request.
To access it on the server, you thus need to read the request body, parse the JSON to a Map or a Java object, and extract the title attribute of the object.
To be able to get the title as a request parameter, you need to use the application/x-www-form-urlencoded
content type, and send the string 'title=aaaaa'
as body of the request.
If you want to get it as a request parameter you need to pass it as a request parameter not request body.
var req = {
method: 'POST',
url: newMessageUrl+"/plain?title=aaaa",
headers: {
'Content-Type': "text/plain"
},
data: {}
};
$http(req).then(function(d){
msgSuccess();
}, function(e){
});
Better way is to send it as a request body if there are more attributes. There are more reasons to use the requestBody for example, JSR validation etc.
Your original JS code remains the same:
var req = {
method: 'POST',
url: newMessageUrl+"/plain",
headers: {
'Content-Type': "text/plain"
},
data: {'title':'aaaaa'}//$scope.pubmFormModel
};
$http(req).then(function(d){
msgSuccess();
}, function(e){
});
But your Controller code should be modified:
@RequestMapping(method = RequestMethod.POST, value = "/newmessage/plain")
public ResponseEntity<?> publishMessage(@RequestBody User user) {
log.info("title - "+user.getTitle())
}
public class User implements Serializable{
private String title;
//getter & setters
}
If you are using Jquery, you have to apply a transformer into your request to be interpreted by Spring Handler.
for example:
var transformer = function (data) {
if (data === undefined) {
return data;
}
return $.param(data);
};
and use in your requests:
var req = {
method: 'POST',
url: newMessageUrl+"/plain?title=aaaa",
headers: {
'Content-Type': "text/plain"
},
data: {},
transformRequest: transformer
};
$http(req).then(function(d){
//Did Something good
}, function(e){
//Did something bad
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.