How to access application data in a session .jsp file - java

I am executing the following loop to view all my session attributes:
<%
for (Enumeration e = session.getAttributeNames(); e.hasMoreElements(); ) {
String attribName = (String) e.nextElement();
Object attribValue = session.getAttribute(attribName);
%>
<BR>
<%= attribName %> - <%= attribValue %>
Which will output:
user.principal.key / user.ip.address.key / session.user.key
However, I wish to access more of the user information that might not exist in session yet, like other variables I set in the user.java file.
How would be the best way to store these variables in the session, so I may go about printing them to my page?

Set them as a session attributes:
public void doGet(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
session.setAttribute("myVariable", variableValue);
}
Use some tag library like JSTL to access attributes sent from servlet instead of using scriptlets.
In case of JSTL use out to print value of your variable:
<c:out value="${myVariable}" />
Don't forget to include JSTL tag lib in your JSP:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
and to download JSTL dependency from here

Related

Can you get an session attribute from a servlet in a <% %> block in a jsp file?

Can I get a session attribute from a Servlet in a
<%
%>
block within a jsp?
use
session.getAttribute("name");
to print
<%= session.getAttribute("name"); %>
And to set them in servlet use
HttpSession session = request.getSession();
session.setAttribute("name", name);

Print contents of a Map<String,List<Bean>> in Java

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

renderRequest attributes are always null after calling renderURL

I can't seem to access data I want to pass to my .jsp files. I've simplified it to the bare-bones and it still doesn't work for me. This portlet is being deployed to a liferay portal.
Problem: I click on the link to call a renderURL for the next .jsp page. In the doView() method, I set an attribute with setAttribute. When I retrieve that attribute in the .jsp, it returns null.
Expected output: "Proper Value"
Actual output: "Default value"
NewPortlet.java (Controller)
public class NewPortlet extends MVCPortlet {
#Override
public void doView(RenderRequest request, RenderResponse response)
throws IOException, PortletException {
request.setAttribute("test", "Proper Value");
String path = ParamUtil
.getString(request, "path", "/html/new/view.jsp");
include(path, request, response);
}
}
view.jsp
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<portlet:renderURL var="testURL">
<portlet:param name="path" value="/html/new/edit.jsp"/>
</portlet:renderURL>
<p>Click me!</p>
edit.jsp
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%#page import="com.liferay.portal.kernel.util.ParamUtil"%>
<portlet:defineObjects />
<%
String test = ParamUtil.getString(renderRequest, "test", "default value");
%>
<p><%= test %></p>
I am not sure what exact usecase you have.
But here issue is, you are setting attribute and trying to fetch parameter, hence it returns null.
For solution to your issues as in code, use renderRequest.getAttribute("test") or use el, ${test}
The "view.jsp" is referring "edit.jsp" using portlet:renderURL and that can be an issue. The render requests may be executed sequentially or in parallel without any guaranteed order.
I am not sure why your workflow is this way (i.e. setting parameter in doView method), but try actionURL instead of renderURL.

<c:forEach> not working for to print List of Strings

Hi I am trying to print the list of strings stored in ArrayList object using JSTL, here is my jsp page:
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.List"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
List<String> al = new ArrayList<String>();
al.add("testing1");
al.add("testing2");
al.add("testing3");
al.add("testing4");
al.add("testing5");
System.out.println("hello"+ al);
%>
<c:forEach var="alla" items="${al}" >
<c:out value="Hello text"></c:out>
<c:out value="${alla}"></c:out>
</c:forEach>
when i see output it is not showing any thing on the browser, I have printed it using foreach it is showing the result where as in JSTL it is not printing ?
jstl is used to print the objects from the session or request scopes. you did not set your List al either of those .
Try adding it to the session and then access it through jstl
HttpSession session = request.getSession();
session.setAttribute("al", al);
and use c:forEach to print it in your page.
See also
Scope of jsp objects
How do i use jstl
Add values to arraylist use JSTL
how do i create an arraylist inside jsp using jstl

JSP: About Session in a system with login in constraint

When I am doing a project requires a login in system, I found that jsp will automatically create session, so I add <%# page session="false" %> into all pages to disable their abilities to create session since I only want one servlet to be able to create session.
However, when it comes to using bean, I found that, I can't use bean with session scope because of <%# page session="false" %>, I would like to ask what is the possible solution to solve this deadlock.
Many thanks
If you are setting session attributes from servlet(after login) then when you move to another JSP from it, the session will retain and you do not need to write
<%# page session="false" %>
on that JSP. All the attributes that you set will be available for you in the session.
Here's a test code :
index page shows 'name' attribute set in servlet - MaintainSession also when you press 'next JSP' button, it takes you to another new JSP which again shows the 'name' attribute.
None of the JSP needs the <%# page session="false" %>.
index.jsp
<body>
<form action="MaintainSession" method="post">
<input type="submit" value="Set Session Attribs"/>
</form>
<h1>Name : ${sessionScope.name}</h1>
<h1>Name : <%=session.getAttribute("name")%></h1>
<form action="Next.jsp" method="post">
<input type="submit" value="Next JSP"/>
</form>
</body>
Next.jsp
<body>
<h1>Hello World!</h1>
<h1>Name : ${sessionScope.name}</h1>
<h1>Name : <%=session.getAttribute("name")%></h1>
</body>
MaintainSession.java
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
session.setAttribute("name", "MyName");
request.getRequestDispatcher("index.jsp").forward(request, response);
}
The flow :
index.jsp ----Press Set Session Attribs---> MaintainSession servlet ----> index.jsp ---- press Next JSP ----> Next.jsp

Categories