JSP does not display table from list of objects - java

I have my controller method:
#RequestMapping(value = "/provide", method = RequestMethod.GET)
public String list(Model model) {
List<Questionare> provide = scs.getPending();
logger.info("Number of questionares: "+provide.size());
model.addAttribute("certDatas", provide);
return "ssl/provide";
}
I have added logger.info in order to check if my list is being correctly created. It is. My logger log info such as :
2014-07-04 09:46:04,118 INFO
[pl.test.QuestionareControler] Number of questionares: 163
Now I want to display those 163 object in my jsp page in form of table like this:
<c:if test="${not empty provide}">
<table class="grid" style="width: 850px;">
<tr>
<th style="width: 100px;">Name</th>
<th style="width: 100px;">Surname</th>
<th style="width: 100px;">email</th>
</tr>
<c:forEach var="person" items="${provide}">
<%
i++;
%>
<tr>
<td>${person.name}</td>
<td>${person.suername}</td>
<td>${person.smtp}</td>
</c:forEach>
</table>
</c:if>
However my jsp page does not show that table (I mean if condition is not met I suppose, because I do not even see table header)
Can anyone give me a hint what am I doing wrong?

Your model is called certDatas and not provide.
Try this:
<c:if test="${certDatas != null}">
Check out the JSP expression language here:
http://www.tutorialspoint.com/jsp/jsp_expression_language.htm

Related

Replace GET request by POST without form in JSP

So i have this JSP page which having data from table and forming a GET request to render more data on another page , by clicking one of the table line
Problem is i have to transforming it into POST method , to avoid getting information in the http request link
i know how to use post with form, but here i have to take the date from a table line and not a form
Any idea how to do that. i'm new to JSP so i don't know how to do it
<table border=0 bgcolor=#92ADC2 cellspacing=1 cellpadding=3 width=95% align=center>
<tr class=entete>
<td class=texte8 align=center> <spring:message code="nom"/></td>
<td class=texte8 align=center> <spring:message code="date_naissance"/></td>
<td class=texte8 align=center> <spring:message code="numero"/></td>
</tr>
<%
String v_Person = "";
String v_date = "";
String v_numero = "";
for (int i = 0; i < PersonListeBean.getPerson(); i++)
{
Gen_rechBean cb = PersonListeBean.getPerson(i);
v_Person = cb.getname();
v_date=cb.getdate();
v_numero=cb.getNumero();
}
%>
<tr class="<%=class_cell%>" onMouseOver="this.className='over';" onMouseOut="this.className='<%=class_cell%>';" onclick="javascript:parent['gauche'].document.location='ResultServlet?name=<%=v_Person%>&numero=<%=v_numero%>&date_naissance=<%=v_date%>">
<td class=texte7 align=left > <%=cb.getname()%></td>
<td class=texte7 align=left > <%=cb.getdate()%></td>
<td class=texte7 align=left > <%=cb.getNumero()%></td>
</tr>
</table>
<br>
<table width="95%" align="center" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="right">
<a target="corps" href="rechResult.jsp" class="rub2" </a>
</td>
</tr>
</table>
I see what are you trying to do.
The easiest way to do that is using a form. So you can call a js method when you click the
<tr onclick="myMethod()">
that you want.
The method can fill your form and send the submit. Using this you can be redirected without sending data in you url.
A basic example could be:
(Supposing these are elements printed by server-side)
<tr onclick="myMethod(<%=getName()%>, <%=getDate()%>, <%=getNumero()%>)">
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
<form id="myForm" action="targetFile.jsp" method="post">
//Hidden inputs to prevent users form touching this fields
<input type="hidden" name="name" id="data1">
<input type="hidden" name="date" id="data2">
<input type="hidden" name="numero" id="data3">
</form>
<script>
function myMethod(data1, data2, data3){
//Im gonna use jQuery. Is like javascript but quite faster to use
//Filling the form
$("#data1").val(data1);
$("#data2").val(data2);
$("#data3").val(data3);
//Submiting it
$("myForm").submit();
}
</script>
Let me know if it was helpful.
c:

Is it possible to use th-field to retrieve the value of a list in Thymeleaf?

I am creating a page in thymeleaf where I retrieve a list from my controller to mount a table, in this table there is a selection field where I retrieve a list of values ​​but I am not able to display the value that is already being retrieved of the database can help me? Please!
I already tried to use the following commands but could not recover the value:
th:field="*{valoresAtributo[__${stat.index}__].valorUsuario}"
I receive the following error: Neither BindingResult nor plain target object for bean name available as request attribute.
<table class="table table-sm table-striped table-bordered" id="dataTable">
<thead>
<tr><th colspan="4">Valores dos Atributos</th></tr>
</thead>
<tbody>
<tr class="text-black">
<td rowspan="2"> Atributo</td>
<td rowspan="2"> Local</td>
<td>Aplicação</td>
<td>Usuário</td>
</tr>
<tr>
<td id="vlAppl"></td>
<td id="vlUser"></td>
</tr>
<tr th:each="valorAtributo, stat : ${valoresAtributo}">
<td th:text="${valoresAtributo[__${stat.index}__].nomeAtributo}"></td>
<td th:text="${valoresAtributo[__${stat.index}__].valorLocal}"></td>
<td th:text="${valoresAtributo[__${stat.index}__].valorAplicaco}"></td>
<td>
<select class="form-control col-md-10" th:field="*{valoresAtributo[__${stat.index}__].valorUsuario}">
<option th:each="option : ${T(com.jequiti.JequitiIntegrador.controller.AtributoController).test(valorAtributo.sqlValidacao)}"
th:value="${{option.valorAtributo}}"
th:text="${option.significadoAtributo}">
</option>
</select>
</td>
</tr>
</tbody>
</table>
#RequestMapping(value="/seguranca/atributo/valores", params = {"atributo","siteOpt","applOpt","userOpt","aplicacao","usuario"}, method = RequestMethod.GET)
public String initAttributeValuesFormFilter(#RequestParam("atributo") Long idAtributo, #RequestParam("siteOpt") Integer idNivel1, #RequestParam("applOpt") Integer idNivel2, #RequestParam("userOpt") Integer idNivel3, #RequestParam("aplicacao") String aplicacao, #RequestParam("usuario") String usuario, Model model)
{
Integer userId = 0;
if(!Strings.isNullOrEmpty(usuario))
userId = userServiceImpl.findIdUsuarioByFantasia(usuario).intValue();
List<ValoresAtributoView> valoresAtributo = buscaValoresAtributos(idAtributo, idNivel1, idNivel2, idNivel3, 0, userId);
model.addAttribute("opUsuarios", userServiceImpl.findAllActiveUsers());
model.addAttribute("opAtributos", atributoService.findAll());
model.addAttribute("valoresAtributo",valoresAtributo);
return "/valoresAtributo";
}
I expected the field to display the value that is currently in the database and the options in the list of values.
Thank you all!
You can only use th:field if you are using th:object in a parent <form /> tag. (Which isn't clear from the HTML you posted -- but you probably are not since your are adding valoresAtributo directly as a model attribute.)
If you wish to show a preselected <option> but without using th:object and th:field you should instead use the th:selected attribute which should evaluate to true or false based on if that option should be selected. It should look something like this:
<select class="form-control col-md-10">
<option
th:each="option : ${T(com.jequiti.JequitiIntegrador.controller.AtributoController).test(valorAtributo.sqlValidacao)}"
th:value="${{option.valorAtributo}}"
th:text="${option.significadoAtributo}"
th:selected="${valorAtributo.valorUsuario == option.valorAtributo}" />
</select>
My way to retrieve list using thymeleaf:
For example list users with list of User entity getting to html page:
#GetMapping("/parsing/explorer")
public ModelAndView parsing(){
ModelAndView modelAndView = new ModelAndView("show");
modelAndView.addObject("users", generateUsersList());
return modelAndView;
}
show.html example:
<table class="w3-table-all w3-card-4">
<tr>
<th>Id</th>
<th>Name</th>
<th>Last name</th>
</tr>
<tr th:each="user : ${users}">
<td th:text="${user.getId()}"></td>
<td th:text="${user.getName()}"></td>
<td th:text="${user.getLastName()}"></td>
</tr>
</table>
So list of User (users) is assigned to the variable user in string <tr th: every = "user: $ {users}">
In the next block of code, we can also call the "User" fields the same way as java using getters, but Thymeleaf also allows you to refer to the fields: user.id/ user.name....
Determining variable in the select block:
<select name="userFromHtml" id=userId required>
<option th:each="user: ${users}">
<title th:text="${user.getLastName()} + ' ' + ${user.getName()} + ' ' + ${user.getIdIO}" th:value="${user.getId()}"/>
</option>
</select>
in this case is necessary to determine th:value in title block: th:value="${user.getId()}". So, in controller is passed variable userFromHtml with value id of selected user.
PS Although Thymeleaf allows you to define variable in direct, I prefer to use getters for data getting.

Detect innermost web element in (nested) in selenium

I am looking for getting the inner most web element in a page, when there are similar nested Webelements in a page.
Consider the example below:
<body>
<table id="level1">
<tr>
<td>
<table id="level2">
<tr>
<td>
<table id="level3">
<tr>
<td>
<p>Test</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
<table id="level1_table2">
<tr>
<td>
<table id="level2_table2">
<tr>
<td></td>
</tr>
</table>
</td>
</tr>
</table>
</body>
So when I do a search on the page by Driver.findElements by tag "table" and which have some text - "Test",
I will get 5 WebElements in total, namely - "level1", "level3" , "level1_table2" , "level2_table2"
What I want to achieve is to have a list of innermost(nested) elements which satisfy my search criteria .
So the List I should get should only have 2 WebElements namely - "level3" and "level2_table2".
I am looking something probably on the lines of recursion. Can somebody help me out.
You don't need recursion - everything you need is the proper XPath expression:
driver.findElements(By.xpath("table[not(.//table)]"))
I would use this strategy:
Search WebElements containing text Test
For each WebElement search for the first parent which match tag name is table
Here is in Java:
List<WebElement> elementsWithTest = driver.findElements(By.xpath("//*[contains(text(),'Test')]"));
List<WebElement> result = new ArrayList<>();
for(WebElement element : elementsWithTest) {
WebElement parent = element.findElement(By.xpath(".."));
while (! "table".equals(parent.getTagName())) {
parent = parent.findElement(By.xpath(".."));
}
if ("table".equals(parent.getTagName())) {
result.add(parent);
}
}
System.out.println(result);
Hope that helps.

JSTL Check if a value in an array matches second array

its me again. Basically Im checking the roles of a user once they hit a page. Its an array, lets say 1,2,3. The contents of the last column on the jsp for testing has the role #'s that are attached to each individual attachment. The last column wont be on the finished product, but I need to do some sort of IF on that array to see if any of the values in the array:
<c:forEach items = "${hotPartRoles}" var = "hpRole">
${hpRole.id}
</c:forEach>
are in the array of the attachment roles:
<c:forEach items = "${item.roles}" var = "role">
${role.id}
</c:forEach>
jsp:
<table class="data_table">
<tr>
<th>Attachments</th>
//These are the user's Roles
<c:forEach items = "${hotPartRoles}" var = "hpRole">
${hpRole.id}
</c:forEach>
</tr>
<tr>
<td class="subtable">
<table class="data_table">
<c:choose>
<c:when test='${empty attachList}'>
<tr>
<td>No Attachments</td>
</tr>
</c:when>
<c:otherwise>
<tr>
<th>Remove Attachment</th>
<th>File Name</th>
<th>File Type</th>
<th>File Size (bytes)</th>
<th>File Attached By</th>
<th>Date/Time File Attached</th>
<th>Roles</th>
</tr>
<c:forEach var="item" items="${attachList}" varStatus="loopCount">
<tr>
<td class="button">
<rbac:check operation="<%=Operation.DELETE%>">
<button type="button" onclick="javascript:delete_prompt(${item.id});">Delete</button>
</rbac:check>
</td>
<td>${item.fileName}</td>
<td>${item.fileType}</td>
<td><fmt:formatNumber value="${item.fileSize}" /></td>
<td>${item.auditable.createdBy.lastName}, ${item.auditable.createdBy.firstName}</td>
<td><fmt:formatDate value="${item.auditable.createdDate}" pattern="${date_time_pattern}" /></td>
<td>
<c:forEach items = "${item.roles}" var = "role">
${role.id}
</c:forEach>
</td>
</tr>
</c:forEach>
</c:otherwise>
</c:choose>
</table>
Now the arrays ont need to match exactly, just a value in the array of user roles is in the array of attachment roles....
I need to do the check here to determin whether or not to put a disable flag on the "delete" button:
<rbac:check operation="<%=Operation.DELETE%>">
<button type="button" onclick="javascript:delete_prompt(${item.id});">Delete</button>
</rbac:check>
</td>
<td>
Doing 2 nested for loops and having a var set to false initially, then set to true and checking on that var seemed to work
<c:forEach var="item" items="${attachList}" varStatus="loopCount">
<c:set var="dispVal" value="false"/>
<c:forEach items = "${item.roles}" var = "role">
<c:forEach items = "${hotPartRoles}" var = "hpRole">
<c:if test="${hpRole.id == role.id}">
<c:set var="dispVal" value="true"/>
</c:if>
</c:forEach>
</c:forEach>
<tr>
<td class="button">
<rbac:check operation="<%=Operation.DELETE%>">
<button type="button"<c:if test="${dispVal != 'true'}"> disabled="disabled"</c:if>
onclick="javascript:delete_prompt(${item.id});">Delete</button>
Create a custom EL function (which shall be an static method in a class, and a proper descriptor in your TLD file). For example a method with signature boolean contains(Collection collection, Object object). And then call it as <c:if test="x:contains(list, object)">

Where do I specify default values for a Java bean that holds meta data to format a Month Calendar

I have a Java bean which stores what I am calling meta data (week start day, any holidays) that my JSP view will use to display a Calendar Month. I am using JSTL, not EL, since company only has jsp 1.2
<table align="center" border="1" cellpadding="3" cellspacing="0" width="100%" class="tableInternalBorder">
<tbody>
<tr>
<th width="180px" class="optionYellow">Sun</th>
<th width="180px">Mon</th>
<th width="180px">Tue</th>
<th width="180px">Wed</th>
<th width="180px">Thu</th>
<th width="180px">Fri</th>
<th width="180px" class="optionYellow">Sat</th>
</tr>
<c:forEach var="week" begin="1" end="${calendar.totalWeeks}" varStatus="status">
<tr>
<c:forEach var="cell" begin="${1+7*(week-1)}" end="${7+7*(week-1)}" step="1" varStatus="status"><c:set var="dayNo" value="${cell-calendar.weekStartDay+1}" />
<c:choose><c:when test="${calendar.weekStartDay>cell || (cell-calendar.weekStartDay+1)>calendar.totalDays}">
<td height="50" class="<c:out value="${calendar.cellColor[cell]}" />">* </td>
</c:when>
<c:otherwise>
<td valign="Top" height="75px" class="<c:out value="${calendar.cellColor[dayNo]}" />"><span class="calDayNo"><c:out value="${dayNo}" /></span><span class="calDayName"> <c:out value="${calendar.holidayName[dayNo]}" /></span><br>
<c:forEach var="dayEvent" items="${eventMap.byDay[dayNo]}" varStatus="status"><div class="eventContent" ><c:out value="${status.count}" />) <c:out value="${dayEvent.event_type_name}" />: <c:out value="${dayEvent.eventUser.lastName}" /></div></c:forEach></td>
</c:otherwise>
</c:choose>
</c:forEach>
</tr>
</c:forEach>
</tbody>
</table>
In this bean I also storing an array of month names so that I can do this in my view.
<c:forEach var="month" items="${calendar.monthList}" varStatus="status">
<option value="<c:out value="${status.index}" />" <c:if test="${month == calendar.monthName}">selected</c:if>><c:out value="${month}" /></option>
</c:forEach>
My question is do I set the month list in my javabean or the method which generates the meta data for the calendar. Here is the method that returns to meta data bean (with logic removed for clarity). Should I set it in this method, this class, or in the Java bean. If it should go in the Java bean, I am not sure how to do that.
public EBCalendar getCalendarMeta (HttpServletRequest request) {
//Get any request parameters
int iYear = STKStringUtils.nullIntconv(request.getParameter("iYear"));
int iMonth = STKStringUtils.nullIntconv(request.getParameter("iMonth"));
EBCalendar ebCal = new EBCalendar();
// Get the current month and year
Calendar ca = new GregorianCalendar();
int curYear = ca.get(Calendar.YEAR);
int curMonth = ca.get(Calendar.MONTH);
// If request parameters are null use todays calendar
if (iYear == 0) {
iYear = curYear;
iMonth = curMonth;
}
ebCal.setCurYear(curYear);
ebCal.setCurMonth(curMonth);
ebCal.setSelYear(iYear);
ebCal.setSelMonth(iMonth);
ebCal.setTotalWeeks(iTotalweeks);
ebCal.setTotalDays(totalDays);
ebCal.setWeekStartDay(weekStartDay);
ebCal.setAbvMonthName(abvMonthName);
ebCal.setMonthName(monthName);
ebCal.setMonthList(monthList);
ebCal.setHolidayName(getEBHolidayNameInMonth(iYear, iMonth));
ebCal.setCellColor(getWeekendHolidayColorMap(iYear, iMonth));
return ebCal;
}
EDIT: Here is what I did based on the accepted answer
I changed this:
<c:forEach var="month" items="${calendar.monthList}" varStatus="status">
<option value="<c:out value="${status.index}" />" <c:if test="${month == calendar.monthName}">selected</c:if>><c:out value="${month}" /></option>
</c:forEach>
to this:
<c:set var="months">January,February,March,April,May,June,July,August,September,October,November,December</c:set>
<c:forTokens var="month" items="${months}" delims="," varStatus="status">
<option value="<c:out value="${status.index}" />" <c:if test="${month == calendar.monthName}">selected</c:if>><c:out value="${month}" /></option>
</c:forTokens>
I think the question here is should you put the default with the view or the model. I am a bigger fan of putting the default with the model because you may have a different jsp that will have different defaults in the future. Then you have to go back and change the default in your model. I vote for in JSP. :)

Categories