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.
Related
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>
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.
I want to read parameter passed by one JSP to another using HTTP POST method.
Following are my two JSP files.
One.jsp
<body>
<form action="Two.jsp" method="post">
<input type="text" value="test value" name="txtOne">
<input type="submit" value="Submit">
</form>
</body>
Two.jsp
<body>
<% response.getWriter().println(request.getParameter("txtOne")); %>
</body>
I can access the parameter in Two.jsp file using scriplet.
I want to avoid scriplet, so I am looking for JavaScript or jQuery solution.
So far I have searched and found JavaScript solution which only reads parameters sent using GET method(query string only).
Any suggestion will be appreciated.
Thanks in advance.
Solution:
I was able to get the value using JSTL:
${param.txtOne}
Try expression language - ${txtOne}, of if the method in one.jsp is GET instead of POST, you would be able to read URL in javascript and extract parameter value from there.
Yes you can get the value by use of JSTL
${param.txtOne}
Update
From EL info page
In EL there are several implicit objects available.
EL Scriptlet (out.print and null checks omitted!)
---------------------------------- ---------------------------------------------
${param.foo} request.getParameter("foo");
${paramValues.foo} request.getParameterValues("foo");
${header['user-agent']} request.getHeader("user-agent");
${pageContext.request.contextPath} request.getContextPath();
${cookie.somename} Too verbose (start with request.getCookies())
Implicit Objects
The JSP expression language defines a set of implicit objects:
pageContext: The context for the JSP page. Provides access to various objects including:
servletContext: The context for the JSP page’s servlet and any web components contained in the same application. See Accessing the Web Context.
session: The session object for the client. See Maintaining Client State.
request: The request triggering the execution of the JSP page. See Getting Information from Requests.
response: The response returned by the JSP page. See Constructing Responses.
In addition, several implicit objects are available that allow easy access to the following objects:
param: Maps a request parameter name to a single value
paramValues: Maps a request parameter name to an array of values
header: Maps a request header name to a single value
headerValues: Maps a request header name to an array of values
cookie: Maps a cookie name to a single cookie
initParam: Maps a context initialization parameter name to a single value
Finally, there are objects that allow access to the various scoped variables described in Using Scope Objects.
pageScope: Maps page-scoped variable names to their values
requestScope: Maps request-scoped variable names to their values
sessionScope: Maps session-scoped variable names to their values
applicationScope: Maps application-scoped variable names to their values
I want to avoid scriplet, so I am looking for JavaScript or jquery solution.
Simply you cannot.
request object can only accessible on server side, i.e in your JSP. You cannot access request or response object in client side that i.e javascript/jquery/whatever.
If you want access jsp value in javascript, try something like
var news=<%= request.getParameter("txtOne")) %>;
As a side note: Avoid scriplets and go for Expression language.
It is time for you to move to some MVC framework like struts than plain JSP. Then you can fill an ActionForm from parameters and use them on Two.jsp.
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>
I'm trying to understand the concept of data binding in Spring-MVC with Velocity (I'm learning this framework and porting an app to this platform).
I'm used to getting form variables using request.getParameter("username"), in the Spring world it seems that I can perform validation and such against "form objects" e.g. a datamodel style object that represent all the fields of a form.
The concept of a validator makes sense, but marshaling the data from a query string to these objects is fuzzy for me still. This is the concept of "Data Binding" correct?
If I'm correct to this point a few specific questions:
When a "binding" is made between a form variable (say "username" for example) and the the field of an object (say org.a.b.MyNewUserFormObj.username) is that "binding" a permanent definition such that all subsequent http posts of that form cause the username form variable to be assigned to org.a.b.MyNewUserFormObj.username?
How in the world do I accomplish the above binding definition? (if what I've said up to now is correct I feel like Costello in 'Who's on First', I don't even know what I just said!), I just need a conceptual picture.
Thanks for setting straight a brain gone astray.
There is no magic in data binding.
Actually, Spring simply populate properties of #ModelAttribute object with the values of request parameters with the corresponding names (in the simpliest case request parameter have the same name as a property, but nested properties are also supported).
So, if you have
<input type = "text" name = "firstName" />
and
public class Person {
private String firstName;
... getters, setters ...
}
you get a value from the form field.
Spring also provides convenient method for creating HTML forms. So, instead of creating form fields manually, you can write in JSP:
<form:form modelAttribute = "person" ...>
<form:input path = "firstName" />
</form:form>
or in Velocity (note that in this case <form> is created manually and property path is prefixed with the model attribute name):
<form ...>
#springFormInput("person.firstName" "")
</form>
Fields of the forms generated this way will be prepopulated with the values of the corresponding properties of the model attribute (that's why model attribute name is needed).