JSTL call parameterized void method [duplicate] - java

How to call a Java method with arguments which is defined in Java class, from JSP using JSTL/EL. The method is returning arrays. Any return value can be used.

You can only invoke methods with arguments in EL if you're targeting and running at least a Servlet 3.0 compatible container (e.g. Tomcat 7 or newer, WildFly 8 or newer, GlassFish 3 or newer, etc) with a web.xml declared conform at least Servlet 3.0. This servlet version comes along with EL 2.2 which allows invoking arbitrary instance methods with arguments.
Assuming that you've a ${bean} in the scope which refers to an instance of a class which has a method something like public Object[] getArray(String key), then you should be able to do this:
<c:forEach items="${bean.getArray('foo')}" var="item">
${item} <br />
</c:forEach>
or even with another variable as argument
<c:forEach items="${bean.getArray(foo)}" var="item">
${item} <br />
</c:forEach>
But if you don't target a Servlet 3.0 container, then you cannot invoke methods with arguments in EL at all. Your best bet is to just do the job in the preprocessing servlet as suggested by Duffymo.
Object[] array = bean.getArray("foo");
request.setAttribute("array", array);
// ...
As a completely different alternative, you could create an EL function which delegates the method call. You can find a kickoff example as option 2 of this answer How to call a static method in JSP/EL? You'd like to end up something like as:
<c:forEach items="${util:getArray(bean, 'foo')}" var="item">
${item} <br />
</c:forEach>
with
public static Object[] getArray(Bean bean, String key) {
return bean.getArray(key);
}
The web.xml file should absolutely not have a <!DOCTYPE> line in top as that would otherwise still force the Servlet 2.3 modus. You can find examples of proper web.xml declarations in the second half of this answer How to install JSTL? The absolute uri: http://java.sun.com/jstl/core cannot be resolved.

The above solution didnt work for me.
I had a function getRemitanceProfileInformation(user) in my java class.
I created a usebean of java class and then invoked
<c:set var="paymentValueCode" value='remittanceaddr.getRemitanceProfileInformation("${user}")'/>
and it worked.

Give the JSP a reference to an instance of the class that has the method and call it.
You're probably asking who gives the JSP that instance - it's a servlet in the model-2 MVC arrangement.
Here's how the flow will work:
Submit a GET/POST request from a JSP to a servlet.
Servlet acts on that request and does some work on the JSP's behalf. Puts all the necessary objects into request, session, or other appropriate scope.
Servlet routes response to the next JSP, which might be the same as the requesting JSP.
Rinse, repeat.

If you're using JSF, you can use an bean act as a model in View Scope, and load from data source automatic. And if you're using JSP, how about using TLD Tag? And using JSTL tag <c:foreach> ? It's saves the memory from saving in the session, or save in session and remove it when load event done? Some how like this (JSTL+TLD)
<c:forEach items="${myTag:getProductByPage(page)}" var="p">
Product name: ${p.productName}
</c:forEach>

Related

How to get to application context path without using scriplets in JSP files?

So I have a code like this in my jsp file:
<a href="<%= getServletConfig().getServletContext().getContextPath() %>/registerMe.jsp"
class="btn">Not a member? Register..</a>
And I know that using scriplets is bad practice in JSP files. How can I avoid such a situation then?
Use an EL expression:
<a href="${pageContext.servletContext.contextPath}/registerMe.jsp"
class="btn">Not a member? Register..</a>
You can use request.getContextPath() in your action class, and you can pass that to JSP as a string using request, or you can use bean to get that in JSP.
Application scoped objects are stored as attributes of the ServletContext. If the "function call" has access to the ServletContext, then it can just grab them as follows:
Bean bean = (Bean) servletContext.getAttribute("beanname");
I of course expect that the "function" is running in the servlet context. I.e. it is (in)directly executed by a servlet the usual way.
You can also try this link. It have example with full explanation.

How to access servlet-context in jsp/struts2?

I have a HashMap<Long, ClientProperties> that I'm putting on the ServletContext at startup.
//During application-startup:
//getProperties() returns HashMap<Long, ClientProperties>
context.setAttribute("clientProps", clientManager.getProperties());
ClientProperties is a POJO with 5 attributes that i need to access in my jsp.
Basicly I need to get the correct POJO (by HashMap-key) and access its properties in my jsp.
More spesific (for example purposes), one of the POJO attributes is clientLogo
In my jsp i now have:
<img src="<c:url value='/images/logo.png'/>" alt="Logo">
I need to replace the path to the logo-file with the clientLogo-property of the POJO.
The HashMap-key to use should be extracted from the User-object stored in the session. It can be retrieved like this: ${sessionScope['user'].clientId}
Any ideas?
Using struts2 and spring btw if that matters.
To get an attribute foo from the servlet context, you use the same syntax as to get it from the session, but replace sessionScope by applicationScope.
But you have so many nested things here that you should define variables:
<c:set var="map" value="${applicationScope['clientProps']}"/>
<c:set var="mapKey" value="${sessionScope['user'].clientId}"/>
<c:set var="pojo" value="${map[mapKey]}"/>
<c:set var="clientLogo" value="${pojo.clientLogo}"/>
<c:url value="${clientLogo}"/>
Note that this is typically the kind of hard work that you should not have to do in the view. Implement the retrieval of the image path in the controller, in Java, and make it available as a property of your action/form, and access it directly from your view.

How to pass a java object to jsp page

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");

using EL inside java tag

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>

See POST parameters in Java EE eclipse debugging

I'm not experienced in debugging Java EE (I'm rather a javascript guy) and I need to see what HTTP POST parameters get to the server side. I put a breakpoint in a jsp file that the form is pointing its action to and now I can't find the POST content in the debug variables window.
Where are they? How can I lookup the POST in debug?
[I'd use wireshark, but it's over the https]
In jsp you can use request object and call its method getParameterNames () or getParameter (String name). You can also call request.getMethod () to ensure that you obtain parameters from POST request.
<%
if (request.getMethod().equals("POST")) {
for (String paramName : request.getParameterNames ()) {
String value = request.getParameter (paramName);
}
}
%>
In the breakpoint, just check the HttpServletRequest property of the JspContext instance and then check its parameterMap property.
Or do it the poor man's way by just printing them all in the JSP:
<c:forEach items="${param}" var="p">
Param: ${p.key}=
<c:forEach items="${p.value}" var="v" varStatus="loop">
${v}${loop.last ? '<br>' : ','}
</c:forEach>
</c:forEach>
That said, you'd normally be interested in them inside a servlet class, not inside a JSP. This would indicate that you're doing some business logic inside a JSP file using using scriptlets. This is considered bad practice. Don't do that and move that raw Java code to real Java classes before it's too late. Use JSP for presentation only. You can use taglibs like JSTL to control the page flow and use EL to access backend data.
In debug mode: see
request -> request -> coyoteRequest -> parameters -> paramHashValues

Categories