Issue
I'm using Spring MVC web app: Servlet + JSP + Hibernate. This is a part from my CustomerController.java
@RequestMapping(value="/CustomerList", method = RequestMethod.GET)
public ModelAndView customerList() {
ModelAndView model = new ModelAndView();
model.setViewName("Customer.List"); // for Tiles View
model.addObject("listCustomer", DAO_Customer.getListCustomer());
return model;
}
@RequestMapping(value="/Customer/{id}/Delete", method = RequestMethod.GET)
public String deleteCustomer(@PathVariable("id") int id, Model model) {
boolean isSuccess = DAO_Customer.deleteCustomer(id);
if (!isSuccess) {
model.addAttribute("error", "Failed");
}
model.addAttribute("success", "Successed");
return "redirect:/CustomerList";
}
and here is the code in CustomerList.jsp
file to display:
...
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:if test="${not empty error}">
<p>${error}</p>
</c:if>
<c:if test="${not empty success}">
<p>${success}</p>
</c:if>
...
I want to redirect to /CustomerList
and include parameters error
+ success
.
The problem is, when I run, it return /CustomerList?success=Successed
and nothing show up expect the default customer list
I search a lot but really don't know how to do what I want. Thanks everyone for read and help.
Solution
You can try with RedirectAttributes#addAttribute.
@RequestMapping(value="/Customer/{id}/Delete", method = RequestMethod.GET)
public String deleteCustomer(@PathVariable("id") int id, RedirectAttributes redirectAttributes) {
boolean isSuccess = DAO_Customer.deleteCustomer(id);
if (!isSuccess) {
redirectAttributes.addAttribute("error", "Failed");
} else{ //also required
redirectAttributes.addAttribute("success", "Successed");
}
return "redirect:/CustomerList";
}
In this case, the url will turn into /CustomerList?success=Successed
if successful.
And you can access param value with EL
as follows:
${param.success} or ${param.error}
Also you can use RedirectAttributes#addFlashAttribute
.
redirectAttributes.addFlashAttribute("success", "Successed");
Then you can access directly as ${success}
or ${error}
.
Answered By - Gurkan Yesilyurt