get map from jsp-form spring - java

I am new in Spring MVC, and I have a problem.
I'm sending to FORM LinkedHashMap, and it's showing great.
model.addAttribute("resultForm", resultForm);
Part of my jsp:
<c:forEach items="${resultForm}" var="resultMap" varStatus="status">
<tr id="tableRow" class="table-row">
<td>
${resultMap.key}
</td>
<td>
<select name="resultMap['${resultMap.key}']" class="espa-config-select">
<option selected value ="${resultMap.value}">${resultMap.value}</option>
<c:forEach items="${mainParams}" var="item2">
<c:if test="${item2.key == resultMap.key}">
<c:forEach items="${item2.value}" var = "q">
<c:if test="${resultMap.value != q}">
<option value="${q}"> ${q} </option>
</c:if>
</c:forEach>
</c:if>
</c:forEach>
</select>
</td>
</tr>
</c:forEach>
Now I need to get it back
Here is part of Controller
#RequestMapping( value = "espa/update", method = RequestMethod.POST )
public String save(#ModelAttribute("resultForm") LinkedHashMap<String,String> resultForm) {
System.out.println("resultMap post "+resultForm.toString());
if (resultForm!=null){
//resultForm.put("Port", port);
espaService.setConfiguration(selectedDevice, resultForm);
LOG.debug("Saving configuration: {} /nPort{}",resultForm, selectedDevice);
}
return "redirect:/espa";
}
But it is empty!
How can I fix it?

In your select you are using the name "resultMap". The name attribute needs to correlate to the Model Attribute, which you are called "resultForm".

Related

html thymeleaf directly post in a select option

I want directly push the selected option. But i dont find a solution. Maybe u can help me?
I have a table with a list of entities. And i will offer a select for every entity. But i want to save the selection directly.
I need the entry.id and the cat.id.
This is what i have.
<form class="myForms" id="uploadCheckerForm" method="post" th:action="#{uploadStatus}">
<table>
<tr th:replace="fragment/form-fragments::checkerMainLine()"></tr>
<tr th:each="entry : ${uploadList}">
<td><select th:id="transactionCategory" th:name="transactionCategory">
<option>Select</option>
<option th:each="cat : ${transactionCategoryList}"
th:text="${cat.name}" th:value="${cat.id}">
</option></select>
</td>
<td th:text="${entry.Comment}">
</tr>
</table>
</form>
What have i to do, that it directly post this infos?
Thanks for help!
I would append some unique identifier of your entry to the name of your <select> with some sort of separator and then accept form data on backend to a Map. Kinda like this:
HTML
<form class="myForms" id="uploadCheckerForm" method="post" th:action="#{uploadStatus}">
<table>
<tr th:replace="fragment/form-fragments::checkerMainLine()"></tr>
<tr th:each="entry : ${uploadList}">
<td><select id="transactionCategory" th:name="'transactionCategory_' + ${entry.guid}">
<option>Select</option>
<option th:each="cat : ${transactionCategoryList}"
th:text="${cat.name}" th:value="${cat.id}">
</option></select>
</td>
<td th:text="${entry.Comment}">
</tr>
</table>
</form>
Controller
#PostMapping( "/uploadStatus" )
public String uploadStatus( #RequestParam Map<String, Long> params ) {
for ( Map.Entry<String, Long> entry : params.entrySet() ) {
if ( entry.getKey().startsWith( "transactionCategory_" ) ) continue; // skip
Long entryId = Long.parseLong( entry.getKey().replace( "transactionCategory_", "" ) ); // get entry ID
SomeDAO.instance().uploadStatus( entryId, entry.getValue() ); // do what you need to do with id of entry and chosen category ID
}
return "redirect:/";
}

how to iterate through jstl list to match condition in java spring mvc

I have one jsp page. I am passing 2 model objects from spring controller.
asset (gets selected asset).
assets (get all assets)
I want to set option selected if condition matches.
My code
<table>
<tr>
<td>Asset Id :</td>
<td>
<form id="getAssetForm" method="get">
<select id="assetid" name="assetid" onchange="submitForm(this);">
<c:if test="${not empty assets}">
<c:forEach items="${assets}" var="assetsproperties">
<c:choose>
<c:when test="${not empty asset}">
<c:forEach items="${asset}" var="assetobj">
<c:choose>
<c:when test="${assetobj.id} == ${assetsproperties.id}">
<option value="${assetobj.id}" selected>${assetobj.name}</option>
</c:when>
<c:otherwise>
<option value="${assetsproperties.id}">${assetsproperties.name}</option>
</c:otherwise>
</c:choose>
</c:forEach>
</c:when>
<c:otherwise>
<option value="${assetsproperties.id}">${assetsproperties.name}</option>
</c:otherwise>
</c:choose>
</c:forEach>
</c:if>
</select>
</form>
</td>
</tr>
<tr>
<td>Name :</td>
<td><input type="text" name="assetname" value="<c:if test="${not empty asset}"><c:forEach items="${asset}" var="assetobj">${assetobj.name}</c:forEach></c:if>"></td>
</tr>
<tr>
<td>Model Number :</td>
<td><input type="text" name="assetmodelnumber" value="<c:if test="${not empty asset}"><c:forEach items="${asset}" var="assetobj">${assetobj.modelNumber}</c:forEach></c:if>"></td>
</tr>
<tr>
<td>Rating (1 to 5 ):</td>
<td><input type="text" name="assetrating" value="<c:if test="${not empty asset}"><c:forEach items="${asset}" var="assetobj">${assetobj.rating}</c:forEach></c:if>"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="Save" value="Update">
</tr>
</table>
<script type="text/javascript">
function submitForm(a){
var e = document.getElementById("assetid");
var assetid = e.options[e.selectedIndex].value;
var assetnametxt = e.options[e.selectedIndex].text;
var assetnameElement = document.createElement("input");
assetnameElement.type = "hidden";
assetnameElement.name = "assetname";
assetnameElement.value = assetnametxt;
var form = document.getElementById('getAssetForm');
form.appendChild(assetnameElement);
form.setAttribute('action', "get-asset");
form.submit();
}
</script>
here is my controller code :
#RequestMapping(value="/get-asset", method = RequestMethod.GET)
public String showGetAssetPage(ModelMap model,
#RequestParam("assetid") int assetid,
#RequestParam("assetname") String assetname){
System.out.println("inside showGetAssetPage() ");
List<Asset> asset = service.getAsset(assetid, assetname);
model.addAttribute("asset", asset);
List<Asset> assets = service.getAssets();
model.addAttribute("assets", assets);
return "update-asset";
}
I want to show selected asset on page load.
How to match condition using jstl?
You should have a boolean field isSelected in your Asset model. In your controller,set the isSelected property in all the assets object. Using this only all assets and checking isSelected property you can set is as selected.

Java Jstl foreach

I'm having a few problems with some JSTL code. The thing is that i'm trying to compare the id of the user that logged in with the id from the reservation class which has a foreign key of the user id.And after doing that i'm trying to populate the page with update links based on the reservation id.
Here's the code of what i tried but i can't find a way to make it work.
<table>
<tr>
<th>Reservation Id</th>
<th>Data CheckIn</th>
<th>Data CheckOut</th>
<th>Numar Persoane</th>
<th>Numar Camere</th>
<th>Action</th>
<%
List<ReservationBean> theReserv = (List<ReservationBean>) request.getAttribute("RESERVATION_LIST");
%>
<% int userId = (Integer) request.getSession().getAttribute("userId"); %>
<c:forEach var="tempReservation" items="${RESERVATION_LIST}">
<!-- set up a link for each res -->
<c:url var="tempLink" value="UserControllerServlet">
<c:param name="command" value="LOAD"/>
<c:param name="reservationId" value="${tempReservation.reservationId}"/>
</c:url>
<c:url var="deleteLink" value="UserControllerServlet">
<c:param name="command" value="DELETE"/>
<c:param name="reservationId" value="${tempReservation.reservationId}"/>
</c:url>
</c:forEach>
<% for(ReservationBean res : theReserv){
/* int userId = (Integer) request.getSession().getAttribute("userId"); */
if(userId == res.getUserId()){ %>
<tr>
<td> <%= res.getReservationId() %> </td>
<td> <%= res.getDataCheckin() %> </td>
<td> <%= res.getDataCheckout() %> </td>
<td> <%= res.getNrPersoane()%> </td>
<td> <%= res.getNrCamere() %> </td>
<td>Update
|
<a href="${deleteLink}"
onclick="if(!(confirm('Are you sure you want to delete this reservation?'))) return false">Delete</a>
</td>
</tr>
<%}%>
<%}%>
</tr>
</table>
In the second for i'm comparing the id of the user that logged in with the id of the user from the reservation class but of course the updated links will contain the last value of the first for and i don't know how to do what i did in pure java with JSTL to have only one for and get the correct values of the update link or delete ones.Do you guys have any clue on how to do that?
I've tried something like this
<table>
<tr>
<th>Reservation Id</th>
<th>Data CheckIn</th>
<th>Data CheckOut</th>
<th>Numar Persoane</th>
<th>Numar Camere</th>
<th>Action</th>
<%
List<ReservationBean> theReserv = (List<ReservationBean>) request.getAttribute("RESERVATION_LIST");
%>
<% int userId = (Integer) request.getSession().getAttribute("userId"); %>
<c:forEach var="tempReservation" items="${RESERVATION_LIST}">
<!-- set up a link for each res -->
<c:if test="${tempReservation.userId}" == userId >
<c:url var="tempLink" value="UserControllerServlet">
<c:param name="command" value="LOAD"/>
<c:param name="reservationId" value="${tempReservation.reservationId}"/>
</c:url>
<c:url var="deleteLink" value="UserControllerServlet">
<c:param name="command" value="DELETE"/>
<c:param name="reservationId" value="${tempReservation.reservationId}"/>
</c:url>
<tr>
<td>${tempReservation.reservationId}</td>
<td>${tempReservation.dataCheckin}</td>
<td>${tempReservation.dataCheckout}</td>
<td>${tempReservation.nrPersoane}</td>
<td>${tempReservation.nrCamere}</td>
<td>Update
|
<a href="${deleteLink}"
onclick="if(!(confirm('Are you sure you want to delete this student?'))) return false">Delete</a>
</td>
</tr>
</c:if>
</c:forEach>
But that if condition doesn't work or i don't know how to compare jstl code with java code
Edit2: I made it work! You had to compare it something like this
<c:if test="${tempReservation.userId == userId }">
Thanks for help!

jstl loop through a list in an object

I am building a Spring MVC web app, I have an object called NodeRel which is defined as below:
public class NodeRel {
private String fromNodeId;
private String toNodeId;
private String fromNodeName;
private String toNodeName;
private List<QuotaValueOnTime> fromNodeSend;
private List<QuotaValueOnTime> toNodeSend;
//getters and setters omitted
}
In the server side code, i obtained a list of NodeRels and bind it to the model. In the jsp page, I want to first loop through the List and then inside it, I want to loop though List. My jsp code:
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th class="center">Count</th>
<th>relation</th>
<th colspan='25'>Detail</th>
</tr>
</thead>
<tbody>
<c:forEach var="nodeRel" items="${nodeRelInfo}" varStatus="stc">
<tr>
<td rowspan="3">${stc.count}</td>
<td rowspan="3">${nodeRel.fromNodeName} --> ${nodeRel.toNodeName}</td>
<td>\</td>
<c:forEach var="x" begin="0" end="23" step="1">
<td>${x}</td>
</c:forEach>
</tr>
<tr>
<td>Send_A</td>
<c:forEach var="node" items="${nodeRelInfo.fromNodeSend}">
<td>${node.sumval}</td>
</c:forEach>
</tr>
<tr>
<td>Send_B</td>
<c:forEach var="x" begin="0" end="23" step="1">
<td>${x}</td>
</c:forEach>
</tr>
</c:forEach>
</tbody>
</table>
</div>
My code doesn't work and I got java.lang.NumberFormatException: For input string: "fromNodeSend" near the second loop:
<c:forEach var="node" items="${nodeRelInfo.fromNodeSend}">
<td>${node.sumval}</td>
</c:forEach>
What is wrong with my code?
Note that the variable ${nodeRelInfo} represents the List and the variable ${nodeRel} represents the each item you work with.
Thus the item you want to loop in the second loop is ${nodeRelInfo.fromNodeSend}. Change the second name of variable looped:
<c:forEach var="node" items="${nodeRel.fromNodeSend}">
<td>${node.sumval}</td>
</c:forEach>
It works on the same logic like Java for-each loop.
for (List nodeRel: nodeRelInfo) {
// bla blaa
for (String node: nodeRel.fromNodeSend()) {
System.out.println(node);
}
}
change your second loop like this because your variable name in parent loop is nodeRel not nodeRelInfo
<c:forEach var="node" items="${nodeRel.fromNodeSend}">
<td>${node.sumval}</td>
</c:forEach>

how can I change special jsp scriptlet to jstl?

i want to change all scriptlets in my jsp pages to jstl,
how can i change this code to jstl
<% Map validationResults = (HashMap) request.getAttribute("validationResults");%>
<% if (validationResults != null) {
if (validationResults.containsKey("userName")) { //how can i chage this line to jstl ?
%>
<%=((ValidationResult) (validationResults.get("userName"))).getDetails()%> //how can i chage this line to jstl too ?
<%}%>
<%}%>
MY JSTL
<c:set var="validationResults" value="validationResults" scope="request"></c:set>
<c:if test="validationResults != null">
//how can i change the code of map here?
</c:if>
and another problem with ArrayList which contains list of Group object , in the loop i want to get each Group object and check a specific method inside Group object , how can I reach to these method through jstl??
I want to change this code
<%List<Group> allGroupList = new ArrayList<Group>();
allGroupList = (ArrayList) request.getAttribute("groups");%>
<% for (int index = 0; index < allGroupList.size(); index++) {%>
<%Group aGroup = (Group) allGroupList.get(index);%>
<label ><%=aGroup.getGroupEName()%></label>
<%if (aGroup.isIsUserGroup()) {%>
<input type="checkbox" name="group" value="<%=aGroup.getGroupNo()%>" CHECKED />
<%} else {%>
<input type="checkbox" name="group" value="<%=aGroup.getGroupNo()%>" />
<%}%>
<%}%>
here's my changed code:
<jsp:useBean id="GroupBean" class="ps.iugaza.onlineinfosys.entities.Group" type="ps.iugaza.onlineinfosys.entities.Group" scope="reqeust">
<c:set var="allGroupList" value="groups" scope="request"></c:set>
<c:forEach var="grp" items="${allGroupList}" varStatus="status">
//?????? what should i do ?
</c:forEach>
For The First Part
JSTL and EL only work with method that follows Java Bean convention. If you really wanna go this route, then you can loop around your map.
<c:forEach items="${requestScope.validationResults}" var="mapEntry" varStatus="index">
<c:if test="${mapEntry.key == 'userName'}">
<tr>
<td>${mapEntry.value.details}</td>
</tr>
</c:if>
</c:forEach>
The other way can be just get userName from the map, and check for if its null or not, and then do whatever you like. This is indeed a better idea.
<c:if test="${requestScope.validationResults['userName'] != null}">
<tr>
<td>${requestScope.validationResults['userName'].details}</td>
</tr>
</c:if>
For The Second
<c:forEach var="grp" items="${requestScope.groups}" varStatus="status">
<label>${grp.groupEName}</label>
<input type="checkbox" name="group" value="${grp.groupNo}" ${grp.isUserGroup ? 'checked' : ''} />
</c:forEach>
As for no 1), You would have to populate your request through an action/controller, and have a JSTL script that iterates through your map as follows:
Warning: Untested
<c:if test="${requestScope.validationResults != null}">
<c:forEach var="entry" items="${requestScope.validationResults}">
<c:if test="${entry.key == 'userName'}">
Result: ${entry.value.details};
</c:if>
</c:forEach>
</c:if>
Adeel Ansari answered number 2 for you.

Categories

Resources