I develop a web app with Spark famework. On one of the sites I want to enable dynamic content loading. What I mean by that is that in Java controller I search for some info in the server and I want to update the website when search finishes, e.g.:
// this is called by get("/module", (req, resp)-> ...);
public static ModelAndView getModules(Request req, Response res) {
Map<String, Object> model = new HashMap<String, Object>();
List<Module> modules = new ArrayList<>();
model.put("modules", modules);
lookForModules(this);
return new ModelAndView(model, "pathToSiteSource");
}
private lookForModules(Listener listener){
// modules search in the background thread
// when any module is found I inform the listener;
// different modules can be found in various times
}
public void onModulesFound(List<Module> modules){
// I want to update the site using the modules that I got
}
I read that WebSockets are a way to go, but examples with WebSockets on Spark website uses AJAX calls, and my search has to be done in my java class. Are WebSockets the correct way to do this anyway?
I managed to solve my problem in some way.
Tha Java code is as above, plus in onModuleFound
method I update a static list of modules that I store in my controller class (not as a variable in getModules
method).
Then in the site code I added AJAX call that updates this specific div
every three seconds. That causes calling getModules
, and setting the most recent modules list into my site's model.
Not sure if this is the best solution, but it works pretty OK for me.