I have to write session values to a a text file in a JSP page. I was able to retrieve the values of the session using following JSTL code.
<c:forEach items="${chapters}" var="name">
<c:out value="Iteration..."/>
<c:out value="${name}"/>
</c:forEach>
After retrieving values , i have to write these values to a text file , and the following sample code works well. But i cannot use JSTL tags inside JSP tags (<% ... %>).
1.Is it possible to use JSTL value inside JSP tags?
2.How to retrieve the session value inside JSP tags ?
It's not recommended to write text file using JSP. It's better to use backend technology so you need to use servlet for that which is made for that, this type of operation must be done by Server Side.
If still you want to do so you can do it using scriplet tag :
<c:set var="name" value="${name}"/>
<%# page import="java.io.*" %>
<%
String str = (String)session.getAttribute("sessionName");
String name = (String)pageContext.getAttribute("name");
String nameOfTextFile = "/resources/data.txt";
try {
PrintWriter pw = new PrintWriter(new FileOutputStream(nameOfTextFile));
pw.println(str);
pw.close();
} catch(IOException e) {
out.println(e.getMessage());
}
%>
Use a servlet for that. JSP is just a view technology.
Related
I am writing a JSP code which goes like this:
<% if(---)
{----}
else
{ ---
%>
<jsp:forward page="error.jsp">
<jsp:param name="" value=""/>
</jsp:forward>
<%
}
%>
The error.jsp is in the same directory as the current jsp file still it is throwing "class not found exception". What to do?
Not much clear from your question what you are trying to achieve but If you are adding the another jsp page within current jsp page then use jsp:include otherwise if trying to redirect to another jsp page then following could be used.
Use in scriptlet response.sendRedirect in your case as below:
<%
response.setHeader("header_key", "header_value");
response.sendRedirect("your_page_location")
%>
Above could be used for external pages as well like "www.google.com"
On the other hand you could use request forward with all old parameters and data from calling page. See below:
RequestDispatcher rd = servletContext.getRequestDispatcher("/pathToResource");
rd.forward(request, response);
Also, another easy way could be to submit a form with action="your_jsp.jsp" but this should be used in case of form submissions where you are sending some data etc.
Make choice for any of above options on a case basis.
Hope it helps!
I've a map in which I'm storing an Id as a Key and under that Id I've a List of bean class where in all the bean properties are set and stored. How do I display the contents of the map in my java class? I tried something like this but not getting the list values.
for (Entry<String, List<MyBean>> me : MyForm.getClientId().entrySet())
{
String key = me.getKey();
List<MyBean> valueList = me.getValue();
System.out.println(" Key: " + key);
System.out.print("Values: ");
for (MyBean s : valueList) {
System.out.println(" " + s.getFundId());//This comes as null even though there are values in the list
}
}
Similarly I want to print the contents on the jsp page. How do I do that?
Try this code :
Set your result map in as request attribute in Servlet as show below
request.setAttribute("myMap", map);
RequestDispatcher des = request.getRequestDispatcher("test.jsp");
des.forward(request, response);
You may used different method to pass value to JSP page.
Than after you can use JSTL Tag Library to read that value in JSP page.
You need to include jstl jar file into your class path and add below line to jsp to add tag library in page
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Used this code in JSP when you required to read value
<c:forEach var="beanList" items="${myMap}">
<c:forEach var="bean" items="${beanList['value']}">
<c:out value="${bean.fundId}"></c:out>
</c:forEach>
</c:forEach>
Where fundId is your bean property name.
May this will help you.
Just try this :-
Put this in your servlet/Controller class:-
javax.servlet.http.HttpServletRequest.setAttribute("myFormEntrySet",
And these lines in your jsp page:-
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
MyForm.getClientId().entrySet());
<c:forEach var="myFormEntrySetVar" items="${myFormEntrySet}">
<c:set var="myBeanList" value="${myFormEntrySetVar.value}" />
<c:forEach var="myBeanListVar" items="${myBeanList}" >
${myBeanListVar}
</c:forEach>
</c:forEach>
To use JSTL please download the jar of JSTL
I'm a beginner to JSP (started today) and wanted to send some data (which I have got in a JSP file from an HTML form) to a JAVA program where I could use it.
Peterclass is the name of the Java program I'm gonna be making/using.
Suppose my JSP file is like this:
<%# page import="com.example.Peterclass"%>
<%# page import="java.util.*"%>
<html>
<body>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
%>
<h1>
Hello, <%=username%>!
</h1>
</body>
</html>
and I wanted to receive the values of username and password variables in a JAVA program (I'm using Tomcat server for the purpose). How shall I do it? Please be as simple as you can be.
Thank you.
First of all, you will need a so called "Servlet" to work with request and response Parameter.
Here is a first tutorial on how to create and use servlets:
Click here
Another tip for you:
It is not state of the art to use so called Scriptlets.
Scriptlets is a form of Java-Code in JSP Sites:
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
%>
You can easily get the parameter you set in your Servlet with:
${requestScope.<<PARAMETERNAME>>}
e.g. ${requestScope.username}
or if your parameter is in the HTTPSession:
${sessionScope.<<PARAMETERNAME>>}
your jsp side would look like this afterwards:
<html>
<body>
<h1>
Hello, ${requestScope.username}!
</h1>
</body>
So, to come back to your question:
In your Servlet you can set the Parameter with
request.setParameter(<<PARAMETERNAME>>,<<VALUE>>)
In this Servlet you can call normal Java-Functions. First step for you is to read through tutorials :)
I am trying to set a variable (named as "o") in jsp in the body of tag - how could I do it without scriplets?
I have wrote this piece of code but it is not working:
<a class="overfl" href="myServlet?action=request.setAttribute('o',i)"> ${values[i]} </a>
Try with JSTL Core c:set Tag to set the attribute in any scope.
Sample code:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="salary" scope="request" value="${2000*2}"/>
ServletRequest#setAttribute() method doesn't return any value.
Get the value back in the same way as you are doing here ${values[i]}
or try with JSTL Core c:out Tag to get the value back.
In your case simply pass the action values as query parameter as shown below:
<a class="overfl" href="myServlet?action=${i}"> ${values[i]} </a>
And get the value back at server side using
String action = servletRequest.getParameter("action");
If the varaible is not already defined in your request's attribute so call <%request.setAttribute('o',i); %> then if you want to write it to the jsp output you have to to write <%request.getAttribute('o') %> in the place where you want to add it's value like this :
<%request.setAttribute('o',i); %>
<a class="overfl" href="myServlet?action=<%=request.getAttribute('o') %>"> ${values[i]} </a>
When trying to use a custom JSP tag library, I have a variable defined in JSP that I would like to be evaluated before being passed to the tag library. However, I cannot seem to get it to work. Here's a simplified version of my JSP:
<% int index = 8; %>
<foo:myTag myAttribute="something_<%= index %>"/>
The doStartTag() method of my TagHandler uses the pageContext's output stream to write based on the inputted attribute:
public int doStartTag() {
...
out.println("Foo: " + this.myAttribute);
}
However, the output I see in my final markup is:
Foo: something_<%= index %>
instead of what I want:
Foo: something_8
My tag library definition for the attribute is:
<attribute>
<name>myAttribute</name>
<required>true</required>
</attribute>
I have tried to configure the attribute with rtexprvalue both true and false, but neither worked. Is there a way I can configure the attribute so that it's evaluated before being sent to the Handler? Or am I going about this totally wrong?
I'm relatively new to JSP tags, so I'm open to alternatives for solving this problem. Also, I realize that using scriptlets in JSP is frowned upon, but I'm working with some legacy code here so I'm kind of stuck with it for now.
Edit:
I have also tried:
<foo:myTag myAttribute="something_${index}"/>
which does not work either - it just outputs something_${index}.
I don't believe that you can use a <%= ... %> within an attribute in a custom tag, unless your <%= ... %> is the entire contents of the attribute value. Does the following work for you?
<% int index = 8; %>
<% String attribValue = "something_" + index; %>
<foo:myTag myAttribute="<%= attribValue %>"/>
EDIT: I believe the <% ... %> within the custom tag attribute can only contain a variable name. not any Java expression.
To keep your JSP code clean and neat, avoid scripting when possible. I think this is the preferred way to do it:
<foo:myTag >
<jsp:attribute name="myAttribute">
something_${index}
</jsp:attribute>
</foo:myTag >
if your tag also contains a body, you'll have to change it from
<foo:myTag myAttribute="<%= attribValue %>">
body
</foo:myTag >
to
<foo:myTag >
<jsp:attribute name="myAttribute">
something_${index}
</jsp:attribute>
<jsp:body>
body
</jsp:body>
</foo:myTag >
<foo:myTag myAttribute="something_${index}"/>