dynamic spring form:select element not bound to model - ajax

I am using Spring.AjaxEventDecoration to dynamically populate a drop down on my JSP but it is throwing an error as it cannot bind to the original model. I have been researching this for a while and I do not think this is possible but it seeems like it should be hence this post.. Help me out somebody!
OK My controller dumbed down looks like this,
#Controller
#RequestMapping(value = "/cis/crimeProperty/")
public class CrimePropertyController
{
#RequestMapping(value = "/manageView", method = RequestMethod.GET)
public ModelAndView managePropertyDetails(Long propertyId) throws DAOException
{
Map<String, Object> model = new HashMap<String, Object>();
CrimePropertyVO crimePropertyVO = new CrimePropertyVO();
model.put("crimePropertyVO", crimePropertyVO);
return new ModelAndView("cis.crime.property.edit", model);
}
#RequestMapping(value = "/changeItemList", method = RequestMethod.POST)
public ModelAndView retrieveItemList(String propertyClass)
{
Map<String, Object> model = new HashMap<String, Object>();
..call service to get list of items from class..
model.put("propertyItemList", propertyItemList);
return new ModelAndView("/cis/property/crime_property_item", model);
}
}
I am using tiles so my tile definition looks like this,
<definition name="cis.crime.property.edit" template="/WEB-INF/jsp/cis/property/manage_crime_property.jsp">
<put-attribute name="itemListFrag" value="/WEB-INF/jsp/cis/property/crime_property_item.jsp"/>
My (manage_crime_property.jsp) JSP looks like so,
<form id= "changeList" action="${pageContext.request.contextPath}/smvc/cis/crimeProperty/changeItemList" method="post">
<select id="propertyClassChange" path="propertyClass">
<option value="" label="-Please Select-"/>
<option value="CLO" label="CLOTHING"/>
<option value="TOL" label="TOOLS"/>
</select>
</form
<form:form modelAttribute="crimePropertyVO" action="${pageContext.request.contextPath}/smvc/cis/crimeProperty/saveProperty" method="post">
<table class="genericOutlinedTable" style="width: 100%;">
<tr>
<td><b>Item</b></td>
<td>
<tiles:insertAttribute name="itemListFrag" flush="true" ignore="false"/>
</td>
</tr>
<tr>
<td><b>Make</b></td>
<td><form:input path="propertyMake" size="20" maxlength="20"/></td>
<td><b>Model</b></td>
<td><form:input path="propertyModel" size="15" maxlength="15"/></td>
</tr>
</form:form>
<script type="text/javascript">
Spring.addDecoration(new Spring.AjaxEventDecoration({
elementId:'propertyClassChange',
event:'onchange',
formId:'changeList',
params: {fragments: 'itemListFrag'}
}));
My (crime_property_item.jsp) JSP fragment looks like this,
<span id="itemListFrag">
<form:select path="propertyItem">
<form:option value="" label="-Please Select-">
<c:forEach var="itemList" items="${propertyItemList}">
<form:option value="${itemList.propertyCode}" label="${itemList.propertyCode}" />
</c:forEach>
</form:select>
</span>
Its all configured correctly and when I change the first drop down it calls my controller changeItemList method which returns my JSP frag and list of items to make up the options but I get a server error ...
Neither BindingResult nor plain target object for bean name propertyItemavailable as request attribute
I've tried having just the options tags in my frag but that doesn't work and I've tried using the spring:bind tag and normal select but can't get that to work either.
Many Thanks in advance for any help with this.

Related

Spring & JSP: Get value from certain input using spring controller

Can somebody help me to get value from certain input using spring controller.
I have 2 input data, and I just need a value from one of these inputs:
<input type="text" name="data01" />
<input type="text" name="data02" />
I just want to retrieve a value from "data01".
I just have used
(HttpServletRequest) request.getParameter("data01")
Or
#RequestParam(value="data01") Integer data01
but the value is null.
Can somebody help me
EDIT:
jsp:
<table>
<tr>
<input type="text" name="data01" />
<input type="text" name="data02" />
</tr>
</table>
controller:
#RequestMapping(value = "/user", method=RequestMethod.GET)
public String showAllData(ModelMap model, HttpServletRequest request) {
String retrievedData = request.getParameter("data01");
System.out.println("data= " + retrievedData);
model.addAttribute("data", new data());
return "data";
}
The retrievedData value is null.
You should be able to get the parameter using this method
<form action="/user" method="get">
<table>
<tr>
<input type="text" name="data01" />
<input type="text" name="data02" />
<input type="submit" value="submit"/>
</tr>
</table>
</form>
and in the controller
#RequestMapping(value = "/user", method=RequestMethod.GET)
public String showAllData(String data01, ModelMap model) {
// your logic here
}
and from the code you have posted. You are casting the parameter to HttpServletRequest
request.getParameter("data01") //returns String as default.
Integer.parseInt(request.getParameter("data01");
From your comment at #user1516735 answer, you cannot use it outside of the form tag. Unless you include it in the parameter from ajax or append the value of "name01" in the url as /user?name01=value
You will get the value of data01 by using the below code:
request.getParameter("data01");
Here request is of type HttpServletRequest. Make sure your input control is inside form tag.

Request method 'POST' not supported Spring MVC

I've a spring form and when I click a submit button I would like to send a list of elements previously updated.
Here's the jsp :
<form:form method="post" modelAttribute="listeBlocs" action="saveFiche">
<c:forEach var="oneBloc" items="${listeBlocs}" varStatus="status">
<h5 class="col m12 s10">${oneBloc.typeBloc}</h5>
<tr>
<td><textarea name="listeBlocs[${status.index}].blocContenu" >${oneBloc.blocContenu}</textarea></td>
</tr>
</c:forEach>
<input type="submit" value="saveFiche" />
</form:form>
Here's the destination Controller:
#RequestMapping(value="/saveFiche", method = RequestMethod.POST)
private ModelAndView updateBloc(#ModelAttribute("listeBlocs") List<Bloc> lblocs) {
BlocDAO blocDAO = new BlocDAO();
for (Bloc b : lblocs) {
System.out.println("------------\nNouveau bloc : " + b.getblocContenu());
blocDAO.update(b);
}
return new ModelAndView("confirmation_update");
}
Any suggestions ?

ModelAttribute not working with lists in spring

I want to bind a List using ModelAttribute. The list contains objects of type Transaction each of which contains transactionid (type int). This is my controller code:
#RequestMapping(value = "/approvecreditdebit.do", method = RequestMethod.POST)
public ModelAndView doActions(HttpServletRequest request,
#ModelAttribute("clc") Clc transactionList, BindingResult result,
ModelMap model) {
/*
* switch (action) { case "approve":
*/
System.out.println("Obj = " + transactionList.getClass());
System.out.println("Val = " + transactionList.getTransactionList());
Users users = new Users();
return new ModelAndView("internal","internal",users);
}
This is my jsp code:
<form:form action="approvecreditdebit.do" method="POST"
modelAttribute="clc">
<table border="1">
<tr>
<th>no</th>
<th>ID</th>
</tr>
<c:forEach items="${clc.transactionList}"
var="transaction" varStatus="status">
<tr>
<td>${status.index}</td>
<td><input name = "transaction[${status.index}].transactionId"
value="${transaction.transactionId}" /></td>
</tr>
</c:forEach>
</table>
<br>
<br>
<center>
<input type="submit" value="approve" />
</center>
</form:form>
This is the Clc class:
public class Clc{
private List<Transaction> transactionList;
public List<Transaction> getTransactionList() {
return transactionList;
}
public void setTransactionList(List<Transaction> transactionList) {
this.transactionList = transactionList;
}
}
The value of transactionList is not being set to the values received from the form. I receive the following error:
Request processing failed; nested exception is java.lang.NullPointerException
I tried searching for the solution on google and got a lot of solutions from stackoverflow but none of them seem to work.
Try something like this (notice the use of <form:input>). I just tried it on a simple Spring MVC app and it works (list is not null and has the values from the form when I try to access it in my POST method).
<c:forEach var="transaction" varStatus="status" items="${clc.transactionList}">
<tr>
<td>${status.index}</td>
<td><form:input path="transactionList[${status.index}].id" /></td>
</tr>
</c:forEach>

How to send back the model data from jsp to controller

I have a controller which sets few values to a model and sends to jsp. In jsp i need to show those values(as labels) along with additional values from user as input values. When i submit the jsp i only get valid values that user has entered and the values set earlier by controller is null.
JSP
<form:form
action="${pageContext.request.contextPath}/admin/deviceAction.html"
modelAttribute="deviceData">
<table class="gridtable" width="500px">
<tr>
<td>Device Name : </td>
<td>${deviceData.deviceName}</td>
</tr>
<tr>
<td>Model Name : </td>
<td>${deviceData.modelName}</td>
</tr>
<tr>
<td>Serial No : </td>
<td>${deviceData.serialNo}</td>
</tr>
<tr>
<td>Device Id : </td>
<td>${deviceData.deviceId}</td>
</tr>
<tr>
<td>Status : </td>
<td>${deviceData.statusCode}</td>
</tr>
<tr>
<td>Action : <span class="required">*</span></td>
<td>
<form:select path="deviceAction" >
<form:option value="" label="--- Select ---" />
<form:options items="${model.actionList}" />
</form:select>
</td>
</tr>
</table>
<input type="submit" value="Submit" id="btn_submit">
</form:form>
Controller:
public ModelAndView beforeSubmit() {
ModelAndView modelView = new ModelAndView();
DeviceData deviceData = new DeviceData();
deviceData.setDevicePk("123");
deviceData.setAccessToken("abcwetrwertewrtetr");
deviceData.setDeviceId("deferterterterterwtetetertg");
deviceData.setDeviceName("test");
deviceData.setEnrolledDate("7-8-13");
deviceData.setModelName("test1");
deviceData.setSerialNo("test2dsfgdfgdfg");
deviceData.setStatusCode("test3");
List<String> actionList = getActionList();
Map<String, List<String>> model = new HashMap<String, List<String>>();
model.put("actionList", actionList);
modelView.addObject("deviceData", deviceData);
modelView.addObject("model", model);
modelView.setViewName("admin/tokenSearchResult");
}
public ModelAndView afterSubmit() {
#ModelAttribute("deviceData") DeviceData deviceData, BindingResult result) {
logger.info("#################device datas are : " + deviceData.getDevicePk() + "###### " + deviceData.getDeviceAction());
return new ModelAndView();
}
deviceData.getDevicePk() is null
Only the drop down value is having valid value. Other values displayed in the screen are received as null.
Edit:
Till now i have found only one solution:
<form:input path="deviceName" readonly="true" />
But this way UI does not looks good. The editable and non editable values mixup in the screen. Looking for a better answer
Finally i am using hidden parameters to solve the problem.
Example:
<td>${deviceData.deviceName}</td>
is replaced by:
<td><form:hidden path="deviceName"</td>
By this way it helps me to avoid any css work(which i am not much comfortable)
If anyone get a better solution kindly post it here
You need to make them into form inputs using the Spring form tags in much the same way as you have for the form:select. If they are not editable by the user, you can always disable them.
You can simple hide those input. For example :
<input type="hidden" name="VehSeriesModelId" value="${vehDetailsVM.id }">
This way, you can get the data to the controller and the user will also not be able to edit the value. On the other hand, your form will also not show it :)

Spring form tag error

I think It is easy for a lot of peoples but I don't know what I'm doing wrong.
My controller:
#RequestMapping(value = "/novo", method = RequestMethod.GET)
public ModelAndView novoTimeSheet() {
Usuario usuario1 = new Usuario(1L,"Leandro1","ltsiciliano1#gmail.com");
Usuario usuario2 = new Usuario(2L,"Leandro2","ltsiciliano2#gmail.com");
Usuario usuario3 = new Usuario(3L,"Leandro3","ltsiciliano3#gmail.com");
List<Usuario> usuarioList = new ArrayList<Usuario>();
usuarioList.add(usuario1);
usuarioList.add(usuario2);
usuarioList.add(usuario3);
Map<String, Object> model = new HashMap<String, Object>();
model.put("usuarios", usuarioList);
return new ModelAndView("timesheetcrud/novo", "timesheetcruddto", model);
}
It's working:
<td>Usuário :</td>
<td>
<select id="usuarios" name="usuarios">
<c:forEach items="${timesheetcruddto.usuarios}" var="usuario">
<option value="${usuario.id}"><c:out value="${usuario.nome}"/></option>
</c:forEach>
</select>
</td>
But I'd like to use spring tag and I put this:
<td>Usuário :</td>
<td>
<td>
<form:select id="id_usuario" path="usuarios">
<form:option value="0" label="--- Select ---" />
<form:options items="${usuarioList}"/>
</form:select>
</td>
</td>
It isn't work:
<td>
<form:select id="id_usuario" path="usuarios">
<form:option value="0" label="--- Select ---" />
<form:options items="${usuarios}"/>
</form:select>
</td>
And It's wrong:
org.springframework.beans.NotReadablePropertyException: Invalid property 'usuarios' of bean class [java.util.HashMap]: Bean property 'usuarios' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
I'd like to know what's benefit to use spring tags instead of JSTL.
Thanks
usuarios is a list .. for a form, you need to bind an object
object will have a list with getters and setters.
object.setUsuarioList(usariolist);
model.put("object", object);
and then
<form:options items="${object.usuarioList}"/>
You can do like this
<form:select path="usuarioList">
<form:options items="${usuarios}" />
</form:select>
You can improve your code like
`<form:select path="usuarioList">
<form:option value="NONE" label="--- Select ---"/>
<form:options items="${usuarios}" />
</form:select>
`
Also please change your variable name for more suitable one like
List<Usuario> usuarios= new ArrayList<Usuario>();
usuarios.add(usuario1);
usuarios.add(usuario2);
usuarios.add(usuario3);
Map<String, Object> model = new HashMap<String, Object>();
model.put("UserList", usuarios);
It looks much good than earlier

Resources