I have a table and I want the lines to be numbered.
In my jsp, I have something like that:
<%! int i = 0; %>
<c:forEach items="${clients}" var="client">
<tr>
<td align="center"><%= ++i %></td>
<td><c:out value="${client.nomPrenom}"/></td>
....
My problem is when I refresh the page, variable i is not reset to 0. It continues to ++
What do I do wrong?
You could do that using jstl as follows , as scriplets are not advised over decades
<c:forEach items="${clients}" var="client" varStatus="loop">
<tr>
<td align="center"><c:out value="${loop.index}" /></td>
<td><c:out value="${client.nomPrenom}"/></td>
</tr>
</ c:forEach>
see How to avoid Java code in JSP files? to learn more on using the jstl and EL
Your JSP is translated to servlet by server container. Every time you refresh your page _jspService is called.
Translation of JSP to servlet code :
public class HelloWorld2$jsp extends HttpJspBase {
//code declare inside <%! %> method goes here
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
{
// code declare inside <% %> method goes here
}
}
Instead of
<%! int i = 0; %>
Use Below Code:
<% int i = 0; %>
Related
I am retrieving answer from ans column by using jdbc and showing it into a jsp page in a form of a table, if ans column is null or empty then I have to give a user edit link, but if ans column has a value then I'm going to show answer but the problem is if-else condition is not working. Please help me to solve this, My code is given below:
<div class="table-responsive">
<table class="table center-aligned-table">
<thead>
<tr class="text-primary">
<th>Question No</th>
<th>Question Name</th>
<th>Answer:</th>
<th> </th>
<th> </th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<%
try{
int oopa=1;
//String nme=(String)session.getAttribute("vname7");
DbCon cc=new DbCon();
Connection onn=cc.fun();
Statement stt=onn.createStatement();
ResultSet r=stt.executeQuery("select ques,ans from postquestion;");
while(r.next()){
%>
<tr class="">
<td><center><%=oopa++%></center></td>
<td><%=r.getString(1)%></td>
<%
if(r.getString(2)==null)
{
%>
<td>Edit</td>
<%
}
else
{
%>
<td><%=r.getString(2)%></td>
<%
}
%>
<td> </td>
</tr>
<%
}
}
catch(Exception vjin){
System.out.println("I am vjin: "+vjin);
vjin.printStackTrace();
}
%>
</tbody>
</table>
</div>
You might get empty values from your results. So check if r.getString(2) is empty or not, null differs from empty value.
More over, JSP is just a view component, writing DAO code in JSP is not a good practice.
Thanks
You can check for null values using wasNull() method of ResultSet.For example like below :
<%
//getting value of column in "a"
String a = r.getString(2);
//checking if resultset return null i.e a is null then do below:
if(r.wasNull())
{
%>
<td>Edit</td>
<%
}
else
{
%>
<td><%=r.getString(2)%></td>
<%
}
%>
I have two arrays:
<%String TXTfileArray[] = (String[])request.getAttribute("txt");%>
<%String TXTContentArray[] = (String[])request.getAttribute("content");%>
the data in the array is repeated.
by using the following statement in JSP i can output the array in the table:
<table border="1">
<tr>
<th>txt name</th>
<th>txt content</th>
</tr>
<% for (int i=0; i< TXTfileArray.length;i++){ %>
<tr>
<td> <%=TXTfileArray[i] %> </td>
<td> <%=TXTContentArray[i] %> </td> <%} %>
</tr>
</table>
how to remove the repeated element in the table?
Please do not hard code, as the array is not fixed. the array is depended on the other process.
You could try adding each element in a Set, and if it already exists don't add it to the table:
<% Set<String> a = new HashSet<>();
for (int i=0; i< TXTfileArray.length;i++)
if (a.add(TXTfileArray[i]) { %>
<tr>
<td> <%=TXTfileArray[i] %> </td>
<td> <%=TXTContentArray[i] %> </td> <%} %>
Although I think JB Nizet's suggestion of using LinkedHashSet<SomeClass> is probably a better way to do it.
Hi I am new to Java world and I am trying to make my own web application with Spring MVC. Now, I am going to read a text file in my local directory, for example, the text file like this:
TestData_FileOne.txt
1,100
2,200
3,300
4,400
5,500
The result I would like to present in a browser page like this (in a table) :
1 2 3 4 5
100 200 300 400 500
so I implemented 1) Controller , 2) Model , and 3)View(.jsp file).
**1) My Controller and 2)Model ([Q1] [Q2]) **
#Controller
public class TestController {
#RequestMapping("/testMVC")
public String testmvc(Model model){
String dirString = "C:/Users/Me/Documents/Test/";
Path testFile;
List<String> testData;
testFile = Paths.get( dirString + "TestData_FileOne.txt");
try {
testData = Files.readAllLines(testFile, StandardCharsets.UTF_8);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//return "unable to read...";
return "unable to read...";
}
// ====== changes from here based on Aeseir's answer========
List<String> dataNum = new ArrayList<String>();
List<String> data = new ArrayList<String>();
for(int i=0; i<testData.size()-1;i++){
dataNum.add(testData.get(i).split(",")[0]);
data.add(testData.get(i).split(",")[1]);
}
model.addAttribute("dataNum", dataNum);
model.addAttribute("data", data);
// ======= changes until here ==============
return "testMVC";
}
}
(Read the text file works fine when I checked System.out.println part)
2) testMVC.jsp file
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<table>
<thread>
<tr>
<th>Table with dynamic data from model</th>
</tr>
</thread>
<tbody>
<c:forEach var="dataNumValue" items="${dataNum}"> [items added but.. Q5]
<tr>
<td>
${dataNumValue}
</td>
</tr>
</c:forEach>
<c:forEach var="dataValue" items="${data}"> [items added but.. Q5]
<tr>
<td>
${dataValue} --- [Q2']
</td>
</tr>
</c:forEach>
</tbody>
</table>
So..I know Q1/Q1' should be match, and Q2/Q2' as well.
1) however, I am confused about the object in model.addAttribute("", object); in Q1, Q2? and addAttribute is the right choice among model attributes?
2) Do I need var="dataNum" and var="data" in Q3, Q4 and did I do correctly?
I appreciate any advice if I made mistake.
Extra Question
so I have updated Controller code and jsp file like the above after Aeseir's answer (Thanks!!) but I have warning in jsp file after I added items then warning (Q5) and of course, the page is not presented.
[Q5]: warning : "items" does not support runtime expressions
I searched for the warning, then advices like check the jstl version - should be above version 1.0 - My jstl version is 1.2. so shouldn't be any problem....
Can you check my changes part? and What else could cause this warning except jstl version?.
Solution for extra question 5
#taglib directive should be like this in jsp file:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> => /jsp was missing in the middle
This #taglib correction + code changes the above based on Aeseir's answer works all fine!
Q1 and Q2
You were almost there. Model will pass most data you put into it. Its up to your rendering page to determine how to display it.
And you will need to change the types to arrays since you want to output multiple strings.
List<String> dataNum = //populate accordingly
List<String> data = // populate accoridngly
model.addAttribute("dataNum", dataNum);
model.addAttribute("data", data);
Q3 and Q4
Yes you do but you need to complete it this way:
<c:forEach var="dataNumValue" items="${dataNum}">
<tr>
<td>
${dataNumValue}
</td>
</tr>
</c:forEach>
<c:forEach var="dataValue" items=${data}>
<tr>
<td>
${dataValue}
</td>
</tr>
</c:forEach>
Hope that helps
I am developing web application.In jsp page I am iterating a list using Scriptlets tags. But I want to execute the same result in JSTL. How Can I do?
Here list contain Column names of Data Base.
Here eList contain Table data (values of a table)
Below is My JSP code:
<table border="1" cellpadding="5" cellspacing="5">
<tbody>
<tr>
<th>SNO</th>
<c:forEach var="column" items="${list}">
<th> ${column} </th>
</c:forEach>
</tr>
//For above list JSTL exectude successfully but while doing below list is not possible
<%List eList =(Vector)request.getAttribute("list1");
Integer s1 = (Integer) request.getAttribute("sno");
Iterator it = eList.iterator();
while (it.hasNext()) {
%>
<tr> <td><%=++s1%></td><%
Object[] row = (Object[]) it.next();
for (int k = 0; k < row.length; k++) {
%>
<td> <%=row[k]%></td>
<% }%>
</tr>
<%
}
%>
</tbody>
</table>
Servelt code
GetTableData .java:
public class GetTableData extends HttpServlet
{
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
Query query1 = entityManager.createNativeQuery("select * from "
+ schemaName + "." + tableName + "");
totalNumberOfRecords = query1.getResultList().size();
query1.setFirstResult(newPageIndex);
query1.setMaxResults(numberOfRecordsPerPage);
List list1 = query1.getResultList();
System.out.println("testszenario" + testszenario.size());
System.out.println(testszenario);
request.setAttribute("list1", list1);
request.getRequestDispatcher("/TableResult.jsp").forward(request,
response);
}
}
How can I do that one with JSTL tags.Thanking you very much
The list1 is in request scope so you can just iterate as you did, for printing SR.No. you can make use of LoopTagStatus
<c:forEach var="data" items="${list1}" varStatus="loop">
<td> ${loop.count} </td>
<td> ${data} </td>
</c:forEach>
Remember
${loop.index} starts from 0
${loop.count} starts from 1
See also
JSTL core
How to avoid Java Code in JSP-Files?
Do like Below
<c:forEach var="data" items="${list1}" varStatus="loop">
<tr>
<td> ${sno+1} </td>
<c:forEach var="innerData" items="${data}">
<td> ${innerData} </td>
</c:forEach>
<c:set var="sno" value="${sno+1}"/>
</tr>
</c:forEach>
Include a jstl jar and include them in jsp page like shown below
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>.............
then by using
<c:forEach items="${values that are set in any scope}" var="any variable">......
..
Please refer to below code.
<c:forEach var="data" items="${list1}" varStatus="loop">
<tr>
<td> ${loop.count} </td>
<c:forEach var="innerData" items="${data}">
<td> ${innerData} </td>
</c:forEach>
</tr>
</c:forEach>
I have an important question but firs sorry for my english, I only know the basic. Well my problem is that I have an error passing an ArrayList from a servlet to jsp page:
<% ArrayList<Usuario> u= (ArrayList<Usuario>)session.getAttribute("listado");%>
<table align="left" cellpadding="0" cellspacing="1">
<tr bgcolor="blue">
<td>Usuario</td><td>Nombre</td>
<td>Apellido</td><td>Clave</td>
</tr>
<% for(int i=0;i<u.size();i++){ %>
<% Usuario usuario = u.get(i); %>
<tr>
<td> <%= usuario.getUsuario() %></td>
<td> <%= usuario.getNombre() %></td>
<td> <%= usuario.getApellido() %></td>
<td> <%= usuario.getClave() %></td>
</tr>
<%} %>
</table>
That's how I'm doing this but I receive an error in:
<% for(int i=0;i<u.size();i++){ %>
What I'm doing wrong? also my servlet Method is like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd;
try {
Connection cn = MySQLConnection.obtenerConexion();
String sql = "select * from tb_usuario";
PreparedStatement ps = cn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
ArrayList<Usuario> listado = new ArrayList<Usuario>();
while (rs.next()){
Usuario usu = new Usuario(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4));
listado.add(usu);
}
request.setAttribute("listado", listado);
request.getRequestDispatcher("/listado.jsp");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I hope you could help me!
You should not use scriptlets in your JSP. You should use EL and tags in your JSP.
e.g.
${listado}
You are setting the variable in request object while retrieving from session, which is not present hence the issue.
You are setting the attribute in doPost as below":
request.setAttribute("listado", listado);
You are retrieving the attribute in your JSP as below":
<% ArrayList<Usuario> u= (ArrayList<Usuario>)session.getAttribute("listado");%>
Please use the same scope session or request in both places.
you are setting the value in to request scope
request.setAttribute("listado", listado);
but then trying to access it in session scope.
session.getAttribute("listado");
due to this u might get a null pointer exception in
u.size()...
try to access it in request scope
request.getAttribute("xxxxxx")
try to avoid adding java code inside JSP whihc is a bad practice. use EL and JSTL instead. you can to the casting part inside the code too..
scriptletsare discouraged to use in ajsp page, use JSTL tags instead. use c-foreach tag to iterate over your arrayList in your jsp page. and you are setting an attribute in a request scope and trying to get it in session scope in your jsp.
heres the link which explains c-foreach tag