Issue
I have list of category in database and I want to bind those category in combobox: I know this is silly question and asked by so many times but I din't get answer as I want please do not down-vote or mark as duplicate.
Hare is my code: Controller class:
public String getCategoryList(Model model) {
List<Category> categoryList = categoryService.getAllCategory();
model.addAttribute("categoryList", categoryList);
return "redirect:/manageProduct";
}
Repository class:
@Override
public List<Category> getAllCategory() {
CriteriaQuery<Category> criteriaQuery = HibernateUtil.getSession(sessionFactory).getCriteriaBuilder()
.createQuery(Category.class);
criteriaQuery.from(Category.class);
List<Category> categoryList = HibernateUtil.getSession(sessionFactory).createQuery(criteriaQuery)
.getResultList();
return categoryList;
}
JSP page:
<label>Product Category</label> <select name="category"
class="browser-default custom-select mb-4">
<option value="" disabled selected>Choose Category</option>
<c:forEach items="${categoryList}" var="catList">
<option value="${catList.id}">${catList.categoryName}</option>
</c:forEach>
</select>
Where I am getting wrong please mark my error and try to answer in a simple way. Thank You.
Expected Result: populate list of category from database. Actual Result: Nothing get populated.
Solution
The problem is that you issue a redirect from the original request and therefore the model is not available when the view is rendered.
public String getCategoryList(Model model) {
List<Category> categoryList = categoryService.getAllCategory();
model.addAttribute("categoryList", categoryList);
//return "redirect:/manageProduct";
return "/manageProduct";
}
There is no need to redirect from a GET request so change as above and it should be fine.
If you do need to make request attributes available after a redirect (e.g. if following the Post/Redirect/Get pattern https://en.wikipedia.org/wiki/Post/Redirect/Get) then you can use Flash Attributes.
See here for more details:
https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-flash-attributes
https://dzone.com/articles/spring-mvc-flash-attributes
Answered By - Alan Hay