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

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>

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 to change the scriplet to JSTL display string array

how to change the scriplet to JSTL
<%String sentenceArray[] = (String[])request.getAttribute("displaySentenceArray"); %>
<% for (int i=0; i< sentenceArray.length;i++){ %>
<p> The Result IS : <%=sentenceArray[i] %> </p>
<%} %>
I am new to JSTL
Your JSTL should look like this
<c:forEach var="sentence" items="${requestScope.displaySentenceArray}" >
<p> The Result IS :<c:out value="${sentence}"></c:out></p>
</c:forEach>
Here requestScope.displaySentenceArray will get the whole array from request.'sentence'will be a single element of array, <c:forEach> tag will iterate the array and <c:out> will print the element to JSP.

Checking if a value is contained in an array in JSP

I have an if statement like so:
<c:if test="${id == '1' || id == '2' || id == '3' || id == '4'}">
and I'm wondering if there is a way that I can simplify this by checking if id is contained within an array/list/set, sort of like
<c:if test="${id isContainedIn {'1','2','3','4'}}">
Obviously this isn't correct, but it demonstrates what I am looking for. Is there anything similar to this? Thanks!
If you can create a String that contains your list, then you could use something like the following code.
<%# taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix = "fn" uri = "http://java.sun.com/jsp/jstl/functions" %>
<%
pageContext.setAttribute("listString", "1234");
%>
<c:set var="id" value="3"/>
<c:if test='${fn:contains(listString, id)}'>
Yes id is contained
</c:if>
You can do something like this:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%
ArrayList list = new ArrayList();
list.add("one");
list.add("two");
list.add("three");
%>
<c:set var="list" value="<%=list%>" />
<html>
<body>
My list is ${list}<br/>
<c:if test='${fn:contains(list, "two")}'>
My list contains two <br/>
</c:if>
<c:if test='${fn:contains(list, ",")}'>
My list contains ,
</c:if>
</body>
</html>
The output for the code above is
My list is [one, two, three]
My list contains two
My list contains ,
I hope it helps someone.

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

JSTL arraylist. Value is empty

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。

Categories

Resources