I am using the json spring view in order to return a simple JSON object from my controller.
The problem is that its returning more data then i want. it is returning the validation errors and things inside of my model when all i am doing is this in the controller:
Map model = new HashMap()
model.put("success", "true");
return new ModelAndView("jsonView", model);
If you look at the bottom of this page in the docs it looks like i am getting back data that POST would return. i am not doing a post, i am doing a GET by going directly to the URL with params.
How do i get this lib to return just the data in my model?
We have used this library and it has worked as expected. Could you try with the following variation of the above code to see if it works? We use this in some places...
ModelAndView modelAndView = new ModelAndView("jsonView");
ModelMap map = modelAndView.getModelMap();
map.addAttribute("success", "true");
return modelAndView;
Related
I'm new to REST and I'm making simple REST application with users and articles. I wonder what's the difference between two samples below:
#GetMapping("/user/{id}")
public User getUserById(PathVariable("id") String id) {
.....
return userService.getUserById();
}
and
#GetMapping("/user/{id}")
public ResponseEntity<User> getUserById(PathVariable("id") String id) {
.....
return new ResponseEntity<> ....
}
Which one is better to use?
And what's the main difference between two of them?
ResponseEntity is containing the entire HTTP response that returns as a response which gives the flexibility to add headers, change status code and do similar things to the response.
Another hand sending PJO class directly like returning users in the example is somewhat similar to return ResponseEntity.ok(user) which responded to user details successfully to the user. But the ability to change headers, status codes is not available if you return PJO directly.
It is good to use ResponseEntity over PJO when there is a scenario you need to change the headers or you need to change status according to the result.
eg: show not found when there is no data you can return ResponseEntity.status(404).body(<-body->).
at least in the Response Entity, you can set the http status and you can use ResponseEntity<?> where ? is generic any object its very convenient to use
I have looked at the various answers and they do not resolve my issue. I have a very specific client need where I cannot use the body of the request.
I have checked these posts:
Trying to use Spring Boot REST to Read JSON String from POST
Parsing JSON in Spring MVC using Jackson JSON
Pass JSON Object in Rest web method
Note: I do encode the URI.
I get various errors but illegal HTML character is one. The requirement is quite simple:
Write a REST service which accepts the following request
GET /blah/bar?object=object11&object=object2&...
object is a POJO that will come in the following JSON format
{
"foo": bar,
"alpha": {
"century": a,
}
}
Obviously I will be reading in a list of object...
My code which is extremely simplified... as below.
#RequestMapping(method=RequestMethod.GET, path = "/test")
public Greeting test(#RequestParam(value = "object", defaultValue = "World") FakePOJO aFilter) {
return new Greeting(counter.incrementAndGet(), aFilter.toString());
}
I have also tried to encapsulate it as a String and convert later which doesnt work either.
Any suggestions? This should really be extremely simple and the hello world spring rest tut should be a good dummy test framework.
---- EDIT ----
I have figured out that there is an underlying with how jackson is parsing the json. I have resolved it but will be a write up.. I will provide the exact details after Monday. Short version. To make it work for both single filter and multiple filters capture it as a string and use a json slurper
If you use #RequestParam annotation to a Map<String, String> or MultiValueMap<String, String> argument, the map will be populated with all request parameters you specified in the URL.
#GetMapping("/blah/bar")
public Greeting test(#RequestParam Map<String, String> searchParameters) {
...
}
check the documentation for a more in depth explanation.
I already search tutorial in spring for method POST, insert the data with response entity (without query) and I getting error in ajax. I want to confirm, What is format url from ajax to java? below my assumption:
localhost:8080/name-project/insert?id=1&name=bobby
is the above url is correct? because I failed with this url. the parameter is id and name.
mycontroller:
#PostMapping(value={"/insertuser"}, consumes={"application/json"})
#ResponseStatus(HttpStatus.OK)
public ResponseEntity<?> insertUser(#RequestBody UserEntity user) throws Exception {
Map result = new HashMap();
userService.insertTabelUser(user);
return new ResponseEntity<>(result, HttpStatus.CREATED);
}
my daoimpl:
#Transactional
public String insertUser(UserEntity user) {
return (String) this.sessionFactory.getCurrentSession().save(user);
}
the code running in swagger (plugin maven) but not run in postman with above url.
Thanks.
Bobby
I'm not sure, but it seems that you try to pass data via get params (id=1&name=bobby), but using POST http method implies to pass data inside body of http request (in get params, as you did, data is passed in GET method) . So you have to serialize your user data on client side and add this serialized data to request body and sent it to localhost:8080/name-project/insert.
As above answer suggest. You are trying to pass data as query parameters.but you are not reading those values in your rest API.either you need to read those query parameters in your API and then form an object or try to pass a json serialized object to your Post api as recommendation. Hope it helps.
Simply, I'm trying to parse a List of composite objects passed from Spring controller via ModelAndView object as the following
Spring part
ModelAndView view = new ModelAndView("my view");
List<ActionHistory> histories = myService.getListData();
view.addObject("histories", histories);
return view;
In Jquery i tried couple of alternatives, first used the below line to construct JSON from List:
var list = JSON.stringify('${histories}');
console.log(histories);
the console is returning
"[com.companyname.projectname.domains.ActionHistory#48126327]"
TypeError: invalid 'in' operand a
I also tried from jquery-json by including "jquery.json.min.js" as a suggestion from this topic discussed but getting the same error above Serializing to JSON in jQuery
var histories = $.toJSON('${histories}');
console.log(histories);
Check you contentType in ajax function it should be.
contentType: "application/json"
Also your Spring controller which is handling this mvc call should configure be configired with
produces=MediaType.APPLICATION_JSON_VALUE
e.g. something like
#RequestMapping(value ="/getList", method= RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
We are using Spring 2.5.x and we are doing this: Posting a form, responding to this in the controller method where we generate some data. Now, at the end we are doing a redirect to another page. We need to access the data generated in the post request handler method.
From the post handler, declared to return a ModelAndView:
Map<String, String> map = new HashMap<String, String>();
map.put("myKey", "someValue");
ModelAndView mav = new ModelAndView(new RedirectView("/my/view", true, true, false), map);
return mav;
In the get method handler we want to access these data and use them in the view for this method. How do we access these values? The modelmap that I inject to this method is empty. And only null values are shown in the view if I try to use ${myKey}
We are using Spring 2.5.x, so I can't use RequestAttributes etc.
FlashMap which you would get with RequestContextUtils. was added in Spring 3.1. As far as I know, you'll therefore need to implement your own flash attributes mechanism. You can use a servlet Filter as explained in this blog post. Or, very basically, add stuff to the HttpSession and clear them in a future request.
Save the map data in session scope before executing your redirect. Then in your page, consume the data from the map using JSTL. At the bottom of your page, remove this map from session scope using <c:remove>.
In your java class:
Map<String, String> map = new HashMap<String, String>();
map.put("myKey", "someValue");
session.addAttribute("myMap", map);
//the rest of your logic...
In your JSP/JSTL code:
Map.myKey value: ${map.myKey}
<!-- at the bottom of the JSP, remove the variable from session -->
<c:remove var="myMap" scope="session" />