Spring mvc pagination how to get result - java

I already have posted this post yesterday..but nobody answerd it..
I am using spring mvc framework.
I want to do pagination like the below picture:--
So I have done :--
#RequestMapping(value = "/detailssection/id",method=RequestMethod.GET)
public #ResponseBody String showthedetails(Map<String, Object> map, HttpServletRequest request) throws IOException{
//I want to display 5 details per page
int recordsPerPage = 5;
//It will count total no of records(like 300 records are there)
int totalnoOfrecords = viewService.TotalnoOfRecoredsbanglains1();
//If the totalnoOfrecords=300 then page noumber will be 300/5=60 that means 1,2....60
int pagenumbers = (int) Math.ceil(totalnoofrecords * 1.0 / recordsPerPage);
map.put("detail", new Detail());
map.put("noOfPages", pagenumbers);
map.put("detailList", viewService.viewDetails());
return "detailssection";
}
and my jsp page is like:--
<div id= "part1">
<div id= "details">
<p>${detail.description}</p>
</div>
</c:forEach>
<%--For displaying Previous link except for the 1st page --%>
<c:if test="${currentPage != 1}">
Previous
</c:if>
<%--For displaying Page numbers.
The when condition does not display a link for the current page--%>
<c:forEach begin="1" end="${noOfPages}" var="i">
<c:choose>
<c:when test="${currentPage eq i}">
${i}
</c:when>
<c:otherwise>
${i}
</c:otherwise>
</c:choose>
</c:forEach>
<%--For displaying Next link --%>
<c:if test="${currentPage lt noOfPages}">
Next
</c:if>
</div>
But I am not getting any page numbers.its only showing the "previous page" section.Its like:--
what am I doing wrong?Is there any problem in jsp page??

Let's start from the begining.
If you have a map on your requestScope, suppose it is MyMap with the following keys: details, noOfPages and detailList, to access it's values by keys, the syntax is the following:
<c:forEach begin="1" end="$MyMap['noOfPages']" var="i" varStatus="loop">
<c:choose>
<c:when test="${currentPage eq i}">
${i}
</c:when>
<c:otherwise>
${loop.index}
</c:otherwise>
</c:choose>
</c:forEach>

Related

How can I save all the data from different textboxs in an array, using JSTL?

I want to recieve any number of textbox values, and save it to an array with JSTL if it's possible.
I generate all the texbox where numberAsked can be any number.
<c:if test="${param.buttonSend != null}">
<form action="index.jsp" method="post">
<c:forEach var = "i" begin = "1" end = "${param.numberAsked}">
<input type="text" name="textbox[]" class="form-control">
</c:forEach>
<button type="submit" name="buttonSave">Save</button>
</form>
</c:if>
Now I want to save all the textboxs in an array.
<c:if test="${param.buttonSave != null}">
<c:set var="data" value="${request.getParameterValues(textbox)}"/>
<c:forEach var = "item" items="${param.data}">
<c:out value="${item}"/>
</c:forEach>
</c:if>
But, it doesn't work, how can I save all the data from all the generated textboxs in an array?.
Here is a demonstration JSP.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<form method="post">
<c:forEach var = "i" begin = "0" end = "5">
<input type="text" name="textbox">
</c:forEach>
<button type="submit" name="buttonSave">Save</button>
</form>
<c:set var="data" value="${paramValues.textbox}"/>
<c:forEach var = "item" items="${data}">
${item}
</c:forEach>

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.

Writing java code in thymeleaf

In Short
I was tring to create a tag for pagination in thymleaf.
In Detail
I already have an example for this in jsp.but I am stuck in the middle.I am not sure how to write this code in thymleaf.
I googled about it,but the results were very confusing.
Example jsp :
<%#tag description="Extended input tag to allow for sophisticated errors" pageEncoding="UTF-8" %>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#tag import="net.megalytics.util.Href" %>
<%#attribute name="currentPage" required="true" type="java.lang.Integer" %>
<%#attribute name="totalPages" required="true" type="java.lang.Integer" %>
<%#attribute name="totalItems" required="true" type="java.lang.Long" %>
<%
if (totalPages > 1) {
String currentUrl = request.getAttribute("javax.servlet.forward.request_uri").toString();
String queryString = "";
if (request.getQueryString() != null)
queryString = request.getQueryString();
Href newUrl = new Href(currentUrl + "?" + queryString);
newUrl.addParameter("page", String.valueOf(currentPage));
String url = "";
Integer totCount =0;
%>
<div class="pull-right">
<ul class="pagination">
<c:choose>
<c:when test="<%=currentPage == 0%>">
<li class="disabled">First</li>
</c:when>
<c:otherwise>
<li class="">
<%
newUrl.removeParameter("page");
newUrl.addParameter("page", "0");
url = newUrl.toString();
%>
First
</li>
</c:otherwise>
</c:choose>
<c:forEach var="count" step="1" begin="1" end="<%= totalPages %>">
<c:choose>
<c:when test="${(currentPage == count-1)}">
<li class="disabled">${count}</li>
</c:when>
<c:otherwise>
<li>
<%
newUrl.removeParameter("page");
newUrl.addParameter("page", String.valueOf(totCount));
url = newUrl.toString();
%>
${count}
</li>
</c:otherwise>
</c:choose>
<%
totCount++;
%>
</c:forEach>
<c:choose>
<c:when test="<%=currentPage == (totalPages-1) %>">
<li class="disabled">Last</li>
</c:when>
<c:otherwise>
<li class="">
<%
newUrl.removeParameter("page");
newUrl.addParameter("page", String.valueOf(totalPages - 1));
url = newUrl.toString();
%>
Last
</li>
</c:otherwise>
</c:choose>
</ul>
</div>
<%
}
%>
Can anyone help me? I am stuck...
Thymeleaf or neither any framework doesn't encourage you to write logic inside your views. This is poor coding practice.
You can do the following instead.
Create a bean method with the logic below
#Bean("urlUtil")
class UrlUtil {
String doSomthing() {
newUrl.removeParameter("page");
newUrl.addParameter("page", "0");
return newUrl.toString();
}
}
Access the bean inside the thymeleaf layout
<a th:href="#{__${#urlUtil.doSomthing()}__}">First</a>
Refer http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#the-springstandard-dialect

Nesting choose within choose using JSP taglibs

<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<td colspan="1" width="100">
<c:choose>
<c:when>
</c:when>
<c:when>
</c:when>
<c:when>
<c:choose>
<c:when></c:when><c:otherwise><c:when></c:when></c:otherwise>
</c:choose>
</c:when>
<c:otherwise>
</c:otherwise>
</c:choose>
</td>
Is there a limit to nesting choose within a choose, such as this?
EDIT: the JSP compiler keeps complaining I have NO end tag if I put another <c:when></c:when> within the otherwise.
As far as I know there is an error:
<c:when>
<c:choose>
<c:when></c:when><c:otherwise><c:when></c:when></c:otherwise>
</c:choose>
</c:when>
should be:
<c:when>
<c:choose>
<c:when></c:when>
<c:otherwise></c:otherwise>
</c:choose>
</c:when>
you cannot have a nested when tag inside otherwise directly, to do that you need another choose tag:
<c:when>
<c:choose>
<c:when></c:when>
<c:otherwise>
<c:choose>
<c:when></c:when>
</c:choose>
</c:otherwise>
</c:choose>
</c:when>
The JSP will be translated to Java, where function will be created for each custom tag like this
private boolean _jspx_meth_c_005fwhen_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fchoose_005f0, javax.servlet.jsp.PageContext _jspx_page_context)
throws java.lang.Throwable {
javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_005fwhen_005f0 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_005fwhen_005f0.setPageContext(_jspx_page_context);
_jspx_th_c_005fwhen_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fchoose_005f0);
// /index1.jsp(4,2) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_c_005fwhen_005f0.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${true}", java.lang.Boolean.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)).booleanValue());
int _jspx_eval_c_005fwhen_005f0 = _jspx_th_c_005fwhen_005f0.doStartTag();
if (_jspx_eval_c_005fwhen_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n");
out.write(" ");
int evalDoAfterBody = _jspx_th_c_005fwhen_005f0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_005fwhen_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.reuse(_jspx_th_c_005fwhen_005f0);
return true;
}
_005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.reuse(_jspx_th_c_005fwhen_005f0);
return false;
}
Having nested functions will increase the function stack levels. By default JVM has decent stack size, and should cause any issue for you/
Eventually you could run out of stack space. Otherwise no.
Common sense and readability is the closest limit you might encounter. Are you having some issues with this code?

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