I am wondering is it possible to generate ModelAndView's output programatically and not via controller's return parameter. For example:
I have the following method that returns a compiled html:
#RequestMapping(value = "/get-list", method = RequestMethod.GET, headers = BaseController.AJAX_HEADER)
public ModelAndView getList(#RequestParam(value = "page", required = true) Integer page,
#ActiveUser User activeUser) {
ModelAndView result = null;
try {
result = new ModelAndView("administration/events-log/list");
result.addObject("events", eventsLogService.getList(page, Config.RECORDS_PER_PAGE));
}
catch (Exception e) {
log(e, activeUser.getUsername());
}
return result;
}
What I want is to create something like that:
#RequestMapping(value = "/get-list", method = RequestMethod.GET, headers = BaseController.AJAX_HEADER)
public #ResponseBody HashMap<String, Object> getList(#RequestParam(value = "page", required = true) Integer page,
#ActiveUser User activeUser) {
HashMap<String, Object> json = new HashMap<String, Object>();
try {
json.put("error", 0);
ModelAndView result = new ModelAndView("administration/events-log/list");
result.addObject("events", eventsLogService.getList(page, Config.RECORDS_PER_PAGE));
json.put("content", result);
}
catch (Exception e) {
/**/
}
return json;
}
so the JSON object that will be sended back to the client will look:
{'error': 0, 'content': compiled_html}
Any thoughts? Thank you
ModelAndView has no output. It just knows the name of the view. The rendering of the view is independent of Spring MVC.
If you simply want to send JSON that contains some HTML you can put the JSON code directly on your jsp. Change your java code like that:
result = new ModelAndView("path/to/json");
result.addObject("events", eventsLogService.getList(page, Config.RECORDS_PER_PAGE));
result.addObject("html", "administration/events-log/list");
Your JSON jsp can look like this:
<%# page contentType="application/json" %>
{
"error": "0",
"content": "<jsp:include page="${html}" />"
}
Please note that this code is just for illustration. You may have adapt it to your situation. And you have to escape the included HTML to get valid JSON.
Related
I want to get the body values from received html request body using Spring boot:
#PostMapping(value = "/v1/notification")
public ResponseEntity<String> handleNotifications(
#RequestParam(value = "uniqueid", required = false)) String uniqueidValue,
#RequestParam(value = "type", required = false)) String statusValue) {
// Get values from html body
return new ResponseEntity<>(HttpStatus.OK);
}
For example when I receive into the notification body:
some_key=some_value&sec_key=sec_value
I would like to parse the values. How I can implement this?
You can take the key value pair request with using Map and #RequestBody as below:
#PostMapping(value = "/v1/notification")
public ResponseEntity handleNotifications(#RequestBody Map<String,String> keyValuePairs) {
// here you can use keyValuePairs
// you can process some specific key like
String value = keyValuePairs.get("someSpecificKey");
return ResponseEntity.ok(value);
}
Here I attach example postman request :
Currently have a java spring application in development. It utilizes a ui along with restful apis which send/receive json via post requests.
Each api request needs to be validated with a token which will be sent with the request. This action is completed and a boolean is returned. Now the problem is when the boolean value is false(token not valid) I need to return a 401 error to the end user. Currently I am returning List which is being converted to json. How can I return some 401 error to the end user.
Example
//done
#RequestMapping(value = "/getSomething"
, method = RequestMethod.POST
, consumes = "application/json"
, produces = "application/json")
#ResponseBody
public List<Obj> getSomething(#RequestBody Input f) {
DAOImpl dAOImpl = (MapDAOImpl) appContext.getBean("DAOImpl");
Boolean res = dAOImpl.validateToken(f.session);
if(res) {
List<Obj> response = dAOImpl.getSomething(f.ID);
return response;
} else {
return new ResponseEntity<String>("test", HttpStatus.UNAUTHORIZED);
}
}
You just need to change your return type to ResponseEntity.
#RequestMapping(value = "/getSomething"
, method = RequestMethod.POST
, consumes = "application/json"
, produces = "application/json")
#ResponseBody
public ResponseEntity<?> getSomething(#RequestBody Input f) {
DAOImpl dAOImpl = (MapDAOImpl) appContext.getBean("DAOImpl");
Boolean res = dAOImpl.validateToken(f.session);
if(res) {
List<Obj> response = dAOImpl.getSomething(f.ID);
return new ResponseEntity<>(response, HttpStatus.OK);
}
return new ResponseEntity<String>("Unauthorized", HttpStatus.UNAUTHORIZED);
}
Note : I would recommend to pass proper JSON in error response so that client can parse and use if required.
FrontEnd: jsp with AngularJS
BackEnd: Spring MVC/Java
I am uploading a file using ng-flow, angularJS. Source: https://github.com/flowjs/ng-flow
File upload is successful. I need to return a json from my Spring Controller. Any clues how to go about it?
P.S. can't find where to put in .success() function, if at all that is applicable.
Spring Controller:
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String uploadFileHandler(#RequestParam("file") MultipartFile file, Model model) {
//Upload file and process
JsonObject jo = Json.createObjectBuilder().add(path, folderPath.toString())
.add(aContentsAttrib, aContents)
.add(bContentsAttrib, bContents).build();
}
app.js code:
(function() {
var app = angular.module('app', ['flow'])
.config(['flowFactoryProvider', function (flowFactoryProvider) {
flowFactoryProvider.defaults = {
target: 'upload',
permanentErrors: [404, 500, 501],
maxChunkRetries: 4,
chunkRetryInterval: 500,
simultaneousUploads: 4
};
flowFactoryProvider.on('catchAll', function (event) {
console.log('catchAll', arguments);
});
// Can be used with different implementations of Flow.js
// flowFactoryProvider.factory = fustyFlowFactory;
}]);
app.controller('PageController', function() {
//this.products = gems;
});
app.controller("TabController", function() {
this.tab = 1;
this.showOutput = false;
this.viewEvents = false;
this.isSet = function(checkTab) {
return this.tab === checkTab;
};
this.changeVal = function() {
this.viewEvents = true;
};
this.setTab = function(setTab) {
this.tab = setTab;
};
});
})();
What exactly should be returned from the spring controller? (String/#ResponseBody String etc)
How to collect that json in angular?
On your controller #ResponseBody should be added and the jo returned as String:
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public #ResponseBody String uploadFileHandler(#RequestParam("file") MultipartFile file, Model model) {
//Upload file and process
JsonObject jo = Json.createObjectBuilder().add(path, folderPath.toString())
.add(aContentsAttrib, aContents)
.add(bContentsAttrib, bContents).build();
return jo.toString();
}
In AngularJS, you should do this for being able to post files and then retrieve the data back:
$http({url: '/url',
method: 'POST',
data: $scope.myFile,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success(data){
$scope.myData = data;
});
In your Spring controller you should just return an Object containing the properties you want to transfer to your angular service. This will be automatically (or by default) be converted to JSON. #RequestBody is not needed.
This return value will be available in the success callback, something like:
$http({
method: 'POST',
url: '...',
}).success(function (data) {
//data is your JSON response
})},
If you are using Spring 3 you can do this
#RequestMapping(value = "/getDealers", value = "/upload", method = RequestMethod.POST)
#ResponseBody
public String uploadFileHandler() {
}
#ResponseBody annotation directly writes the response to the response stream. You would not need a JSP. Just send the request for the controller from the browser & the controller method will write the response to the response stream.
You can parse the response using Jquery or any json library & display in the JSP
Check this out
An alternate way, which I just found out. Will be useful to extract from existing code, without any modification. It does introduce an extra global variable, outside your main angular app, and might not be highly recommended, but still, posting this.
var json = {};
var app = angular.module('app', ['flow'])
.config(['flowFactoryProvider', function (flowFactoryProvider) {
flowFactoryProvider.defaults = {
target: 'processxls',
permanentErrors: [404, 500, 501],
maxChunkRetries: 4,
chunkRetryInterval: 500,
simultaneousUploads: 4
};
flowFactoryProvider.on('catchAll', function (event) {
console.log('catchAll', arguments);
this.jsonResponse = arguments[2]; //Note this change
//json = this.jsonResponse;
console.log(this.jsonResponse);
json = angular.fromJson(this.jsonResponse);
});
// Can be used with different implementations of Flow.js
// flowFactoryProvider.factory = fustyFlowFactory;
}]);
'json' variable now has the json response received. You can use it for further use now.
P.S. in order to check for which value of 'i' arguments[i] gives you the json, see console.
I am trying to implement REST API endpoints in y application.
#Controller
public class HerokuController {
#RequestMapping(value = "/heroku/resources/", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<JSONObject> provision(#RequestBody JSONObject body){
System.out.println("called! \n");
JSONObject response = new JSONObject();
response.put("id", 555);
response.put("message", "Provision successful!");
return new ResponseEntity<JSONObject>(response,HttpStatus.OK);
}
So I wrote this class containing a method which mapping is (heroku/ressources).
But when I try to call it, I get a 404 error because /WEB-INF/heroku/resources.jsp not found. However, I don't even want to get a view but a HTTP response.
Can anyone tell me which configuration file should we generally modify to tell Spring that this controller doesn't want to send back a view but a HTTP response?
The method is however called if I change it to this :
#RequestMapping(value = "/heroku/resources/", method = RequestMethod.POST)
public ModelAndView provision(final HttpServletRequest request){
System.out.println("called! \n");
JSONObject response = new JSONObject();
response.put("id", 555);
response.put("message", "Provision successful!");
final Map<String, Object> result = new HashMap<String, Object>();
return new ModelAndView("jsonView",result);
}
So changing the return type to "ModelAndView".
thanks.
You are missing the #ResponseBody
#RequestMapping(value = "/heroku/resources/", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody ResponseEntity<JSONObject> provision(#RequestBody JSONObject body){
System.out.println("called! \n");
JSONObject response = new JSONObject();
response.put("id", 555);
response.put("message", "Provision successful!");
return new ResponseEntity<JSONObject>(response,HttpStatus.OK);
}
I had the same problem once, for fix that you can use #RestController instead of #controller (this will send Json by default) and you can definy your method like this
#RequestMapping(value = "/heroku/resources/", method = RequestMethod.POST)
public JsonOut provision(#RequestBody JsonIn json)
I always made my object with the value that i will get from the client, and alway the definition of the output
Ex
public class JsonOut{
protected String id;
protected String message;
...set ....get
}
and you have to put in the spring xml file this two value
<mvc:annotation-driven />
<context:annotation-config/>
With this configuration you will have json always!
This will work with spring 4, i dont know if with spring 3 will work
I would like to set the produces = text/plain to produces = application/json when I encounter an error.
#RequestMapping(value = "/v0.1/content/body", method = RequestMethod.GET, produces = "text/plain")
#ResponseBody
public Object getBody(#RequestParam(value = "pageid") final List<String> pageid, #RequestParam(value = "test") final String test) {
if (!UUIDUtil.isValid(pageid)) {
Map map = new HashMap();
map.put("reason", "bad pageId");
map.put("pageId", pageId);
map.put("test", test);
return new ResponseEntity<Object>(map, HttpStatus.BAD_REQUEST);
}
return "hello";
}
The problem with this code is that it doesn't print the error as json when I send an invalid pageId. It gives me a HTTP 406 error Not acceptable, because it expects to produce text/plain but I didn't return a String.
The cleanest way to handle errors is to use #ExceptionHandler:
#ExceptionHandler(EntityNotFoundException.class) //Made up that exception
#ResponseBody
#ResponseStatus(value = HttpStatus.NOT_FOUND)
public ErrorObject handleException(Exception e) {
return new ErrorObject(e.getMessage());
}
Then assuming you've configured your resolvers properly and put the right JSON serialization library in the classpath, the instance of ErrorObject will be returned to the client as a JSON response.
Of course you can set up multiple #ExceptionHandler methods as needed.