How to load a JavaScript file using thymeleaf + springboot - spring

I have 2 methods that return a ModelAndView Object.
The first one gets the mapping from the browser and returns a modelandview that links to to an html file.
On that html file on the end I link a script tag to a spring root like this:
<!-- Calendar Js -->
<script type="text/javascript" src="../../../static/assets/vendor/netcorr/calendar/calendar.js"
th:src="#{/customer/web/wall/calendarItems(wallId=${wallId})}"></script>
In the controller, I have the second method that loads based on this call that I'm making just above:
/customer/web/wall/calendarItems(wallId=${wallId})
This method throws into the modelandview some objects that i need in the view.
This modelandview has root to a js file.
The problem is that the html does not load the js file that is called above.
Tried some solutions found on Stackoverflow, the solutions were to handle all of this in the mvdconfig controller.
And go throw the dependencies and make sure the dependencies are for Spring 4.
I m using Spring 1.5.9 and spring-boot-starter-thymeleaf
#GetMapping(value = "/customer/web/wall/calendar", params = {"wallId"})
public ModelAndView calendar(#RequestParam(value = "wallId") long wallId,
Authentication auth,
RedirectAttributes redirectAttributes){
ModelAndView modelAndView = new ModelAndView("/customer/wall/calendar");
modelAndView.addObject("wallId",wallId);
return modelAndView;
}
#GetMapping(value = "/customer/web/wall/calendarItems", params = {"wallId"})
public ModelAndView calendarItems(#RequestParam(value = "wallId") long wallId,
Authentication auth,
RedirectAttributes redirectAttributes){
User currentUser = (User) auth.getPrincipal();
Set<Long> wallIds = new HashSet<>();
wallIds.add(wallId);
PlaybookFilters playbookFilters = new PlaybookFilters();
playbookFilters.setCustomerId(currentUser.getCustomerId());
playbookFilters.setWallIds(wallIds);
List<Playbook> playbooks = playbookService.getPlaybooks(playbookFilters);
Date dateBegin = calendarService.getDateBegin();
Date dateEnd = calendarService.getDateEnd();
List<CalendarItem> calendarItems = calendarService.fetchPbiForPlaybooks(playbooks, dateBegin, dateEnd);
ArrayNode items = objectMapper.createArrayNode();
calendarItems.forEach(item -> items.add(item.toJsonNode()));
ModelAndView modelAndView = new ModelAndView("/customer/wall/calendarItems");
modelAndView.addObject("events", items);
return modelAndView;
}

Related

ModelAndView reference to view with name model is null in spring boot

I have a jsp page named product. I have send some message to jsp page from controller using ModelAndView. But it returns null. ModelAndView's Message is not set to jsp page. here is my controller code..
#RequestMapping(value = "/add", method = RequestMethod.POST)
public ModelAndView adduser(#ModelAttribute("productForm") Errors error, Model model) {
ModelAndView modelAndView = new ModelAndView("product");
System.out.println(modelAndView);
modelAndView.addObject("outMessage", "User Registration Success");
return new ModelAndView("redirect:/productSetup");
}
Please help me..
You should use Redirect Flash Model attributes when redirecting.
#RequestMapping(value = "/add", method = RequestMethod.POST)
public ModelAndView adduser(#ModelAttribute("productForm") Errors error, RedirectAttributes redir) {
ModelAndView modelAndView = new ModelAndView("product");
System.out.println(modelAndView);
redir.addFlashAttribute("outMessage", "User Registration Success");
return new ModelAndView("redirect:/productSetup");
}
Refer this for more info : https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/support/RedirectAttributes.html

Meaning of addObject in springMVC

I am developing a web service using Spring MVC. When I referred to some examples on serving JSP pages in Controller I came across the following code:
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView showLogin(HttpServletRequest request, HttpServletResponse response) {
ModelAndView mav = new ModelAndView("login");
mav.addObject("login", new Login());
return mav;
}
Can someone tell me the reason for using addObject here. I hope "login" refers to the JSP page login.jsp. If so, what does new Login() refers to?
ModelAndView mav = new ModelAndView("login");
"login" indeed refers to the name of the JSP page. Returning this ModelAndView will direct the user to login.jsp.
mav.addObject("login", new Login());
adds an attribute to the Model in ModelAndView. This means you can access the Login object in your JSP page by accessing it through the attribute name "login", e.g. ${login}.

Return list of values on ajax success in spring MVC

I am looking for returning a list of values after ajax success in spring mvc
#RequestMapping(value = "/getAlertNotification.ftl")
public ModelAndView getAlertNotification(HttpServletRequest request
){
Map<Object, Object> model = new HashMap<Object, Object>();
User user = RequestUtils.getUser(request);
List<CardRequestNotification> Cardreqlist=cardRequestManager.cardRequestNotification(user);
model.put("listObj", Cardreqlist);
return new ModelAndView(new JSONView(model));
}
$("#alertLink").click(function()
{ var $this = j$(this);
GtsJQuery.ajax(GtsJQuery.getContextPath()
+ "/getAlertNotification.ftl",
function(data) {
/* how i return Cardreqlist object list`enter code here` in here */
});
I guess you are having a misunderstanding concept, if you are trying to return a ModelAndView then you need to specify the JSP file or HTML template which will be rendered, and you need the specific ModelAndView name.
But you are mixing Views and JSON, which is for AJAX calls, so i guess your code would be something more like this:
#RequestMapping(value = "/getAlertNotification.ftl")
#ResponseBody
public List<CardRequestNotification> getAlertNotification(HttpServletRequest request) {
Map<Object, Object> model = new HashMap<Object, Object>();
User user = RequestUtils.getUser(request);
List<CardRequestNotification> Cardreqlist = cardRequestManager.cardRequestNotification(user);
model.put("listObj", Cardreqlist);
return Cardreqlist;
}
Then in your JS code, you could do:
data.Cardreqlist

Migrating to Spring MVC 4

We are migrating our mvc code to Spring 4. Previously we had a a method formBackingObject which we converted to get method initForm.
But trouble is - in previous controller which was extending SimpleFormController, formBackingObject was getting called even before submit method. We have now removed SimpleFormController. But initForm is getting called only only once on page load. It doesn't get called before submit. And there is some custom logic of creating user object and adding to UserProfileForm object.
Have you faced similar issue.
Old code
protected Object formBackingObject(HttpServletRequest request) throws Exception {
final UserProfileForm userProfileForm = new UserProfileForm();
final String id = request.getParameter("id");
if (id != null && !id.trim().equals("")) {
final User user = authenticationServices.findUser(ServletRequestUtils.getLongParameter(request, "id"));
userProfileForm.setUser(user);
} else {
final User user = new User();
userProfileForm.setUser(user);
}
return userProfileForm;
}
new code
#RequestMapping(method = RequestMethod.GET)
public String initForm(HttpServletRequest request, ModelMap model) throws Exception{
final UserProfileForm userProfileForm = new UserProfileForm();
final String id = request.getParameter("id");
if (id != null && !id.trim().equals("")) {
final User user = authenticationServices.findUser(ServletRequestUtils.getLongParameter(request, "id"));
userProfileForm.setUser(user);
} else {
final User user = new User();
userProfileForm.setUser(user);
}
addToModel(request, model);
model.addAttribute("userProfileForm", userProfileForm);
return "user-management/user-profile";
}
Create a method annotated with #ModelAttribute to fill your model.
#ModelAttribute("userProfileForm");
public UserProfileForm formBackingObject(#RequestParam(value="id", required=false) Long id) throws Exception{
final UserProfileForm userProfileForm = new UserProfileForm();
if (id != null) {
final User user = authenticationServices.findUser(id);
userProfileForm.setUser(user);
} else {
final User user = new User();
userProfileForm.setUser(user);
}
return userProfileForm;
}
#RequestMapping(method = RequestMethod.GET)
public String initForm() {
return "user-management/user-profile";
}
This way you can also use the #RequestParam annotation instead of pulling out parameters yourself.
See the reference guide for more information on the subject.
Certain inter-module dependencies are now optional at the Maven POM level where they were once required. For example, spring-tx and its dependence on spring-context. This may result in ClassNotFoundErrors or other similar problems for users that have been relying on transitive dependency management to pull in affected downstream spring-* . To resolve this problem, simply add the appropriate missing jars to your build configuration.

Spring MVC + GWT : Redirect Issue

I am using Spring annotated MVC framework in an app which I am developing.
Following is the issue I am facing:
I have Controller which does a redirect, after a POST:
#RequestMapping(value = "/emdm-viewer-redirect.do", method = RequestMethod.POST)
public ModelAndView getMetricKeysAndRedirect(#RequestParam Object jsonObject, Model model)
{
ModelAndView modelAndView = new ModelAndView("redirect:/mdm-viewer.do");
.....
.....
....//make some service calls and populate value1
...
modelAndView.addobject("param1", value1);
return modelAndView;
}
I have another controller which is mapped to URL mdm-viewer.do (The redirect URL mentioned above):
#RequestMapping(value = "/mdm-viewer.do", method = RequestMethod.GET)
public String getMDMViewer(Model model) {
return "mdmViewer"; //returns a mdmViewer.jsp
}
Please note that the mdmviewer.jsp is a GWT entrypoint which is in classpath.
I have my firebug window open which tells me that a GET request was made for mdm-viewer.do, but it gives me a blank response. In fact, it does not redirect to the new jsp and stays on the same page from where the POST request was made.
However, if I copy the firebug URL and open it in a new window of my browser, I see the expected results.
Any ideas what I am doing wrong here? Tried to google it a lot, but can't find a similar issue anywhere.
Eventually, I returned a ModelAndView back from the POST method using a
#ResponseBody
And in my GWT Module, I used the response.getText() output to do a
#Override
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
JSONObject jsonObject = (JSONObject) JSONParser.parse(response.getText());
String viewName = jsonObject.get("viewName").isString().stringValue();
JSONObject jsonParams = jsonObject.get("model").isObject();
Set<String> chartKeys = jsonParams.keySet();
String redirectURL = viewName + "?";
for (String keyString : chartKeys) {
redirectURL = redirectURL + keyString + "=" + jsonParams.get(keyString).isString().stringValue() + "&";
}
Window.open(GWT.getHostPageBaseURL() + redirectURL, "_self", "");
}
}

Resources