How to add the result variable of form submission to mapping? - java

I have this form in a jsp file where I dynamically populate a dropdown from a list. It works fine. This is the home jsp at core address "/" and it sends data to "/spravochnik/list".
<form action="/spravochnik/list" method="post">
<select name="tableName">
<c:forEach var="dropDown" items="${dropDown}">
<c:forEach var="valuesInRows" items="${dropDown.valuesInRows}">
<c:forEach var="valuesInRow" items="${valuesInRows}" varStatus="loop">
<c:if test="${loop.index %2 != 0}">
<option><c:out value="${valuesInRow}"></c:out></option>
</c:if>
</c:forEach>
</c:forEach>
</c:forEach>
</select>
<input type="submit" value="submit" />
</form>
Now I have a controller
#RequestMapping(value = "/spravochnik/list", method = { RequestMethod.POST, RequestMethod.GET })
public String getSpravochniks(Model m, #RequestParam("tableName") String tableName) {
Integer idPrepend = spravochnikService.getIdAtSpravName(tableName);
List<Spravochnik> spravList = spravochnikService.findAll(tableName);
m.addAttribute("spravList", spravList);
m.addAttribute("tableName", tableName);
m.addAttribute("idPrepend", idPrepend);
return "home";
}
It also works fine, and the resulting table (what I got from findAll) is shown with address /spravochnik/list. Question: How can I show it with address depending on what variable "tableName" i sent from the home.jsp? For example, if in the dropdown I select "employees" and pass it with the form under the name "tableName", I want the result to be shown under /spravochnik/list/employees and if I choose "vehicles" it should be "/spravochnik/list/vehicles"?
What I tried
-Adding variable to action
and in controller #RequestMapping(value = "/list/{tableName}" and tableName as #PathVariable. Actual Result: Not Found.
-The same with #RequestParam instead of Path Variable. Actual result: Not Found.

Related

How to delete an elements from a list in spring mvc

In workers.jsp I have:
....
<form action="/workers" id="personForm" method="post" >
<c:forEach items="${page.content}" var="row" varStatus="status">
<tr>
<td><input type="checkbox"/></td>
<td>${row.name}</td>
...
<td>
<input type='image' src='/pages/img/del.png' />
<input type='hidden' name="removeid" value='${row.id}'/>
</td>
</tr>
</c:forEach>
</form>
When I click on input, ${row.id} goes to:
#RequestMapping(value = "/workers", method = RequestMethod.POST)
public ModelAndView getAllByPage(#ModelAttribute("removeid") Long removeid, Model uiModel, Pageable pageable) {
if(removeid!=null) {
userService.remove(removeid);
}
...
}
But removeid in this case is always the first, that was added to the jsp page.
Besides that, how to get the array of ids, using jsp to remove many items?
Help me, please.
You can write 1 separate REST end point for deleting multiple items.
Example:
public List<Long> deleteMultiple(List<Long> toBeDeleted){
deleteService(toBeDeleted);
return toBeDeleted;
}
You can call this End point via AJAX with multiple ides & refresh your page.

spring Form binding using path not attribute not working

I have a form ,when I am using spring form tags with the path attribute,I get the following error
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'selectedPerson' available as request attribute
However when I use the regular HTML input with the name attribute I don't see any issues.
What am I doing wrong.
Here is the controller code
#RequestMapping(value="/savePersonChanges.htm",method=RequestMethod.POST)
public ModelAndView savePersonChanges(HttpSession session,#Valid #ModelAttribute(value="selectedPerson")PersonBean editedPersonBean,BindingResult bindingResult){
ModelAndView mav=new ModelAndView();
mav.setViewName(LANDING_PAGE;
mav.addObject(TAB_SELECTOR,"EditPerson");
if(session!=null){
Rpt_date=(java.util.Date)session.getAttribute("editDate");
}
if(bindingResult.hasErrors()){
mav.addObject("errorDescription",errorDescription );
}
else{
/* Call service that updates database with table changes */
try{
PersonService.updatePerson(Rpt_date, editedPersonBean
}
catch(Exception e){
log.logError("Exception while updating Person", e.toString());
}
}
return mav;
}
The form is as follows:
<form:form modelAttribute="selectedPerson" id="editPersonForm">
<table id="selectPerson">
<tbody>
<tr>
<td>
<select id="personId" name="personId" onchange="getPersonDetails(this)">
<c:choose>
<c:when test="${empty selectedPerson}">
<option value="0" selected ="selected">Select A Person</option>
<c:forEach var="personIdItem" items="${editPersonProperties.personproperties}">
<option value="${personIdItem.personId}"><spring:escapeBody>${personIdItem.personName}</spring:escapeBody></option>
</c:forEach>
</c:when>
<c:otherwise>
<c:forEach var="personIdItem" items="${editPersonProperties.personproperties}">
<c:if test="${personIdItem.personId eq selectedPerson.personId}">
<option value="${personIdItem.personId}" selected ="selected">${personIdItem.personName}</option>
</c:if>
<c:if test="${personIdItem.personId ne selectedPerson}">
<option value="${personIdItem.personId}"><spring:escapeBody>${personIdItem.personName}</spring:escapeBody></option>
</c:if>
</c:forEach>
</c:otherwise>
</c:choose>
</select>
</td>
</tr>
</tbody>
</table>
<!-- Person Details -->
<table id="editPersonTable">
<tr>
<td>First Name</td>
<td> <form:input type ="text" path="fname" value="${selectedPerson.fname}"></form:input></td>
<td>Last Name</td>
<td> <form:input type ="text" path="lname" value="${selectedPerson.lname}"/></td>
</tr>
</table>
<div class="editcancelstyle">
<input id="savebtn" type="button" onclick="savePerson()" value="Save" />
<input id="cancelbtn" type="button" onclick="cancelPersonEdits ()"value="Cancel" />
</div>
</form:form>
I understand that the path attribute will bind the field to the form. However, I keep getting the bind error. If I replace using plain HTML, the controller sees the edited values for the fname and lname for the SelectedPerson bean.
Here is your problem, when you do :
<form:... modelAttribute="selectedPerson" ...>, the selectedPerson is the key of model object mapped from the holder of both Model & View class ( ex : ModelAndView), suppose you bind a model in your controller with new ModelAndView ("yourForm", "selectedPerson", new Person()),
#RequestMapping(value = "/form")
public ModelAndView userInput() {
ModelAndView mv = new ModelAndView("personForm", "selectedPerson", new Person());
return mv;
}
now the Person is mapped with selectedPerson so when this form returned as the response from controller, your form has already been bound to the Person model, so that you use path to refer to this Person's attributes (ex. path="name" , means it refers to Person's name attribute)
In your form, on modelAttribute="selectedPerson", the selectedPerson is not binded to any models, since "selectedPerson" is never assigned to any object because you didn't do any binding first before processing ( submitting ) the form.
this is why you got
> java.lang.IllegalStateException: Neither BindingResult nor plain
> target object for bean name 'selectedPerson' available as request
> attribute.
Note that to get this binding works, add also the following on the top of your form
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
you can then populate the fields of the form (assuming you put action="result.html"):
#RequestMapping(value = "/result")
public ModelAndView processUser( #ModelAttribute("selectedPerson") Person person, BindingResult result) {
if (result.hasErrors()) {
return new ModelAndView("errorPage","message","Something goes wrong");
}
/*System.out.println(person.getName());*/
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("personResult");
modelAndView.addObject("person", person);
return modelAndView;
}

OnClick Event Not Firing Before Spring MVC Controller

I am trying to fire onClick event and Spring controller one by one.
In the click event of the button, I set a hidden field and then I want the controller to be executed AND the hidden field to be available in it. Here is my code for the JSP and the Spring Controller
JSP
<html:hidden property="MenuID" name="MenuID" id="hidMenuID" />
<c:forEach items="${menus}" var="menu" >
<tr class="cartItem">
<td align="left" >${MenuId}</td>
td align="right"><input type="text" name="menu_name" value="${Name}"/></td>
<td align="right"><input type="text" name="menu_price" value="${MenuPrice}"/></td>
<td align="right"><input type="submit" class="button" name="add_menu" value="Add" onclick="return SetMenuID();"></td>
<td align="right"><input type="submit" class="button" name="remove_menu" value="Remove" onclick="return SetMenuID();"></td>
</tr>
</c:forEach>
JavaScript
<script type="text/javascript">
function SetMenuID()
{
var MenuID = document.getElementById('hidMenuID');
MenuID.value = 'The new value';
return true;
}
</script>
Spring MVC
#RequestMapping(params = "add_menu", method = RequestMethod.POST)
public ModelAndView AddMyMenu(#RequestParam("MenuID") String menu_id, Model model, #ModelAttribute("cart") ArrayList<Menu> mycart)
{
int nMenuId = Integer.parseInt(menu_id);
Menu menu = m_arrMenus.get(nMenuId);
model.addAttribute("menus", GetMenus());
mycart.add(menu);
return new ModelAndView("edit_menu");
}
As you might guess, I am populating data from database. I have an onClick function associated with each ADD button. I set hidden field in thid function and want it to be available in my controller. But a runtime exception comes that
Error Status 400 - Required string MenuID is not present
What should I do to achieve similar result ? Thanks for any input.
#RequestParam expects a parameter my name in the request url.
Since your form is submitted and there are no request param that the action recieves. This is a reason you are getting 400 http error from server.
See the difference between #RequestParam vs #PathVariable
So either change the #RequestParam annotation or add (required = false) to it.

Adding values from a controller to a dropdown Spring MVC

In my Controller I have
#RequestMapping(value="/getCounties", method = {RequestMethod.GET},produces=MediaType.Application_JSON_VALUE)
public #Responcebody List<Counties>(#RequestParam String province){
List<Counties> county = this.xService.getCounties(county);
return county;
}
This method send the province chosen in the form down to the repository and join on the counties within that province.
In my dropdown on the form how do I return these values into the dropdown.
I currently have
<tr>
<td>
<form:select path="cdGcd" class="textbox" onclick="getCounty()">
<form:option value="-" label="Please Select"/>
<form:options path="county" items='${county}' itemValue = "countycode" itemLabel="countydescription"/>
</form:select>
</td>
</tr>
You can not return List directly form controller.
For passing data from controller to JSP you need to add data in Model and return respective JSP page.
So you need to change your method to,
#RequestMapping(value="/getCounties", method = {RequestMethod.GET})
public String getCountries(#RequestParam String province, Model model){
List<Counties> county = this.xService.getCounties(county);
model.addAttribute("county",county);
return "jsp page";
}
If you want to achieve this using AJAX then,you need to return JsonObject from controller.

Getting User's Selection From ListBox in Spring MVC/JSP/Controller

I am building my first Spring MVC application and I'm at a point where I'm a little stuck. I have a call to a database to retrieve a list of numbers(regions) and then populate them in a list box. The user should choose one of the selections and then hit the submit button. The problem is that I don't know how to capture this on the controller side. At first I thought it would have just been as easy as getting a parameter but I guess not. I don't want to build a Java class/Bean for just a number. That would seem kind of foolish. So let me share my code with you.
JSP:
<html>
<head>
<title>Spring 3 MVC Series - Contact Manager</title>
</head>
<body>
<h2>Branches</h2>
<form:form method="get" action="branch.html">
<table>
<c:if test="${not empty lists}">
<select name="regions" size="4">
<c:forEach var="listVal" items="${lists}">
<option>${listVal} </option>
</c:forEach>
</select>
</c:if>
</table>
</form:form>
<form:form method="get" action="loadbranches.html">
<c:if test="${not empty lists}">
<select name="branches" size="4">
<c:forEach var="branchVal" items="${branches}">
<option>${branchVal} </option>
</c:forEach>
</select>
</c:if>
<tr>
<td colspan="2">
<input type="submit" value="submit choice" />
</td>
</tr>
</form:form>
</body>
</html>
CONTROLLER:
#Controller
#SessionAttributes
public class BranchController {
#RequestMapping(value = "/loadbranches", method = RequestMethod.GET)
public ModelAndView getBranches()
{
//org.springframework.web.util.WebUtils.getParametersStartingWith(, prefix)
DatabaseConnect dbCon = new DatabaseConnect();
ArrayList<Object> branches = dbCon.loadData(USER SELECTED NUMBER I CANNOT FIGURE OUT);
ModelAndView model = new ModelAndView("branch");
model.addObject("branch", branches);
return model;
}
#RequestMapping("/branch")
public ModelAndView showRegions()
{
DatabaseConnect dbCon = new DatabaseConnect();
ArrayList<Object> regionIDS = dbCon.loadData("regions");
ModelAndView model = new ModelAndView("branch");
model.addObject("lists", regionIDS);
return model;
}
}
As you see it's not really that complicated of an application quite yet. I am working with databases and another Java class but it works perfectly. So is there any way to get the user selection from the listbox in a Request Parameter or something? Ideally I want this to happen when the user hits submit, so that's why there's a separate form tag besides the initial loading of the list of numbers (regions), if that makes sense. I've looked at different examples involving select path parameters but isn't there just an easy way to get the selection from the list box after the user hits the submit button? I would really appreciate help with this!
Thank you!
try with this:
#RequestMapping(value = "/loadbranches", method = RequestMethod.GET)
public ModelAndView getBranches(#RequestParam(value="branches") String branches)
{
....
}
if users can select more than 1 brach (multiple select) you can inject a List:
#RequestMapping(value = "/loadbranches", method = RequestMethod.GET)
public ModelAndView getBranches(#RequestParam(value="branches") List<String> branches)
{
....
}

Resources