JSTL arraylist. Value is empty - java

i was searching for the same problem as mine, but i didn't find anything. This is my problem:
I have ArrayList which includes beans. My beans is class 'Row'. There are setters and getters.
This is method from Database class:
public ArrayList<Row> getDatalist() {
datalist = new ArrayList<Row>();
try {
String query = "SELECT * FROM ...";
ResultSet r = s.executeQuery(query);
while(r.next()) {
Row row = new Row();
row.setLocation(r.getString(4));
row.setVolume(r.getInt(3));
row.setTime(r.getTime(5));
row.setDate(r.getDate(5));
datalist.add(row);
}
} catch (SQLException e) {
e.printStackTrace();
}
return datalist;
}
My servlet:
ArrayList<Row> rows = db.getDatalist();
request.setAttribute("rows", rows);
request.getRequestDispatcher("/main.jsp").forward(request,response);
And at least 'main.jsp':
<c:forEach var="row" items="${rows}">
<c:out value="${row.location}"></c:out>
</c:forEach>
The problem is that ${row.location} is empty. My page source:
<c:forEach var="row" items="[webservice.model.Row#1e41769, webservice.model.Row#1bd0815, webservice.model.Row#15dd716, webservice.model.Row#1d40d08]">
<c:out value=""></c:out>
</c:forEach>
Any idea? Thanks a lot.

Well, your page source indicates the problem clearly: the c tags aren't interpreted by the container. This means that you forgot to declare the c taglib at the top of the JSP:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

be sure you have set this:
<%# page isELEnabled ="true"%>
to make el expression enable。

Related

JSTL iterate list

I have this class:
public class Orders{
private Integer id;
private String name;
//getters/setters
}
In controller I pass a List<Orders> to jsp:
#RequestMapping(value = "/orders")
public ModelAndView orders(){
List<Orders> orders = ...//get list from db
//print list in console
orders.forEach(e -> System.out.println(e.getId() + " - " + e.getName()));
//print -> 1 - name1 ; 2 - name2
return new ModelAndView("orders", "orders", orders);
}
In jsp use it like this:
${orders.size()}
<c:forEach items="${orders}" var="order">
<c:out value="${order.getId()}"></c:out>
</c:forEach>
In browser at inspect(html code) looks like this:
"2"
<c:foreach items="[com.web.entity.Orders#21e16dd6,
com.web.entity.Orders#52a33913]" var="order">
<c:out value=""></c:out>
</c:foreach>
I tested in controller by printing list in console and everything is right.
Why in jsp is not printed?
Could you please provide more details (controller code, html page tags ...).
Still I've some point to share with you :
Use always a toString method in your Entity/POJO.
Use order.id instead of order.getId()
Make sure you have JSTL core tag in the top of your HTML page :
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Try to have a simple c:out tag:
<c:out value="${order.id}"/>

How could i print after i used request.getAttribute in a jsp?

In my servlet, i have:
List list = new ArrayList();
....
request.getSession().setAttribute("list",list);
RequestDispatcher dispatcher=request.getRequestDispatcher("result.jsp");
dispatcher.forward(request,response);
And in my result.jsp file, i wanted to print out the checks on website, so i tried :
String[] str = (String[])request.getAttribute("list");
But there is a error said
org.apache.jasper.JasperException: java.lang.ClassCastException: java.util.ArrayList cannot be cast to [Ljava.lang.String;
So what should i do to print the list?
Thank you.
Actually list is of type ArrayList not an Array, so try this instead :
<%
ArrayList<String> list = (ArrayList<String>) request.getSession().getAttribute("list") ;
//do something ...
%>
And make sure you are allowing your jsp to access to the Session using : <%# page session="true" %>
However as #JBNizet said it's so preferable to use jstl expression over than Java code in the jsp pages :
in the servlet :
List<String> list = new ArrayList<>();
request.setAttribute("list" , list);
RequestDispatcher dispatcher=request.getRequestDispatcher("result.jsp");
dispatcher.forward(request,response);
In the Jsp :
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<c:forEach items="${list}" var="element">
//use the element here...
${element}
</c:forEach>

Calling a method from servlet in a JSP page,method with parameters from that JSP page

I tried different ways to call that method, but none worked. My problem is that I want to give as variable parameters from that jsp page where I calling that method
those are my varabiles:
<c:forEach begin="0" end="21" step="1" var="time">
<c:forEach begin="${0}" end="${6}" step="1" var="day">
.............
</c:forEach>
.........................
</c:forEach>
<c:set var="sala" value='<%=session.getAttribute("room").toString()%>'/>
<c:set var="z" value='<%=Integer.parseInt(session.getAttribute("next").toString())%>'/>
Here I tried to call my method
<c:set var="getData" value='<%= try{
mysql a =new mysql();
a.getData( %>${time},${day}<%+%>${z},${sala}<%);
}catch (Exception ex){ return ex.toString();} %>'/>
we can't use the jstl variables directly in scriptlet tags.
We need to use the below syntax :
pageContext.getAttribute(String name);
According to your example,
<%
try
{
mysql a =new mysql();
String time=pageContext.getAttribute("time");
String day=pageContext.getAttribute("day");
String sala=pageContext.getAttribute("sala");
String getData=a.getData(time,day,sala);
}
catch (Exception ex){ return ex.toString();}
pageContext.setAttribute("getData", getData);
%>
<c:out value="${getData}"/>

In Spring MVC - model.addAttribute usage for dynamic data and how to place the data in jsp file

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

how to update large information in excel to oracle database using jsp or servlet or java

in my project i have a excel sheet which contains the marks,id,credits in large number... i need to upload into database from excel file.... iam using apache poi to read and update but iam getting error...
DB_Connection.java
package DB;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DB_Connection
{
// private String datasize;
private Connection con;
public DB_Connection()
{
try
{
String conUrl="jdbc:oracle:thin:#localhost:1521:xe";
String userName="SYSTEM";
String pass="raje";
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection(conUrl,userName,pass);
}
catch(Exception s)
{
System.out.println(s);
}
}
public Connection getConn()
{
return con;
}
public void setConn(Connection con)
{
this.con = con;
}
}
readExcel.jsp:
<%#page language="java" import="java.sql.*" contentType="text/html" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<%# page import ="java.util.Date" %>
<%# page import ="java.io.*" %>
<%# page import ="java.io.FileNotFoundException" %>
<%# page import ="java.io.IOException" %>
<%# page import ="java.util.Iterator" %>
<%# page import ="java.util.ArrayList" %>
<%# page import ="org.apache.poi.hssf.usermodel.HSSFCell" %>
<%# page import ="org.apache.poi.hssf.usermodel.HSSFRow" %>
<%# page import ="org.apache.poi.hssf.usermodel.HSSFSheet" %>
<%# page import ="org.apache.poi.hssf.usermodel.HSSFWorkbook" %>
<%# page import ="org.apache.poi.poifs.filesystem.POIFSFileSystem" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<jsp:useBean id="connection" class="DB.DB_Connection" scope="application">
<jsp:setProperty name="connection" property="*"/>
</jsp:useBean>
<%!
Connection con;
PreparedStatement ps=null;
public static ArrayList readExcelFile(String fileName)
{
/** --Define a ArrayList
--Holds ArrayList Of Cells
*/
ArrayList cellArrayListHolder = new ArrayList();
try{
/** Creating Input Stream**/
FileInputStream myInput = new FileInputStream(fileName);
// System.out.print("myInput");
/** Create a POIFSFileSystem object**/
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
/** Create a workbook using the File System**/
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
/** Get the first sheet from workbook**/
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
/** We now need something to iterate through the cells.**/
Iterator rowIter = mySheet.rowIterator();
while(rowIter.hasNext())
{
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
ArrayList cellStoreArrayList=new ArrayList();
while(cellIter.hasNext())
{
HSSFCell myCell = (HSSFCell) cellIter.next();
cellStoreArrayList.add(myCell);
}
cellArrayListHolder.add(cellStoreArrayList);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return cellArrayListHolder;
}%>
<%
String fileName="C://Documents and Settings//raje//Desktop//JGRESULTS1.xls";
ArrayList dataHolder=readExcelFile(fileName);
//Print the data read
//printCellDataToConsole(dataHolder);
con= connection.getConn();
ps=con.prepareStatement("insert into sample2 values(?,?,?,?)");
int count=1;
ArrayList cellStoreArrayList=null;
//For inserting into database
for (int i=1;i < dataHolder.size(); i++)
{
cellStoreArrayList=(ArrayList)dataHolder.get(i);
ps.setString(1,((HSSFCell)cellStoreArrayList.get(0)).toString());
ps.setString(2,((HSSFCell)cellStoreArrayList.get(1)).toString());
ps.setString(3,((HSSFCell)cellStoreArrayList.get(2)).toString());
ps.setString(4,((HSSFCell)cellStoreArrayList.get(3)).toString());
count= ps.executeUpdate();
System.out.print(((HSSFCell)cellStoreArrayList.get(3)).toString() + "\t");
}
count++;
//For checking data is inserted or not?
if(count>0)
{ %>
Following details from Excel file have been inserted in student table of database
<table>
<tr>
<th>Student's Name</th>
<th>Class</th>
<th>external</th>
<th>credits</th>
</tr>
<% for (int i=1;i < dataHolder.size(); i++) {
cell StoreArrayList=(ArrayList)dataHolder.get(i);%>
<tr>
<td><%=((HSSFCell)cellStoreArrayList.get(0)).toString() %></td>
<td><%=((HSSFCell)cellStoreArrayList.get(1)).toString() %></td>
<td><%=((HSSFCell)cellStoreArrayList.get(2)).toString() %></td>
<td><%=((HSSFCell)cellStoreArrayList.get(3)).toString() %></td>
</tr>
<%}
}
else
{%>
<% out.print("not successfull");
} %>
</table>
</body>
</html>
output:
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: An exception occurred processing JSP page /readExcel.jsp at line 98
95: {
96: cellStoreArrayList=(ArrayList)dataHolder.get(i);
97: ps.setString(1,((HSSFCell)cellStoreArrayList.get(0)).toString());
98: ps.setString(2,((HSSFCell)cellStoreArrayList.get(1)).toString());
99: ps.setString(3,((HSSFCell)cellStoreArrayList.get(2)).toString());
100: ps.setString(4,((HSSFCell)cellStoreArrayList.get(3)).toString());
101: count= ps.executeUpdate();
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:553)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:457)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:3 93)
root cause
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
java.util.ArrayList.RangeCheck(ArrayList.java:547)
java.util.ArrayList.get(ArrayList.java:322)
org.apache.jsp.readExcel_jsp._jspService(readExcel_jsp.java:175)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
You'll get more and better help if you actually post the error.
This code is a mess. It's doing too much:
POI to read and parse spreadsheets
JSP to display
JDBC to persist
I'd recommend decomposing it into pieces as separate classes that you can develop, test, and put aside.
No one should be writing JSPs with scriptlets. That's a discredited 1999 style. Better to learn JSTL and add some servlets.
UPDATE:
Here's the cause:
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
java.util.ArrayList.RangeCheck(ArrayList.java:547)
You've assumed that an array element is present, but the JVM disagrees with you.
Here's the essence of what you did wrong:
List<String> values = new ArrayList<String>();
values.add("element one");
System.out.println(values.size()); // this will print 1
System.out.println(values.get(100)); // there's only one element in the list, but you tried to access 100.
Error! Figure out where your code did something like this and you'll have it.
From looking at your code and the stack trace it looks like you are getting an IndexOutOfBoundsException because the row of cells in the cellStoreArrayList is only of length 1. I would recommend looking at your spreadsheet to ensure that every row you are reading in has 4 columns since this constraint is hardcoded.
On a related note, if you are going to hardcode array indices you should surround it in some kind of exception catching mechanism.
As someone pointed out: what you do is a very bad practice...
However, the current problem is most likely, that the row you are trying to read a cell from is not long enough, so the (note: array backed ) list runs out of bounds.
To be prepared for this situation, I'd do it this way:
cellStoreArrayList=(ArrayList)dataHolder.get(i);
for(int i=1;i<4;i++) { // I'd use a loop even for fixed number of iterations, I vigorously hate duplication
if(cellStoreArrayList.size()>=i) { // check for row to be long enough --> no ArrayOutOfBounds anymore HSSFCell cell = (HSSFCell)cellStoreArrayList.get(i-1);
if(cell!=null) { // check for null: no NullPointerException anymore...
ps.setString(i,cell.toString());
}
else {
ps.setString(i,"");
}
//ps.setString(i,cell==null?"":cell.toString()); //this is good too, but a bit probably less readable
}
}
Notes:
use generics! the List could have had a <HSSFCell> generic type, eliminating the need for a cast, and solving quite some possibilities for mistakes and errors
don't store the name fo the implementation in the variable name! cellStoreArrayList = bad! cellStoreList = good

Categories

Resources