Please correct me if I am wrong. I am developing a small web application for learning purpose. I have a jsp in which a list of top scorers in the the game are to be displayed in a table. For that I wrote a ServletContextListener and in the contextInitialized() method I have set an attribute(LinkedHashSet) in the ContextScope, which is the list of top 10 scorers in the game. I think it can be accessed using EL. But how can I update this collection?
You can use request.getSession().getServletContext().getAttribute("your_attribute_name_here") and can access the LinkedHashSet, once you get it you can add/remove/update values in it and again set it back to put updated values like request.getSession().getServletContext().setAttribute("your_attribute_name_here", "update_LinkedHashSet"); As best of my knowledge using EL you can access it but can not put back the updated value in attribute.
Note: while accessing the attribute you will need the explicit type casting.
You can update attribute like :
<%((Set<String>)pageContext.getServletContext().getAttribute("set")).add("Second"); %>
<% Set<String> set = (Set<String>) pageContext.getServletContext().getAttribute("set"); %>
from servlet context
<c:forEach items="${set}" var="s">
<c:out value="${s}"/>
</c:forEach>
Related
In my controller I have code like this:
List<FeesReceiptIntegrationModel> FRIList = feesReceiptIntegrationService.listInstituteWiseCollectionSummary(model, request);
model.addAttribute("FRIList", FRIList);
I want to access this FRIList and its fields in Scriptlet of JSP page.
I tried something like this:
String fcash = request.getParameter(FRIList.cashamount);
but it does not work.
List myMap = (ArrayList) request.getAttribute("FRIList.cashamount");
I don't want to access this via JSTL tags but I would like to access this only in scriptlet.
Can anybody tell me how this can be achieved?
Using scriplets is a bad idea. Try to avoid using java codes inside JSP page.
You can use JSTL c:forEach for your purpose
Simple example
<c:forEach items="${FRIList}" begin="0" end="1" var="test">
${test.cashamount}
</c:forEach>
You cant print the values in the list as it is, you need to iterate them after you get the list from the model. As said,
I don't want to access this via JSTL tags but I would like to access this only in scriptlet
<% List<FeesReceiptIntegrationModel > myMap = (ArrayList<FeesReceiptIntegrationModel >) request.getAttribute("FRIList");
for(FeesReceiptIntegrationModel obj : myMap ){
obj.getcashamount(); // your getter method here
}
%>
but it is not advisable to use the scriptlets, please have a look at How to avoid Java code in JSP files?
I'm working on a componentization system based on JSPs. This means that parts of the JSP can be moved from one JSP to an other one via drag and drop and leads to a need for a local page scope as variable of a component defined in one JSP my collide in an other JSP.
I can use Servlet 3.0 / JSP 2.2 / JSTL 1.2.
++ Tag File ++
The straight way of doing that would be to create a tag file for a component or something similar as they have this local page scope. But for every change in the tag file it would need to get redeployed and needing to create a tag file needs some time by itself. But if there is no other solution this direction (custom tags, tag files, JSP includes,...) is probably the way to go.
++ Namespace prefixing/suffixing ++
In Portlets one is supposed to concatenate each variable with a namespace provided from the portlet response object. I could do something similar but this can lead to side effects and unexpected behavior. If someone forgets to prefix/suffix the namespace it might work for some time but stops working at an other time without changing the code when the component moved to an other JSP with a conflicting variable name.
++ Custom Tag wrapping ++
I was hoping that I as a component framework developer can wrap the component code of a component developer with a tag file for a component tag like this
<a:component>
<div data-component-id="9">
<c:set var="componentId" value="9"/>
<c:set var="path" value='${abc:getCurrentPath()}_${componentId}'/>
<c:set var="resource" value='${abc:getResourceFromPath(path)}'/>
<c:set var="val" value="${resource.getValue('paragraphValue')"/>
<p><c:out value="${value}"/></p>
</div>
</a:component>
to have the variable in the local page context of the tag file. But instead they are in the context of the surrounding page. I'm looking for something like this
<% { %>
<div data-component-id="9">
<%
String componentId = 9;
String path = obj.getCurrentPath()+componentId;
Resource resource = otherObj.getResourceFromPath(path);
String value = resource.getValue("paragraphValue");
%>
<p><c:out value="<%=value%>"/></p>
</div>
<% } %>
which would create a code block in which variables have their own namespace. But of course for JSTL and JSTL-EL instead of scriptlet code.
I had a look at the JSTL specification but did not find out if there is a way to create such a local page scope. But I didn't check everything as it's huge and I'm not sure if it's possible with custom tags.
It is clear to me that bigger code blocks should not be in the JSP but with the framework I would like to provide simple solutions for smaller components.
++ Changing the JSP code ++
When components are initially placed on a JSP or moved around via drag 'n drop I actually move the JSP code of a component from one JSP to an other or within a JSP. This means I can also programmatically manipulate the JSP code of a component if it doesn't get too complex and it helps solving the problem.
As I thought that custom tag wrapping could be the ideal solution I created an other more specific question and I've got an answer here that solves the problem.
It's simply to remove all pageContext attributes before the evaluation of the body and adding them again at doEndTag().
I have a class language having features ID and Name.
I have another class Language_List that has ArrayList<language> lang as a member variable.
In my JSP page I want to access the Name variable of ArrayList<language> lang using EL and For each Loop.
<c:forEach var="language" items="${languages.lang}">
${language}<br>
</c:forEach>
However, it doesn't show ant result and intellisense doesn't work too. Anyone who can help me with this
PS: languages is a Bean variable contain list of languages from DB
I tried this and got this
<b>${languages.lang}</b>
HTML
[sakila.language#f1541c, sakila.language#63c8fabf, sakila.language#1fc644c7, sakila.language#11cd751d, sakila.language#47c3cc0c, sakila.language#7894ca3, sakila.language#47066532, sakila.language#74ddda0b, sakila.language#1116441e, sakila.language#4cd21655, sakila.language#74b84dd9, sakila.language#6fff1d6c, sakila.language#55e4d6e5, sakila.language#22d88071, sakila.language#33d88c96, sakila.language#4df5e671, sakila.language#4aec2cb3, sakila.language#576ac232, sakila.language#76a6dbd7, sakila.language#44ab3d1c, sakila.language#46391c7c, sakila.language#4f7d34e8, sakila.language#251c941d, sakila.language#77400ef3]
The EL doesn't access fields of your objects. It accesses bean properties of your objects. This means that ${languages.lang} is translated to a call to languages.getLang().
If you don't have such a getter, you'll get an exception though. If it just doesn't display anything, it's probably because languages is null, or because its lang list is null or empty. To confirm or infirm those guesses, we need to see the code where you create and populate the bean and its list of languages, and where you store it somewhere to make it accessible from the JSP.
Another possibility is that you forgot to declare the core taglib at the beginning of the JSP. To confirm or infirm that, paste the code of the JSP, and the HTML code generated by the JSP (using View page source in the browser)
I have a serveresource method which is invoked on clicking a link. The serveresource method takes the input from the parameter that was passed and retrieves a row from the database. Now all the values in a row are in set using the mutator methods. I have everything in a java object. I need to pass this object to a jsp page to print the values of a single row on the jsp page. I am not sure how to handle that java object in the jsp page instead of setting each value as an attribute in the serveresource method. Need help from experts.. Thanks in Advance
UPDATE
It was because I have an Ajax call and when I set values it is in a completely different life cycle which is causing the problem. I figured it out.
You should defining the java object as Bean in JSP.
The Bean in JSP can be defined using < jsp:useBean..> standard jsp tag. And set and get property using < jsp:setProperty..> and < jsp:getProperty..> standard jsp tags.
Refernces:
Use Bean
Using Beans in JSP. A brief introduction to JSP and Java Beans
UseBean syntax
< jsp:setProperty> and < jsp:getPropety> syntax
The usual method is to add it to the HttpServletRequest object, thus:
MyBean myBean = new MyBean();
myBean.setValue("something);
myBean.setAnotherValue("something else");
// ... stuff ...
request.setAttribute("myBean", MyBean);
This can be accessed from the jsp page using EL thus:
<table>
<tr>
<td>${myBean.value}</td>
<td>${myBean.anotherValue}</td>
</tr>
</table>
you can bind with request object
In Servlet or JSP
request.setAttribute("strIdentifire", yourJavaObject);
In JSP
YourJavaObjectClass obj = (YourJavaObjectClass)request.getAttribute("strIdentifire");
I have an attribute which I have forwarded from a servelet to a jsp file and while I can use this object with EL I'd like to know how to access it inside the java tags. An example is something like the following:
Searching for "${search_phrase}" returned
<c:forEach var="video" items="${results}">
${video.getVideoName()}
${video.getVideoID()}
</c:forEach>
So results here is an ArrayList of type Video which is forwarded from a servlet to a jsp
I would like to access this ArrayList inside <% %> tags in order to perform some more involved tasks that I cant do with EL.
Anybody know how to do this?
On a side note, this ArrayList I'm creating could potentially get large. Where is this stored? On the server or in some users temp files? If it's stored in server memory does it get cleaned after some period of time / an event such as the user that requested the ArrayList closes connection to server?
It all depends where you stored the list. If you stored it in a request attribute (and not anywhere else), then it will be eligible to garbage-collection when the request has been handled.
If you stored it in a session attribute, then it will be stored in the server memory (and/or the file system or the database depending on the container configuration) until the session times out or is invalidated, or until you remove it. HTTP is a stateless protocol. The user doesn't have a connection to the server.
Java code between <% %> is not a java tag. It's scriptlet, and should not be used in a JSP. If you need to do something that EL or JSP tags can't do easily, then either
write a custom JSP tag yourself, put the Java code in this JSP tag, and invoke the tag from the JSP, or
or write a custom EL function, and invoke this function from the JSP
or prepare the work in a controller (servlet, MVC framework action) before dispatching to the JSP, so that the JSP can generate the markup easily.
The list is accessible using the getAttribute method corresponding to the setAttribute method you used to store the list:
HttpServletRequest.setAttribute() --> HttpServletRequest.getAttribute()
HttpSession.setAttribute() --> HttpSession.getAttribute()
ServletContext.setAttribute() --> ServletContext.getAttribute()
I think you should use something like
<c:forEach var="video" items="${results}">
<c:forEach var="videoType" items="${video.types}"> //suppose videoType is an object
<c:out value="${videoTypeDetails}" />
</c:forEach>
</c:forEach>