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");
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>
I have an ArrayList of a class Room. I need to send it from a jsp to a servlet.
It seems the only way an html or a jsp can send values to a servlet is via a form, the method I tried was to pass it as a hidden parameter as follows:
<input type="hidden" name="allRooms" value="<%=request.getAttribute("allRooms") %>" />
But in the servlet to which i submit this form I get a compile error "String cannot be converted to List" for the following:
List<Room> allRooms=(List<Room>)request.getParameter("allRooms");
Just converting the parameter to an Object type first and then converting it to a List as shown below gives the same exception but this time as a Runtime Exception:
Object a=(Object)request.getParameter("allRooms");
List<Room> allRooms=(List<Room>)a;
Is there any method to pass the List to the servlet or I will have to set it as a session variable in the JSP ?
Thanks in advance.
Is there any method to pass the List to the servlet or I will have to set it as a session variable in the JSP ?
Use session.That is one best solution.
There is no way to represent an ArrayList in HTML to send via html form. Use session instead.
I think if you pass the following params, and array is formed in servlet side
param[0]=ss , param[1]=ssw
You could do this.
List<String> roomParams =(List<String>)request.getParameter("param");
But to make this.
List<Room> allRooms=(List<Room>)request.getParameter("allRooms");
That I think is not possible, so you should use Session attributes
session.setAttribute("allRooms", new ArrayList<Room>());
I believe you should not be sending the List to Servlet directly and should look out for other options.
How are you generating the ArrayList on the browser page? If it is generated from a multi-select element from UI, then you can access the request parameter values as Array in Servlet.
Shishir
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 a framework based on JSP, and I want to move the logic from the JSP in Java, so for that I'm using a POJO with
<jsp:useBean id="myBean" class="myClass" scope="page"/>
<c:set var="myVariable" scope="request" value="${myBean.myGetter}"/>
I have a reference to the request in myClass.
My question is if I can set some attributes on request, do a RequestDispatcher.include to a JSP that will use the attributes I set, when the call gets back, to use some attributes that were put on the request by the included JSP.
I used RequestDispatcher only in servlet/filter, but not on a POJO within a getter.
Yes, if you have reference to request you can do it. Ultimately, the JSP code is translated to Servlet, and calling include in Bean will be as same as calling it from code within servlet.
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>