Accessing the value of servlet in two jsps - java

I have a Servlet, which sends values to a JSP1. I am setting the values in the servlet as
request.setAttribute();
and i am using
dispatcher.forward(request, response);
and i am able to access these values in the JSP1 using expression language.
Now, I also need to use this in another JSP2.
These two JSP's are clubbed together to display in a single page. So, I need to access the values of the servlet in the second jsp as well. How can i do that?

As you say you have both the jsp clubbed in a single page , you can simply get the attribute as,
${attributeName}
it refers to the object set in the HttpServletRequest scope . I suggest to take the tutorial for Expression language

It is quite simple. If you are setting an attribute "attr1" in a servlet and then forwarding to a JSP (file1.jsp):
request.setAttribute("attr1", "first attr");
request.getRequestDispatcher("file1.jsp").forward(request, response);
And suppose in the first JSP (file1.jsp), you are including another JSP (say file2.jsp):
<body>
.....
<jsp:include page="file2.jsp"></jsp:include>
.....
</body>
Then in file2.jsp, you can access attr1 by calling the request object's getAttribute method:
<body>
....
${attr1}
....
</body>
In case of jsp:include action, when file2.jsp is included in file1.jsp, both request and response objects are passed to file2.jsp as parameters. So file2.jsp can access the attributes of file1.jsp's request object.

Related

How to create a parameter in JSP? [duplicate]

What is the difference between getAttribute() and getParameter() methods within HttpServletRequest class?
getParameter() returns http request parameters. Those passed from the client to the server. For example http://example.com/servlet?parameter=1. Can only return String
getAttribute() is for server-side usage only - you fill the request with attributes that you can use within the same request. For example - you set an attribute in a servlet, and read it from a JSP. Can be used for any object, not just string.
Generally, a parameter is a string value that is most commonly known for being sent from the client to the server (e.g. a form post) and retrieved from the servlet request. The frustrating exception to this is ServletContext initial parameters which are string parameters that are configured in web.xml and exist on the server.
An attribute is a server variable that exists within a specified scope i.e.:
application, available for the life of the entire application
session, available for the life of the session
request, only available for the life of the request
page (JSP only), available for the current JSP page only
request.getParameter()
We use request.getParameter() to extract request parameters (i.e. data sent by posting a html form ). The request.getParameter() always returns String value and the data come from client.
request.getAttribute()
We use request.getAttribute() to get an object added to the request scope on the server side i.e. using request.setAttribute(). You can add any type of object you like here, Strings, Custom objects, in fact any object. You add the attribute to the request and forward the request to another resource, the client does not know about this. So all the code handling this would typically be in JSP/servlets. You can use request.setAttribute() to add extra-information and forward/redirect the current request to another resource.
For example,consider about first.jsp,
//First Page : first.jsp
<%# page import="java.util.*" import="java.io.*"%>
<% request.setAttribute("PAGE", "first.jsp");%>
<jsp:forward page="/second.jsp"/>
and second.jsp:
<%# page import="java.util.*" import="java.io.*"%>
From Which Page : <%=request.getAttribute("PAGE")%><br>
Data From Client : <%=request.getParameter("CLIENT")%>
From your browser, run first.jsp?CLIENT=you and the output on your browser is
From Which Page : *first.jsp*
Data From Client : you
The basic difference between getAttribute() and getParameter() is that the first method extracts a (serialized) Java object and the other provides a String value. For both cases a name is given so that its value (be it string or a java bean) can be looked up and extracted.
It is crucial to know that attributes are not parameters.
The return type for attributes is an Object, whereas the return type for a parameter is a String. When calling the getAttribute(String name) method, bear in mind that the attributes must be cast.
Additionally, there is no servlet specific attributes, and there are no session parameters.
This post is written with the purpose to connect on #Bozho's response, as additional information that can be useful for other people.
The difference between getAttribute and getParameter is that getParameter will return the value of a parameter that was submitted by an HTML form or that was included in a query string. getAttribute returns an object that you have set in the request, the only way you can use this is in conjunction with a RequestDispatcher. You use a RequestDispatcher to forward a request to another resource (JSP / Servlet). So before you forward the request you can set an attribute which will be available to the next resource.
-getParameter() :
<html>
<body>
<form name="testForm" method="post" action="testJSP.jsp">
<input type="text" name="testParam" value="ClientParam">
<input type="submit">
</form>
</body>
</html>
<html>
<body>
<%
String sValue = request.getParameter("testParam");
%>
<%= sValue %>
</body>
</html>
request.getParameter("testParam") will get the value from the posted form of the input box named "testParam" which is "Client param". It will then print it out, so you should see "Client Param" on the screen. So request.getParameter() will retrieve a value that the client has submitted. You will get the value on the server side.
-getAttribute() :
request.getAttribute(), this is all done server side. YOU add the attribute to the request and YOU submit the request to another resource, the client does not know about this. So all the code handling this would typically be in servlets.getAttribute always return object.
getParameter - Is used for getting the information you need from the Client's HTML page
getAttribute - This is used for getting the parameters set previously in another or the same JSP or Servlet page.
Basically, if you are forwarding or just going from one jsp/servlet to another one, there is no way to have the information you want unless you choose to put them in an Object and use the set-attribute to store in a Session variable.
Using getAttribute, you can retrieve the Session variable.
from http://www.coderanch.com/t/361868/Servlets/java/request-getParameter-request-getAttribute
A "parameter" is a name/value pair sent from the client to the server
- typically, from an HTML form. Parameters can only have String values. Sometimes (e.g. using a GET request) you will see these
encoded directly into the URL (after the ?, each in the form
name=value, and each pair separated by an &). Other times, they are
included in the body of the request, when using methods such as POST.
An "attribute" is a server-local storage mechanism - nothing stored in
scoped attribues is ever transmitted outside the server unless you
explicitly make that happen. Attributes have String names, but store
Object values. Note that attributes are specific to Java (they store
Java Objects), while parameters are platform-independent (they are
only formatted strings composed of generic bytes).
There are four scopes of attributes in total: "page" (for JSPs and tag
files only), "request" (limited to the current client's request,
destroyed after request is completed), "session" (stored in the
client's session, invalidated after the session is terminated),
"application" (exist for all components to access during the entire
deployed lifetime of your application).
The bottom line is: use parameters when obtaining data from the
client, use scoped attributes when storing objects on the server for
use internally by your application only.
Another case when you should use .getParameter() is when forwarding with parameters in jsp:
<jsp:forward page="destination.jsp">
<jsp:param name="userName" value="hamid"/>
</jsp:forward>
In destination.jsp, you can access userName like this:
request.getParameter("userName")
Basic difference between getAttribute() and getParameter() is the return type.
java.lang.Object getAttribute(java.lang.String name)
java.lang.String getParameter(java.lang.String name)

How to use jsp value in servlets?

i want to use JSP values in servlet. iam fetching some parameters from the url and i need to pass those parameters in my servlet and also the servlet result something by using those parameters and i want to use the result again in the same jsp and in other jsp.
i get those parameters first time when my home jsp is called.
i am getting url parameter by using jstl core tags:
<c:set var="data" scope="session" value="${param.urldata}" />
How do i do this using JSP tags???
Thanks in advance
As i understand somewhat , you are trying to send the values from JSP page to Servlet..
For this we have lot of solution
Pass the value through method
Set the value at session and get it wherever you want in the whole application
I prefer second point, because which hold the value for the entire application
Check Pass variables from servlet to jsp
Above question pass the value from servlet to JSP,Your question is opposite of the answer that's it..!
Set value at JSP : session.setAttribute("key","value");
Get value at Servlet: session.getAttribute("name");
Also refer : Sharing values between servet and JSP

Java Server Page Param confusion

When jsp:include or jsp:forward is executed, the included page or forwarded
page will see the original request object, with the original parameters
augmented with the new parameters and new values taking precedence over
existing values when applicable.
For example, if the request has a parameter
Lname=abc and a parameter Lname=xyz is
specified for forward, the forwarded request
will have Lname=xyz, abc.
The new parameter has precedence
Please explain with an example.
Lets understand main difference between jsp:include and jsp:forward.
jsp:include, includes the page inside the current page. So the included page will appear exactly where u have added the jsp command inside the current page.
e.g.
...
<jsp:include page="inc/include.jsp" />
...
but jsp:forward will forward the current page to the forwarded page. Meaning when the current page is called the forwarded page is called immediately after.
e.g.
if (...) { forwarded to pageOne.jsp }
else if (...) { forwarded to pageTwo.jsp }
Now following is the way we can access parameters for both jsp:forward and jsp:include.
jsp:include : we can access parameters using param not by request object.
e.g.
${param.param1}
while in jsp:forward : we can access parameters using request object.
e.g.
request.getParameter("param1")
This is what the main difference between the parameters in jsp:inlcude and jsp:forward. And thus, we are getting new value in jsp:forward (say Lname=xyz).
example:
say we have a parameter Lname=xyz in request object. In current jsp it can be accessed using below code
<%= (String)request.getParameter("Lname"); %> <%-- This will print xyz on jsp --%>
Now, further the same parameter name can be used with jsp:forward, like...
<jsp:forward page="fwd/pageOne.jsp?Lname=abc" />
or
<jsp:forward page="fwd/pageOne.jsp">
<param name="Lname" value="abc"/>
</jsp:forward>
This will result Lname=abc in fwd/pageOne.jsp using request.getParameter() method.
Thanks

problem with passing bean data from servlet to jsp

I have 2 jsp pages, one called as MyPage.jsp and other as View.jsp. View.jsp has a tree structure. MyPage.jsp has some text fields called as number and design which need to be populated through a bean via servlet. On click of any of the tree node in View.jsp, MyPage.jsp should be rendered with the text fields values set. Now what is happening is since MyPage.jsp is being called twice, i.e. once in View.jsp(in ajax function) and second in the request dispatcher in the servlet so the bean values being set in the servlet are lost. Please suggest a better way so as to retain the values throughout and that on click of the tree node MyPagejsp is rendered with the field values set.
responseBean.setNumber("220");
responseBean.setDesign("xyz");
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
request.setAttribute("responseBean", responseBean);
RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/MyPage.jsp");
requestDispatcher.include(request, response);
response.getWriter().write("Success");
The jsp page from where MyPage.jsp is called with the bean values set has following code
View.jsp
$.ajax({
url : AJAX_SERVLET,
type: "GET",
data: "Number="+node.data.title,
success : function(output) {
$("[id=content]").attr("src", '/Test-portlet/MyPage.jsp');
}
});
}
MyPage.jsp
<jsp:useBean id="responseBean" class="com.web.bean.ResponseBean" scope="request">
<jsp:setProperty name="responseBean" property="*"/>
</jsp:useBean>
<body>
<%System.out.println("Values"+responseBean.getNumber()); %>
</body>
In the above MyPage.jsp code, System.out.println is printing the value twice; once as
Values 202
and second as Values null. Since it replaces the original value with null just because MyPage.jsp is called twice and so the second time value is lost. Please help
I believe that you're confusing/misunderstanding some basic concepts, particularly how HTTP works and how Ajax is supposed to work.
What is happening here is that you're effectively firing two HTTP requests. One by $.ajax() and other by element.attr('src', url). Each request results in a fully distinct bean instance being created and set. You're completely ignoring the bean data in the callback of the $.ajax() request. I am not sure what HTML element [id=content] represents, but I guess that it's an <iframe>. That's not entirely the right way.
You should end up with effectively firing one HTTP request. There are basically 2 solutions:
Forget the $.ajax() and send the request by element.attr('src', url).
$("[id=content]").attr("src", "/Test-portlet/MyPage.jsp?number=" + encodeURIComponent(node.data.title));
You can also change the URL to be a servlet one so that you have a bit more preprocessing control and finally use RequestDispatcher#forward() instead of include(). Do NOT write HTML to the response in the servlet. Let JSP do it.
Forget the <iframe> thing and process the response fully by Servlet/Ajax without intervention of JSP. You would need to convert the bean into other data format which is easily parseable by JavaScript/jQuery. I would suggest to use JSON for this.
$.get(AJAX_SERVLET, { "number": node.data.title }, function(response) {
$("#number").text(response.number);
$("#design").text(response.design);
});
with in HTML for example
<div id="number"></div>
<div id="design"></div>
and in servlet
// ... (create ResponseBean the way as you want)
String json = new Gson().toJson(responseBean);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
See also:
How to use Servlets and Ajax?

How to pass variable from a servlet to a jsp page?

I have a servlet (front-controller), which analyse the request, prepare some necessary data (model) and then should pass it to the jsp to be rendered.
How should I pass the data from servlet to jsp? (I hoped that it was possible to add new parameters to parameters map in the request object, but that map is unmodifiable).
I can add attributes to the request but I don't know how to retrieve them from the jsp.
All the data should be in the request scope. What's the correct way?
I can add attributes to the request but I don't know how to retrieve them from the jsp.
You don't need to specifically 'retrieve' them, just referring them works
request.setAttribute("titleAttribute", "kittens are fuzzy");
and then
Title here: ${titleAttribute}
You can use the request or the session scope for this. Apart from the answer by Nikita Rybak, you can use
request.getSession().setAttribute("key","value");
And then use it in JSP using scriplet.
<%=session.getAttribute("key")%>
Note that in the example given by Nikita, Expression Language(EL) has been used(I am not sure if it's JSTL tags). You need to explicitly state that EL is not to be ignored by using the isELIgnored property.
<%# page isELIgnored="false" %>

Categories

Resources