How to pass checkbox values to the controller in Spring MVC - spring

I have a jsp page with list of functions. Here in controller I get this list from database and pass it to jsp.
#RequestMapping(value = "/functionlist", method = RequestMethod.GET)
public ModelAndView functionList(Model model) throws Exception {
ModelAndView mv = new ModelAndView("functionList");
mv.addObject("functionList", getFunctionsFromDB());
return mv;
}
In my jsp page I create table using this list of functions
<table id="table">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<c:choose>
<c:when test="${not empty functionList}">
<c:forEach var="function" items="${functionList}">
<tr>
<td><input name="id" value="${function.id}" hidden></td>
<td>${function.name}</td>
<td>
<input type="checkbox" id="${function.id}" value="${function.action}"></td>
</tr>
</c:forEach>
</c:when>
</c:choose>
</tbody>
</table>
<button type="submit" name="save">Save</button>
I also give function id to checkbox id.
My Function entity is the following
public class Function {
private Integer id;
private String name;
private Boolean action;
...
}
I want to press button Save and get in controller "/functionlist/save" my list of checkbox values.

Try to add form like this to your jsp page
<form:form id="yourForm" action="/functionlist/save" method="POST" modelAttribute="functionList">
<c:forEach items="${functionList}" varStatus="status" var="function">
<tr>
<td>${function.name}</td>
<td>
<form:checkbox path="functionList[${status.index}].action"/>
</td>
</tr>
</c:forEach>
<input type="submit" value="submit" />
</form:form>
and in Controller you should have a method like this
#RequestMapping(value = { "/functionlist/save" }, method = RequestMethod.POST)
public String savePerson(#ModelAttribute("functionList")List<Function> functionList) {
// process your list
}
If this does not work, you can try to wrap you list.
public class FunctionListWrapper {
private List<Function> functionList;
public FunctionListWrapper() {
this.functionList = new ArrayList<Function>();
}
public List<Function> getFunctionList() {
return functionList;
}
public void setFunctionList(List<Function> functionList) {
this.functionList = functionList;
}
public void add(Function function) {
this.functionList.add(function);
}
}
in controller instead of passing list, pass wrapper
FunctionListWrapper functionListWrapper=new FunctionListWrapper();
functionListWrapper.setFunctionList(userService.getFunctionList());
mv.addObject("functionListWrapper", functionListWrapper);
For more details please take a look at this questions: question 1 and question 2

First you need to add name attribute to your checkbox inputs.You can get these in
an array on controller with same name as your name attribute.eg-
#RequestMapping(value = "/functionlist", method = RequestMethod.GET)
public ModelAndView functionList(Model model,#RequestParam("checkboxname")String[] checkboxvalues) throws Exception {
ModelAndView mv = new ModelAndView("functionList");
mv.addObject("functionList", getFunctionsFromDB());
return mv;
}

few things.
First you should think about a form object, which is the exchange entity between the view and the controller. The form entity will be something similar to the followng:
public class Form {
private List<Function> functions;
//getters & setters
}
secondly, since you are using Spring MVC, you should leverage the <%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %> library. Consequently, your form will be:
<form:form commandName="form" action="/your/url">
<c:forEach items="${form.functions }" var="function" varStatus="status">
<tr>
<td><form:hidden path="functions[${status.index }].id"></td>
<td>${function.name}</td>
<td>
<form:checkbox path="functions[${status.index }].action" id="${function.id}" value="${function.action}"/>
</td>
</tr>
</c:forEach>
</form:form>
and finally the controller will be something like
#RequestMapping(value="/your/url", method=RequestMethod.POST)
public String postForm(#ModelAttribute("form") FormForm form)
{
//cool stuff here
}
please note that the proper HTTP method is POST, not GET. Yup, I know things work also with GET it's definitely a deprecated strategy.
In addition, figure out how I referred the list of Function in the Form. I used the variable function in the foreach statement when I had to display data, I referred the list when I had to bind the Form object for transferring data to the controller. Last but not least, I haven't tried the code. I wrote it on the fly just to give you hints about how to do it properly.
One last thing. Since you pass the Form to the JSP, you don't need anymore to fill the Model with the attribute you used. Just fill the form with your data and use it to diaplay them in the view. Just like this ${form.stuff.you.want}

Related

JSP&Spring: How can I pass one parameter using JSP EL with submit button?

I'm trying to pass one parameter from a jsp page to Spring controller file.
However, I fail and fail again.
When I put just real data of database like a, b, c... instead of "${deleteList['user_id']}", my codes works well.
I have no idea.
I'd be appriciated if I can get your answer.
<table border="0">
<c:forEach items="${deleteList}" var="deleteList">
<tr><td align="right">ID:</td><td>${deleteList.user_id}</td></tr>
</c:forEach>
</table> <form action="${pageContext.request.contextPath}/user/delete" method="get"> <input type="hidden" name="user_id" value="${deleteList['user_id']}" />
<input type="submit" name="confirm" value="Delete" />
#RequestMapping(value = "/delete", params="confirm", method = RequestMethod.GET)
public String deleteConfirm(Model model, HttpServletRequest req) {
String user_id=req.getParameter("user_id");
UmsDAO dao=sqlSession.getMapper(UmsDAO.class);
ArrayList<UVO> uvo = dao.deleteList(user_id);
model.addAttribute("deleteList", uvo);
return "user/deleteConfirm";
}
<c:forEach items="${deleteList}" var="deleteList">
<tr><td align="right">ID:</td><td>${deleteList.user_id}</td></tr>
</c:forEach>
you are not sending any value in user_id..
<tr><td align="right">ID:</td><td>${deleteList.user_id}</td>
<td> from this try once.. you will get specific value what you want</td>
</tr>
Instead of using form every time use anchor tag and send value in partameter
Solution:
use HttpSession
For example:
#RequestMapping(value = "/delete", params = "confirm", method = RequestMethod.GET)
public String deleteConfirm(Model model, HttpServletRequest req) {
HttpSession session = req.getSession();
String user_id = (String) session.getAttribute("user_id");
UmsDAO dao = sqlSession.getMapper(UmsDAO.class);
ArrayList<UVO> uvo = dao.deleteList(user_id);
model.addAttribute("deleteList", uvo);
return "user/deleteConfirm";
}

<option> returning emptyin UI form:select of spring mvc3

I've a list of values to be passed from my controller to the jsp page. I've the below controller:
#RequestMapping(value="/addClient.do", method = RequestMethod.GET)
protected ModelAndView Submit(HttpServletRequest request, HttpServletResponse response) throws Exception {
MyForm = new MyForm();
MyForm.setClientList(MyService.getClientList(/*"30-JUN-15"*/));
System.out.println("Size of list : "+MyForm.getClientList().size()); //-- Displayed as 10 which is correct
ModelAndView model = new ModelAndView("feeMaintenance");
model.addObject("clientForm",MyForm);
model.addObject("selectedMenu", "MenuSelected");
model.addObject("clientsList",MyForm.getClientList());
return model;
}
And my jsp form is as below:
<body>
<form:form method="post" modelAttribute="clientForm" action="${userActionUrl}">
<tr> <td align="left">
<form:select path="clientList">
<form:option value="-" label="------Select Client ------">
<form:options items="${clientsLists}">
</form:options></form:option></form:select>
</tr> </td>
</form>
</body>
I've removed the additional unrelated code. The drop down only shows ----Select Client--- even though the controller shows the correct values of the clientList. Unable to figure out whats missing.
if MyForm.getClientList() is successfully return list of client data than
rewrite this line into jsp page.
you write key name into controller is clientsList and you write this into jsp page is clientsLists this is wrong.
I hope this is work.
try this code.
model.addObject("country", projectservice.getallCountry());
**Note:**itemLabel name is same as property name into pojo class and also itemValue name.

Simple JSP-Spring 3 dropdown list not working

I know this should be pretty easy but I'm stuck after trying several things.
I'm only trying to display in my jsp a basic dropdown list. Spring version is 3 so I want everything to work with annotations.
JSP form with dropdown list:
<form:form method="post" commandName="countryForm">
<table>
<tr>
<td>Country :</td>
<td><form:select path="country">
<form:option value="Select" label="Select" />
</form:select>
</td>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form:form>
CountryForm.java is a plain object with a single String attribute "country", with its getters and setters.
Controller who deals with the GET request is the following:
#Controller
public class CountryFormController {
#RequestMapping(value = "MainView", method = RequestMethod.GET)
public String showForm(Map model) {
CountryForm cform = new CountryForm();
model.put("countryForm", cform);
return "MainView";
}
}
However, when I redirect to the JSP "MainView" I get the typical error:
org.apache.jasper.JasperException: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'countryForm' available as request attribute
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:502)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:424)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
What am I doing wrong?
The select tag in the Spring TagLib needs to be provided with a collection, map or array of options. I'm not sure what you would like these to be so I will make some assumptions.
You need to include a collection, map or array of objects in your controller. Ideally you would have a Country class and create new instances for a set of countries. For the example to work with your code, I just created a static list of countries. Add the list to your model and then modify the select tag, setting the options to ${countries}. Assuming country is a field of type String on CountryForm with appropriate get/set methods, the country should data-bind to field when the form is submitted.
Controller
#Controller
public class CountryFormController {
#RequestMapping(value = "MainView", method = RequestMethod.GET)
public String showForm(Map model) {
List<CountryForm> cfs = new ArrayList<CountryForm>();
cfs.add("United States");
cfs.add("Canada");
model.put("countries", cfs);
model.put("countryForm", cform);
return "MainView";
}
}
JSP
<form:select path="countryForm.country" options="${countries}"/>
I have sample code at GitHub, try it an let me know. Look at landing.jsp and UserController
<form:select path="users[${status.index}].type" >
<form:option value="NONE" label="--- Select ---"/>
<form:options itemValue="name" itemLabel="description" />
</form:select>
HTH

If you intend to handle the same path in multiple methods Spring

Im using spring MVC.
My Controller is :
#RequestMapping(value = "/approval/pendingescort", method = RequestMethod.GET)
public String getPendingEscort(Model model) {
log.debug("Received request to show Pending Escorts");
// Retrieve all pending escort details by delegating the call to Servicelayer
List<EscortRegistration> pendingEscortdetails = approvalService.getAllPendingEscort();
// Attach zones to the Model
model.addAttribute("pendingEscortdetails", pendingEscortdetails);
// This will resolve to /WEB-INF/jsp/pendingescort.jsp
return "pendingescort";
}
#RequestMapping(value = "/approval/pendingescort/success", method = RequestMethod.GET)
public String addEscort(#RequestParam(value="mobileno", required=true) String mobileno,Model model) {
log.debug("Received request to Accept Escort Request");
// Call ZonedetailsService to do the actual Updating
approvalService.approveEscortRequest(mobileno);
// Add mobile reference to Model
model.addAttribute("mobileno", mobileno);
// This will resolve to /WEB-INF/jsp/addedescortpage.jsp
return "pendingescort";
}
and my JSP Is :
<tbody>
<c:forEach items="${pendingEscortdetails}" var="escort">
<c:url var="editUrl" value="/efmfm/main/approval/pendingescort/success?mobileno=${escort.mobilenumber}" />
<c:url var="deleteUrl" value="/efmfm/main/approval/pendingescort/delete?mobileno=${escort.mobilenumber}" />
<tr>
<td><c:out value="${escort.mobilenumber}" /></td>
<td><c:out value="${escort.imei}" /></td>
<td> Approve
<!-- <td>Approve</td> -->
Reject
</td>
</tr>
</c:forEach>
</tbody
when i click to approve its sending to success page. i want to bring this to previous page with refresh.
Can any one solve my problem.
use
return "redirect:../../../approval/pendingescort";
Instead of
return "pendingescort";
First: I guess you need to use "../.."
return "redirect:../../../approval/pendingescort";
One more doubt. Are you using tiles??

Paging with page numbers in JSP file not url

I am using spring paging framework for my form. I am testing the paging framework from here:
http://www.developer.com/java/web/article.php/10935_3830886_3/A-Pagination-Technique-Using-Spring.htm. The url for my form displays the page numbers like this:
1st page: http://...stuff../mySite/paging/paging/0
2nd page: http://...stuff../paging.do?action=list&p=1
3rd page: http://...stuff../paging.do?action=list&p=2
etc
The paging is not consistent and causes a problem in my code (note the difference btwn first pg and 2nd pg urls) and to keep my url clean, I prefer to store the page numbers as a hidden jsp parameter. Is it possible? Do you have any advice? Thanks.
My controller:
#Controller
#RequestMapping(value="/paging")
#ApplicationComponent(component="Paging")
public class PaginationController
{
private final Log logger = LogFactory.getLog(getClass());
#Autowired
private ItemDao itemDao;
#RequestMapping(value="/paging/{p}")
public ModelAndView list(#PathVariable("p") int page) throws Exception
{
ModelAndView mav = new ModelAndView("paging/paging");
System.out.println("In the paging controller");
// get data in a list from jsp
List searchResults = itemDao.getAllItems();
// initialize PagedListHolder with the list,
PagedListHolder pagedListHolder = new PagedListHolder(searchResults);
pagedListHolder.setPage(page);
int pageSize = 5;
pagedListHolder.setPageSize(pageSize);
mav.addObject("pagedListHolder", pagedListHolder);
return mav;
}
}
Here is the JSP:
<jsp:useBean id="pagedListHolder" scope="request" type="org.springframework.beans.support.PagedListHolder"/>
<%-- // create link for pages, "~" will be replaced with the proper page number --%>
<c:url value="/paging.do" var="pagedLink">
<c:param name="action" value="list"/>
<c:param name="p" value="~"/>
</c:url>
<tg:paging pagedListHolder="${pagedListHolder}" pagedLink="${pagedLink}"/>
<%-- // show only current page data --%>
<table width="200px" border="1">
<tr>
<th width="20px">No.</th>
<th>Print Items from pagedListHolder list</th>
</tr>
<c:forEach items="${pagedListHolder.pageList}" var="item">
<tr>
<td>${item.key}</td>
<td style="color:blue;font-weight:bold;text-align:right">${item.data}</td>
</tr>
</c:forEach>

Resources