Could please anybody who has experiences with processing post xmlHttpRequests with Spring DispatcherPortlet, tell me what is the best way to do it ? I'm using YUI io module and Jackson Object Mapper as an example :
#ResourceMapping(value="stuff")
public void method(ResourceResponse response){
Person person = new Person();
person.setWeight(150);
ObjectMapper mapper = new ObjectMapper();
try{
mapper.writeValue(response.getWriter(), person);
}
...
}
Ajax:
function() {
var A = AUI();
A.io("<portlet:resourceURL id="stuff" />", {
method: 'POST',
data: {
description: 'value'
}
});
}
This is the issue where you can vote up that spring-portlet environment will have the same support that common spring-mvc has. Which is #ResponseBody, data conversion to JSON etc. Now AFAIK one has to do it manually...
EDITED: Figured out the solution
PLEASE: Take a look at this issue which is better formulated https://stackoverflow.com/questions/4782971/handling-ajax-requests-with-spring-portlet
How do you construct the URL? I think you're creating a Action URL, perhaps it should be an render URL. It means, instead of <portlet:actionURL/> you should be using <portlet:renderURL/>.
Hope it helps.
I suppose the best way to respond to ajax requests in spring portlets is described in this blog post Marshal Json data using Jackson in Spring MVC with Jaxb Annotations
This also helpful Create JSON response for AJAX request in spring 3.0
Unfortunately it is not so fancy as it would be in spring-web-mvc
Related
I have developed Small Spring boot Rest api app. I can able to get the data or create new record and search with paging and sorting.
Now i'm looking for provide input data in body to get the data instead of providing in URL with GET method. Is this method also default function ? Please advise.
public interface CodeTextRepository extends PagingAndSortingRepository<CodeText, Long> {
}
How to write POST method to just get the data ?
http://localhost:8080/api/code
method : POST
{
"code":1
}
If I understand you correctly, you want to create a controller that will get the a model as body parameter ({ "code": 1 }) in a POST method and then do something with it.
To do that, you can create a controller that looks like the following (I inserted pseudo-code as an example):
#RestController
#RequestMapping(value = "/api/code")
public class CodeTextController {
private CodeTextRepository codeTextRepository;
// constructor injection
public CodeTextController(CodeTextRepository codeTextRepository) {
this.codeTextRepository = codeTextRepository;
}
#PostMapping
public CodeText postCodeText(#RequestBody CodeTextRequest codeTextRequest) {
// some code to get from the DB
return codeText;
}
}
public class CodeTextRequest {
private int code;
// getters and setters
}
Simply add Accept header to the request, like
accept: application/json
Spring Data-Rest will return the body after a POST request if either the returnBodyOnCreate flag was explicitly set to true in the RepositoryRestConfiguration OR if the flag was NOT set AND the request has an Accept header.
You can set the flag directly during configuration, or you can set it via the application.properties:
spring.data.rest.returnBodyOnCreate = true
you can also set it separately for update:
spring.data.rest.returnBodyOnUpdate = true
---- edit
Maybe I misunderstood your question. If you simply want to GET an existing data using POST method, then DO NOT DO IT AT ALL! That's not a REST API any more. There must be some reason you want to do it, but you should try do resolve that original problem instead in another way!
Here is the controller:
Here is the postman:
Via form-data, I can get caseId in my controller.
But raw with header, I can't.
I don't know why... Is there anything wrong with my controller ?
Please help, thanks.
edit 1:
Yeah. Add something more
We know, springMVC will bind data for us, but when we use POST request and put data in body via raw and Content-Type:application/json, spring will still bind data? request.getInputStream() will only call once.
edit 2:
I found a way to get the raw.
get the json string.
edit in 11/29/2017
I found that:
Post with raw, I need to use #RequestBody to recive the value.
Here are the example of how to retrieve data using POSTMAN and bind with SpringMVC
#RequestMapping(value = "/user/", method = RequestMethod.GET)
public ResponseEntity<List<User>> listAllUsers() {
List<User> users = userService.findAllUsers();
if (users.isEmpty()) {
return new ResponseEntity(HttpStatus.NO_CONTENT);
// You many decide to return HttpStatus.NOT_FOUND
}
return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}
You may refer to this article : Spring Boot Rest API Example
Can u bind request param as below and check :
public Object getTcaseByCaseId(#RequestParam("caseId") String caseId) {
I have a sample Angular 2 code below.
this.headers = new Headers({ 'Content-Type': 'application/json' });
this.options = new RequestOptions({ headers: this.headers });
this.http.post('/api/todo/create', JSON.stringify(todo), this.options);
I also have an API action as seen below (ASP.NET Core)
[HttpPost]
[Route("create")]
public IActionResult Create([FromBody] Todo todo)
{
return this.Ok();
}
This code works but I am not comfortable in seeing the [FromBody] attribute in the parameter. I know that for Post requests, MVC reads it from the body. But, I have been using Restangular in AngularJS before and the parameter object is sent to an API without the [FromBody] attribute.
Is there a way to just pass the object to the API action without using the [FromBody] attribute or reading the content of the request and then deserializing it to an object?
I think using the payload of a POST method is what you should do to send data to the server. You can choose the content type you want (JSON, url encoded form, ...).
That said, the Angular2 HTTP support is low-level. I mean there is no high-level API for REST. You need to set headers by your own, choose the HTTP method you want to use... I won't find something like Restangular in Angular2.
This link could help you:
https://www.quora.com/What-are-some-of-the-best-practices-for-designing-a-RESTful-API
I'm trying to serialize a knockout object and pass it into a JSON property called multipleCharge.
This is the ajax code to send data though Get method to a mvc controller
$.ajax({
url: _url,
type: 'GET',
//data: { multipleCharge: ko.mapping.toJS(_vm)},
data: { multipleCharge : { AccountId : 2 } },
dataType: 'json'});
And this is the method
[HttpGet]
public HttpResponseMessage GetSalesInvoiceMultipleCharge
([FromUri]MultipleChargeDto multipleCharge)
{
...
}
Please, note that the ajax method has a comment line. Using the hardcoded line, it works, multipleCharge object is not null, but if I uncomment the another line, it's a bad request in my browser.
Look at this.
Any idea about what's happening. Using the Chrome console, it looks ok; so I can't identify the error.
It is may be IIS problems with very long URL.
See this Issue with URL length in IIS7 (Windows Server 2008) question and related answers.
Also see this http://www.iis.net/configreference/system.webserver/security/requestfiltering documentation.
You could try to solve this problem by editing web.config. But also you could use POST method instead of GET and send your data in request body.
In my last SO question, I asked how to modify the serializer settings for Json.NET, which ASP.NET Web API natively uses for (de)serialization. The accepted answer worked perfectly, and I was, for example, able to embed type information into the serialized JSON string.
However, when I try to throw back this JSON string to a Web API action that's expecting the model's parent class, Web API still deserializes to the parent class, removes all data corresponding to the child class, and prevents casting to and detection of the child class.
class Entity { }
class Person : Entity { }
public Person Get() {
return new Person();
}
public bool Post(Entity entity) {
return entity is Person;
}
A simple use case would be doing something like this in jQuery:
// get a serialized JSON Person
$.ajax({
url : 'api/person' // PersonController
}).success(function (m) {
// then throw that Person right back via HTTP POST
$.ajax({
url : 'api/person',
type : 'POST',
data : m
}).success(function (m) {
console.log(m); // false
});
})
I'd expect that by modifying the JsonSerializerSettings of Json.NET to embed type information that it'd be able to read that and at the very least, try to force deserialization to that type, but apparently it does not.
How should I tackle something like this?
Web API really doesn't do any (de)serialization "natively". It happens to have a few MediaTypeFormatters included in the config.Formatters collection by default. Feel free to remove those and create your own MediaTypeFormatter that handles the serialization the way you want it to be done.
MediaTypeFormatters are really not that hard to create.
Actually the 2nd POST call is sending application/x-www-form-urlencoded data and that's why the type information is not picking up by the JsonMediaTypeFormatter. Try setting the contentType to be "application/json".
Also, the data in the 2nd POST request body seems to be encoded and it needs to be decoded before sending back to the service.
I was able to get this to work:
// get a serialized JSON Person
$.ajax({
url: 'api/person' // PersonController
}).success(function (m) {
// then throw that Person right back via HTTP POST
$.ajax({
url: 'api/person',
type: 'POST',
contentType: "application/json",
data: JSON.stringify(m),
}).success(function (m) {
alert(m); // true!
});
})