Cant print ArrayList in JSP from Servlet - java

So I have this simple list made in a java servlet, and I would like to display it within a JSP page. Servlet code:
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
ArrayList<String> myList = new ArrayList<String>();
myList.add("cat");
myList.add("dog");
myList.add("frog");
request.setAttribute("list", myList);
String nextJSP = "/index.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);
}
}
However it won't print in the following JSP file:
<%#page import="java.io.*" %>
<%#page import="java.net.*" %>
<%#page import="java.util.*" %>
<%#page import="java.util.List" %>
<%#page import="java.util.ArrayList" %>
<%#page language="java" import="myPackage.*" %>
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<% List<String> myList = (ArrayList<String>)
request.getAttribute("list"); %>
<% out.println(myList); %>
</body>
</html>
Any help would be appreciated!

The HTTP 500 error is come from this line:
<% List<String> myList = (ArrayList<String>)
request.getAttribute("list"); %>
It has extra (),remove it and make it as below,then the HTTP 500 will diappear,instead you will got a warning Type safety:Unchecked cast from Object to ArrayList<String>,but it doesn't matter
For how to print the ArrayList,if you have import JSTL tag in your jsp page,you can do it as below,previous answer has metioned:
<c:forEach var="li" items="${list}">
<c:out value="${li}"/>
</c:forEach>
If you do not want to use JSTL, you can use java code to print it:
<% for(int i=0;i<myList.size();i++){
out.println(myList.get(i));
} %>

Okay, your are having a HTTP 500 error message and I would suspect that it is coming from the following part of your code:
<% out.println(myList); %>
Keep in mind that the out used here is not System.out and does not behave the same way. Instead try (replace the line mentionned above by the following):
<% Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
out.println(<iterator.next());
}
%>

You could use core tag foreach as
<c:forEach var="list" items="${YourList}">
<c:out value="${list}"/>
</c:forEach>

Related

Identifier expected after this token

I got a error : Identifier expected after this token
Syntax error on token "tag", Identifier expected after this token
And here is my code:
<%# page import="photoshare.Picture" %>
<%# page import="photoshare.PictureDao" %>
<%# page import="photoshare.HREF_AND_IMGSRC" %>
<%# page import="photoshare.ToolsDao" %>
<%# page import="org.apache.commons.fileupload.FileUploadException" %>
<%# page import="java.util.ArrayList" %>
<%# page import="java.util.List" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Get POP Tags</title></head>
<body>
<h1>With Photos with popular Tags:</h1>
<%
String tagName = request.getParameter("tag");
List<String> popTags = new ArrayList<String>();
ToolsDao toolsDao = new ToolsDao();
popTags = toolsDao.getPopularTags();
for (tag:popTags) {%>
<a href="popTags.jsp?tag=<%= tagName %>">tagName <a>
<%}
List<HREF_AND_IMGSRC> tagPhotos = toolsDao.getHrefAndImgSrcFromTag(tagName);
for (HREF_AND_IMGSRC photo:tagPhotos) {
int pictureId = photo.getPictureID();
int selectedAlbumID = photo.getAlbumID();
String selectedAlbum_id = Integer.toString(selectedAlbumID);
%>
<td><a href="picture.jsp?id=<%= pictureId %>&album_id=<%= selectedAlbum_id%>">
<img src="/photoshare/img?t=1&picture_id=<%= pictureId %>"/></a></td>
<%
}
%>
Click here to Main Page<br>
</body>
</html>
I am finding some reasons for this but nothing similar, can anybody help me to figure out what is the problem for this specified error?
I found the problem which is :
for (tag:popTags) {%>
<a href="popTags.jsp?tag=<%= tagName %>">tagName <a>
<%}
I have to declare the type of the tag in popTags list such as:
for (String tag:popTags) {%>
<a href="popTags.jsp?tag=<%= tagName %>">tagName <a>
<%}

How to set parameters in XSL stylesheet with the help of Transformer object when i have my xml generated dynamically in jsp

I need to set Parameters in my XSL stylesheet.I am retrieving all values in a list and using it to create XML dynamically in jsp. So there is no external xml file created in this process..But now I need to set variable in XSLt stylesheet. But as there is no xml file created so I am finding it difficult to use transform Object.Here is MY code
<%# page contentType="text/xml" %>
<%#page import="java.util.ArrayList,aj.model.BriefBoardDetail,
javax.xml.transform.Transformer,javax.xml.transform.TransformerFactory,
javax.xml.transform.stream.StreamSource" %>
<% ArrayList<BriefBoardDetail> list =(ArrayList)
request.getAttribute("boardList");
int countofPages =(Integer) request.getAttribute("countOfPages");
int pageNumber = (Integer) request.getAttribute("currentPageNumber");
Transformer transformer =
TransformerFactory.newInstance().newTransformer(new
StreamSource("/xslt/indexPageStyle.xsl"));
transformer.setParameter("currentPage" , pageNumber);
transformer.setParameter("lastPage" , countofPages);
transformer.transform(???, ???);//what parameter i need to set here?
%>
<?xml-stylesheet type="text/xsl" href="xslt/indexPageStyle.xsl"
version="1.0" encoding ="UTF-8" ?>
<AlgorithmHome>
<%
for(BriefBoardDetail bbs : list) {
%>
<subject id = '<%=bbs.getBoardId() %>' >
<name> <%=
bbs.getBoardName() %></name>
<description> <%=
bbs.getDescription() %></description>
</subject>
<%} %>
</AlgorithmHome>
So I need to set countOfPages and pageNumber in indexPageStyle.xsl.But as xml is generated dynamically in this jsp so what I need to set as XMLSource and outputTarget in transformer.transform(XMLSource, outputTarget) if i need to display it in browser.
I made some changes in above code and it worked fine..
<%#page contentType ="text/html; charset=ISO-8859-1" %>
<%#page import ="java.util.ArrayList,aj.model.BriefBoardDetail" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>
<% ArrayList<BriefBoardDetail> list =(ArrayList) request.getAttribute("boardList");
Integer countofPages =(Integer) request.getAttribute("countOfPages");
Integer pageNumber = (Integer) request.getAttribute("currentPageNumber");
%>
<c:set var="xmldata">
<AlgorithmHome>
<%
for(BriefBoardDetail bbs : list) {
%>
<subject id = '<%=bbs.getBoardId()%>'>
<name> <%=
bbs.getBoardName() %></name>
<description> <%=
bbs.getDescription() %></description>
</subject>
<%}%>
</AlgorithmHome>
</c:set>
<c:import url="/xslt/indexPageStyle.xsl" var="xslt"/>
<x:transform xml="${xmldata}" xslt="${xslt}">
<x:param name ="currentPage" value="${param:pageNumber}"/>
<x:param name ="lastPage" value="${param:countofPages}"/>
</x:transform>
Its all working fine.
But now i want to pass both countofPages and pagenumber to my XSL stylesheet.But I am not able to pass it.I google and all i got was everyone passed String inside value tag.I am so confused ..Please tell me hoe to pass a value

how to add arraylist in Jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%=new Date() %>
<%
ArrayList al = new ArrayList();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
%>
<select>
<option value="<%=al%>"></option>
</select>
</body>
</html>
This is my code i want to add Arraylist in drop down in Jsp I dont know how to Bind arraylist in html obtion or drop down please help me i have tried Much but unable to do this .
You have to use JSTL <forEach> to iterate through the elements and add it to the select-option . Probably make the List a scoped attribute . Populate the List object in the servlet, set it in request/session scope and forward the request to this JSP. Remember you can populate the List in the JSP itself and use pageScope to refer it , but that will be bad design in my opinion.
<select>
<c:forEach var="element" items="${al}">
<option value="${element}">${element}</option>
</c:forEach>
</select>
Here , al is the name of the attribute which stores the List in probably request or session scope.
Use JSTL in project :
Download the JSTL 1.2 jar .
Declare the taglib in JSP file for the JSTL core taglib.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
If you want to use just the scriptlets(which is bad off course) :
<%
List<String> al = new ArrayList<String>();
al.add("C");
..........
...........
%>
<select>
<% for(String element: al) { %>
<option value="<%=element%>"><%=element%></option>
<% } %>
</select>
The above code will work if you have defined the List as List<String> , or else you need to cast the element to String.
Read How to avoid Java Code in JSP-Files?.
EDITED
Try this:
<%
ArrayList al = new ArrayList();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
%>
<select>
<% for(int i = 0; i < al.size(); i++) {
String option = (String)al.get(i);
%>
<option value="<%= option %>"><%= option %></option>
<% } %>
</select>
</body>
</html>
Take a look at the tag in the core JSTL library.
Store the arraylist in pageScope.myList and loop as follows:
<select>
<c:forEach items="${pageScope.myList}" var="item" varStatus="status">
<option value='${item}'></option>
</c:forEach >
</select>
This is preferable than using scriptlets which are not considered good practice
Try this: declare your arraylist in between <%! … %>
<%! ArrayList al = new ArrayList(); %>

Send data from servlet to jsp

I tried to send a list from my servlet to a jsp page. This is the servlet code:
Query q = new Query("post").addSort("time", SortDirection.DESCENDING);
PreparedQuery pq = datastore.prepare(q);
QueryResultList<Entity> results = pq.asQueryResultList(fetchOptions);
for (Entity entity : results) {
System.out.println(entity.getProperty ("content"));
System.out.println(entity.getProperty ("time"));
}
req.setAttribute("postList",results);
req.getRequestDispatcher("/tublr.jsp").forward(req, resp);
The jsp code:
<%
QueryResultList<Entity> result = request.getAttribute("postList");
for (Entity entity : results) {
<b> IT WORRRKKKK !!! </b> <br>
}
%>
But I get an error
EDIT : I added
<%#page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# page import="java.util.List,com.google.appengine.api.datastore.Query.SortDirection,com.google.appengine.api.datastore.*" %>
And now i get a new error
An error occurred at line: 37 in the jsp file: /tublr.jsp Type
mismatch: cannot convert from Object to QueryResultList .....
Caused by:
org.apache.jasper.JasperException: Unable to compile class for JSP:
I m do it for the school and we have to di it like this now , we have to use java in the jsp page.
1) You need to add import statements at top of the JSP.
Example:
<%# page import="java.util.List" %>
2) It is NOT good practice to have Java code directly embedded in JSP
Read more here on SO Wiki
Don't do any coding on JSP page. There is a JSTL library for this kind of stuff, and to iterate and display stuff you should use forEach tag:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
and for loop
<x:forEach select="${postList}" var="item">
... code
</x:forEach>
You forgot <% %> for the html code
<%
QueryResultList<Entity> result = request.getAttribute("postList");
for (Entity entity : results) {
%> <b> IT WORRRKKKK !!! </b> <br><%
}
%>
Have you imported QueryResultList in your jsp?
You need to cast list obtained from request.getAttribute("postList") to QueryResultList.
<%
QueryResultList<Entity> result =(QueryResultList)request.getAttribute("postList");
for (Entity entity : result) {
// Your code goes here You can use <%= %> to print values.
// <b> IT WORRRKKKK !!! </b> <br>
}
%>
For more about expression

Displaying array values in jsp

I have following two array in my code
List<Double> centralityList = (List<Double>) request
.getAttribute("centralityList");
List<String> labelList = (List<String>) request
.getAttribute("labelList");.
Now I have six string values and corresponding 6 double values of the string in these two array. My question is how to display them in tabular format in my JSP?Is this possible
For Example:
label list contains [a,b,c,d,e]
centrality list contains- [4,6,8,9,0]
So now I want to display output like:
label list centrality list
a 4
b 6
c 8.
. .
etc
Yes of course you can. You can use scriplets but they are not recommended. Instead use JSTL.
Try this out:
Have this at top of your JSP:
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
And code for displaying data
<c:forEach begin="0" end="${fn:length(centralityList) - 1}" var="index">
<tr>
<td><c:out value="${centralityList[index]}"/></td>
<td><c:out value="${labelList[index]}"/></td>
</tr>
</c:forEach>
try this code
<%
List<Double> centralityList = (List<Double>) request
.getAttribute("centralityList");
List<String> labelList = (List<String>) request
.getAttribute("labelList");
String myString="";
%>
<table>
<tr><td>
<%
for(int i = 0; i < labelList.size(); i++)
{
out.println((String)labelList.get(i));
}
%>
</td><td>
<%
for(int i = 0; i < centralityList.size(); i++)
{
out.println((double)centralityList.get(i));
}
%>
</td>
</table>
You can achieve this eaisly by using JSTL which is even more easy and far better way but as in your code I didn't find any evidence of using JSTL , so this is the way for now
You can use JSTL tags and iterate through this-
<c:forEach var="Array" items="userNames">
// do something with the element
</c:forEach>
Use this in your jsp page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

Categories