Return list of values on ajax success in spring MVC - ajax

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

Related

SPRING MVC: Defined HttpSession in One Method is Not Available to Another Method

I am facing a problem regarding to the Httpsession that I implementing in the Spring MVC project.
First of all, after the user successfully login, I will take the Httpsession object in loginAuthentication controller and set attribute with the name and value I want. (Shown in following figure).
A.java controller file,
#RequestMapping(value="login-authentication", method = RequestMethod.POST)
public String authentication(#Valid #ModelAttribute("systemAccount") SystemAccount systemAccount,
BindingResult bindingResult, Model model, HttpServletRequest request){
if (bindingResult.hasErrors()) {
model.addAttribute(GenericConstant.MessageAttributeName.ERROR_MSG_NAME.toValue(), SystemMessage.SystemException.LOGIN_INCORRECT_USERNAME_PASSWORD.toValue());
model.addAttribute("systemAccount", new SystemAccount());
return "index";
}else {
if (systemAccountService.authenticate(systemAccount.getUsername(), systemAccount.getPassword()) != null &&
!"".equals(systemAccountService.authenticate(systemAccount.getUsername(), systemAccount.getPassword()))) {
SystemAccount dbSystemAccount = systemAccountService.authenticate(systemAccount.getUsername(), systemAccount.getPassword());
request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ID.toValue(),dbSystemAccount.getAccountID());
//check account role
if(dbSystemAccount.getCounterStaff()!= null && !"".equals(dbSystemAccount.getCounterStaff())){
CounterStaff counterStaff = dbSystemAccount.getCounterStaff();
request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_NAME.toValue(), counterStaff.getStaffName());
request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ROLE.toValue(), GenericConstant.SystemRole.COUNTER_STAFF.toValue());
}else if(dbSystemAccount.getCustomer()!= null && !"".equals(dbSystemAccount.getCustomer())){
Customer customer = dbSystemAccount.getCustomer();
request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_NAME.toValue(), customer.getCustomerName());
request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ROLE.toValue(), GenericConstant.SystemRole.CUSTOMER.toValue());
}else if(dbSystemAccount.getManager()!= null && !"".equals(dbSystemAccount.getManager())){
Manager manager = dbSystemAccount.getManager();
request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_NAME.toValue(), manager.getManagerName());
request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ROLE.toValue(), GenericConstant.SystemRole.MANAGER.toValue());
}else if(dbSystemAccount.getDoctor()!= null && !"".equals(dbSystemAccount.getCounterStaff())){
Doctor doctor = dbSystemAccount.getDoctor();
request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_NAME.toValue(), doctor.getDoctorName());
request.setAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ROLE.toValue(), GenericConstant.SystemRole.DOCTOR.toValue());
}
request.setAttribute(SessionAttribute.AttributeName.LOGIN_DATE.toValue(), DateTimeUtil.getCurrentDate());
return "mainPage";
}else {
model.addAttribute(GenericConstant.MessageAttributeName.ERROR_MSG_NAME.toValue(), SystemMessage.SystemException.LOGIN_INCORRECT_USERNAME_PASSWORD);
model.addAttribute("systemAccount", new SystemAccount());
return "index";
}
}
}
After everything is ready, the controller will navigate user to the main page and the main page able to access all the defined variable without issue. (The following figure shown the controller that mapped with mainPage).
A.java controller file,
#RequestMapping(value = "/mainPage", method = RequestMethod.GET)
public String renderMainPageView(Model model, HttpServletRequest request) {
if(request.getAttribute(SessionAttribute.AttributeName.LOGIN_CHECK.toValue()) != null) {
model.addAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ID.toValue(),
request.getAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ID.toValue()));
model.addAttribute(SessionAttribute.AttributeName.LOGIN_ACC_NAME.toValue(),
request.getAttribute(SessionAttribute.AttributeName.LOGIN_ACC_NAME.toValue()));
model.addAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ROLE.toValue(),
request.getAttribute(SessionAttribute.AttributeName.LOGIN_ACC_ROLE.toValue()));
model.addAttribute(SessionAttribute.AttributeName.LOGIN_DATE.toValue(),
request.getAttribute(SessionAttribute.AttributeName.LOGIN_DATE.toValue()));
return "mainPage";
}else {
model.addAttribute("systemAccount", new SystemAccount());
return "index";
}
}
In the navigation menu of main page, I click on the selection to direct me to add manager web page. (The following shown the link).
<a href="addManager" target="ifrm" >Add New Account</a>
The controller that mapped with the link (GET) able to detect. However, this controller (renderAddManagerView) does not recognised the HTTP session that I defined earlier when I try to access using the getAttribute method in the if condition. It keep showing null value (Shown in the following figure.
B.java controller file,
#RequestMapping(value = "/addManager", method = RequestMethod.GET)
public String renderAddManagerView(Model model, HttpSession httpSession) {
if(httpSession.getAttribute(SessionAttribute.AttributeName.LOGIN_CHECK.toValue()) != null) {
model.addAttribute("manager", new Manager());
model.addAttribute(FormSelectionValue.FormSelectionAttributeName.COUNTRY_SELECTION.toValue(), FormSelectionValue.COUNTRY_SELECTION_LIST);
model.addAttribute(FormSelectionValue.FormSelectionAttributeName.GENDER_SELECTION.toValue(), FormSelectionValue.GENDER_SELECTION_LIST);
return "addManager";
}else {
model.addAttribute("systemAccount", new SystemAccount());
return "index";
}
}
So I am not sure what is the issue for my code and there is no error message is displayed.
I have solved the issue by using the HttpServletRequest instead of HttpSession.
Now my session will not be loss even redirect or navigate to any pages in JSP.
Something like this:
#RequestMapping("/renderview", method = RequestMethod.GET)
#Controller
public class TestController {
#RequestMapping(method = RequestMethod.GET)
public String myMethod(HttpServletRequest request)
{
request.getSession().setAttribute("mySession", "XXX");
return "jspview";
}
}
Reference: Set session variable spring mvc 3

How to load a JavaScript file using thymeleaf + springboot

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;
}

How to postForObject list of object?

I have a working example of posting only one object, but i dont know how to post a list of object. Here's how im trying to do this :
Client
protected List<EventStudent> doInBackground(Object... params) {
RestTemplate template = new RestTemplate();
template.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
EventStudent[] array = new EventStudent[event.size()];
event.toArray(array);
template.postForObject(URL.GET_EVENT_INFO ,array, EventStudent[].class);
return event;
}
this is how im trying to get them on server:
Server
#RequestMapping(value = "/eventstudent", method = RequestMethod.POST)
#ResponseBody
public List<EventStudent> saveRemider(#RequestBody List<EventStudent>event) {
return service.save(event);
}
But it won't work
the problem is generic and type erasure for List , this would be equivalent of List< ? > in controller method.
Create a custom list class just to wrap List into List that can be handled by spring mvc
public class EventStudentList extends ArrayList<EventStudent> {
}
and use it as
#RequestMapping(value = "/eventstudent", method = RequestMethod.POST)
#ResponseBody
public List<EventStudent> saveRemider(#RequestBody EventStudentList event) {
return service.save(event);
}

Reference Data is lost from Form when Validation Fails (Spring 3 MVC)

I am new to Spring
I am having a page addContact,in that I am getting dropDown Data from Database in the following way
#RequestMapping("/addContact")
public ModelAndView registerContact(#ModelAttribute Contact contact) {
List<ContactType> contactTypeList = contactdao.getContactTypeList();
Map<Integer,String> contactTypeSelect = new LinkedHashMap<Integer,String>();
Iterator<ContactType> iterator = contactTypeList.iterator();
while (iterator.hasNext()) {
ContactType ct = iterator.next();
contactTypeSelect.put(ct.getContactTypeId(),ct.getContactTypeName());
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("contactTypeSelect", contactTypeSelect);
return new ModelAndView("addContact", "map", map);
}
Now to Insert the Data into Database, I am having following method,
#RequestMapping("/insert")
public String insertData(#Valid Contact contact, BindingResult result, HttpServletRequest request ) {
if (result.hasErrors()) {
return "addContact";
}
else {
HttpSession session = request.getSession();
session.setAttribute("path", request.getSession().getServletContext().getRealPath("/WEB-INF"));
if (contact != null){
contactService.insertData(contact,request);
}
return "redirect:/getList";
}
}
When the validation fails, the drop down data is lost (which is obvious), what is the correct way of achieving the validation.
Create a method annotated with #ModelAttribute which loads the reference data. This method will be called before each #RequestMapping method.
#ModelAttribute("contactTypeSelect")
public List<ContactType> registerContact() {
return contactdao.getContactTypeList();
}
In your form you can use the <form:select ../> tag to render the itemValue and itemLabel.
<form:select items="${contactTypeSelect}" itemLabel="contactTypeName" itemValue="contactTypeId" />
With this you can refactor your addContact method to the following
#RequestMapping("/addContact")
public String registerContact(#ModelAttribute Contact contact) {
return "addContact";
}
You lose the drop down data because you're not adding in the contact map in the insertData method. Pull out the code where you grab the contact data into a separate (private) method and use it in the result.hasErrors() if block as such:
if (result.hasErrors()) {
return new ModelAndView("addContact", "map", map);
}
Also, I strongly suggest adding a method to the #RequestMapping annotation as such:
#RequestMapping("/insert", method=RequestMethod.POST)
This keeps people from making GET calls to this method.

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