Jsp get and parse url to view JAVA - java

I have passed this url parameter.
?previous=[{user_id=3,%20email=ivanov#test.eu,%20budget_limit=23.00,%20budget_remain=9.87,%20status=1,%20first_name=Test,%20last_name=Test,%20middle_name=Test,%20egn=553745347,%20firm=,%20mol=,%20phone=000000000,%20address=Test,%20shipping_address=null,%20zdds=true,%20pay_type=0,%20bulstat=}]
I am trying to show this in jsp page. I have got the parameters and print the to console like this.
<%
String[] previous = request.getParameterValues("previous");
for (int i = 0; i < previous.length; i++) {
System.out.println(previous[i]);
}
%>
But i do not know how to pass them to the view page ?

You have to change your URL first otherwise you will end up writing parsing logic.
Sample Request : http://localhost:8080/hello?user_id=3&email=ivanov#test.eu&budget_limit=23.00
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<body>
<c:forEach var="par" items="${paramValues}">
${par.key} = ${par.value[0]};
</c:forEach>
</body>
Output : This will be visible on browser.
user_id = 3; budget_limit = 23.00; email = ivanov#test.eu;

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>

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

jsp: how to get value from session?

I get an String array from session and I want to show the String from the array.
I know javascript can't get data from session directly. Is there any method I can get the data from session and transfer it to javascrip?
My code as follows:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%String[] sele = (String[])session.getAttribute("selections");%>;
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta http-equiv="Expires" content="0">
<meta http-equiv="kiben" content="no-cache">
<title>Check List</title>
<script language="javascript" type="text/JavaScript" src="cookie.js">
</script>
<script text="text/javascript">
{
var selections = //String array form session
for(var v=0;v<selections.length;v++){
fillForm(selections[v]);
}
}
function fillForm(name){
var checkbox= document.createElement("input");
checkbox.type="checkbox";
checkbox.name=name;
checkbox.value=name;
checkbox.id=name;
var label = document.createElement("label");
label.htmlFor="id";
label.appendChild(document.createTextNode(name));
var container = document.getElementById("checklist");
container.appendChild(checkbox);
container.appendChild(label);
container.appendChild(document.createElement("br"));
}
function submitAction(){
addUserName(document.getElementById("checklist"));
var elem = document.getElementById("checklist").elements;
for(i =0;i<elem.length;i++){
elem[i].checked = true;
}
var form = document.getElementById("checklist");
form.submit();
}
</script>
</head>
<body>
<form id="checklist" action="selection">
</form>
<Button type="button" onclick="submitAction()" name="submit">Submit</button>
</body>
</html>
Simply use JSP Expression Language and JSP JSTL
<script>
alert("value: ${selections}");
</script>
Here selections is an attribute that is set in any scope page, request, session or application.
You can directly access an attribute form session scope:
{sessionScope.selections}
Note: I don't know that Java ArrayList does work in JavaScript as well. If it doesn't work then simply set a comma separated string as session attribute and split it in JavaScript as shown below.
Sample code:
<script>
var selections = "${sessionScope.csv}".split(",");
for ( var v = 0; v < selections.length; v++) {
alert(selections[v]);
}
</script>
Here csv is a comma separated string value that is set in session scope.
Use JSP JSTL and EL instead of Scriplet that is more easy to use and less error prone.
You can achieve it in JSTL without using JavaScript. Simply iterate the list using <c:forEach> tag and add that much of check boxes and labels.
Sample code:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
...
<body>
...
<c:forEach items="${selections }" var="name">
<input type="checkbox" name="${name}" value="${name}" id="${name}">
...
</c:forEach>
</body>

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

Categories