Send data from servlet to jsp - java

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

Related

Cant print ArrayList in JSP from Servlet

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>

loop an ArrayList of Object into my JSP?

I look for the way to make a loop to show a list of people's in my JSP, but nothing displays when I make the code below:
My ArrayList "resultArray" consists of objects "Person":
[Person{id=1, namePerson='Tom'},
Person{id=2, namePerson='Paul'},
Person{id=3, namePerson='Mary'},
Person{id=4, namePerson='Luky'}]
Here is my code into my JSP file:
<%# page import="mypath.Person" %>
<%# page import="java.util.ArrayList" %>
<html>
<%
ArrayList<Person> userList=(ArrayList<Person>) request.getAttribute("resultArray");
if(userList != null) {
for(Person u : userList) {
u.getId();
u.getNamePerson();
}
}
%>
You are just calling the method and you are not writing anything to outstream.
You should consider writing it to see in the page. For example
out.write(u.getId());
Maybe you can use something like this:
<c:forEach items="${userList}" var="item">
${item.namePerson}<br>
</c:forEach>

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

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