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}.
Related
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;
}
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
I am very new to Spring Framework and web develop field.
I was surprised that Spring can add attributes in its redirect response that goes to client side.
As far as I know, if a server gives a response that let client do redirect, then another request is made by client and contained values from previous request or response are gone.
But clearly it doesn't in Spring. How can this happen?
There are two ways to send parameters with redirection in spring.
1.Parameters will be visible in URL.
#RequestMapping(method = RequestMethod.PUT, produces = "text/html")
public String update(#Valid User user, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
uiModel.addAttribute("parameter1", "value1");
uiModel.addAttribute("parameter2", "value2");
return "redirect:/" + "redirectionURL";
}
2.Parameters will be hidden in URL.
#RequestMapping(method = RequestMethod.PUT, produces = "text/html")
public String update(#Valid User user, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest, RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("parameter1", "value1");
redirectAttributes.addFlashAttribute("parameter2", "value2");
return "redirect:/" + "redirectionURL";
}
This is my code inside the controller class. When the user enters localhost:8080/url, it retrieves the original long url let's say www.google.com saved in the database and then i want it to redirect to www.google.com but instead it redirects to localhost:8080/www.google.com and thus gives en error 500.
#RequestMapping(value="/{url}", method = RequestMethod.GET)
public RedirectView getLongURl(#PathVariable("url") String url) {
String original = database.getLongUrl(UrlShortener.decode(url));
RedirectView redirectview = new RedirectView();
redirectview.setUrl(original);
return redirectview;
}
You should return a ModelAndView
#RequestMapping(value="/{url}", method = RequestMethod.GET)
public ModelAndView method(#PathVariable("url") String url) {
String original = database.getLongUrl(UrlShortener.decode(url));
return new ModelAndView("redirect:" + original);
}
You do not have the option to redirect your request to an outside domain/host like google.com using the RedirectView. As it's name says, it redirects your request to an "another view" in your application.
Refer the docs for more on RedirectView
I'm using Spring MVC and I'm wondering is it possible to change URL when I return ModelAndView (the view is situated at the WEB-INF folder, so redirecting to it is not working) from the controller? I mean when I return it the URL is the previous one, and its obvious because dispatcher is working, not the redirecting.
#RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView authenticate(#RequestParam("login") String login, #RequestParam("password") String password) {
ModelAndView modelAndView = new ModelAndView();
User user = userDao.getUserByLogin(login);
if (user != null && user.getPassword().equals(password)) {
modelAndView.addObject("user", user);
modelAndView.setViewName("home");
}
return modelAndView;
}
So my home model is in WEB-INF folder, so return redirect:/home will not work for it. Yes, I can redirect it with return home, but in that case the URL will not change.
Use redirect:/url to some other method and return the view.
When redirecting the model attributes won't available in new method so to get that in redirected method set it in RedirectFlashAttributes.
Hope it helps.