I'm trying to retrieve attribute values set by a servlet in a JSP page, but I've only luck with parameters by ${param}. I'm not sure about what can I do different. Maybe its simple, but I couldn't manage it yet.
public void execute(HttpServletRequest request, HttpServletResponse response) {
//there's no "setParameter" method for the "request" object
request.setAttribute("attrib", "attribValue");
RequestDispatcher rd = request.getRequestDispatcher("/Test.jsp");
rd.forward(request,response);
}
In the JSP I have been trying to retrieve the "attribValue", but without success:
<body>
<!-- Is there another tag instead of "param"??? -->
<p>Test attribute value: ${param.attrib}
</body>
If I pass a parameter through all the process (invoking page, servlets and destination page), it works quite good.
It's available in the default EL scope already, so just
${attrib}
should do.
If you like to explicitly specify the scope (EL will namely search the page, request, session and application scopes in sequence for the first non-null attribute value matching the attribute name), then you need to refer it by the scope map instead, which is ${requestScope} for the request scope
${requestScope.attrib}
This is only useful if you have possibly an attribute with exactly the same name in the page scope which would otherwise get precedence (but such case usually indicate poor design after all).
See also:
Our EL wiki page
Java EE 6 tutorial - Expression Language
Maybe a comparison between EL syntax and scriptlet syntax will help you understand the concept.
param is like request.getParameter()
requestScope is like request.getAttribute()
You need to tell request attribute from request parameter.
have you tried using an expression tag?
<%= request.getAttribute("attrib") %>
If the scope is of request type, we set the attribute using request.setAttribute(key,value) in request and retrieve using ${requestScope.key} in jsp .
Related
When we can access all the implicit variables in JSP, why do we have pageContext ?
My assumption is the following: if we use EL expressions or JSTL, to access or set the attributes we need pageContext. Let me know whether I am right.
You need it to access non-implicit variables. Does it now make sense?
Update: Sometimes would just like to access the getter methods of HttpServletRequest and HttpSession directly. In standard JSP, both are only available by ${pageContext}. Here are some real world use examples:
Refreshing page when session times out:
<meta http-equiv="refresh" content="${pageContext.session.maxInactiveInterval}">
Passing session ID to an Applet (so that it can communicate with servlet in the same session):
<param name="jsessionid" value="${pageContext.session.id}">
Displaying some message only on first request of a session:
<c:if test="${pageContext.session['new']}">Welcome!</c:if>
note that new has special treatment because it's a reserved keyword in EL, at least, since EL 2.2
Displaying user IP:
Your IP is: ${pageContext.request.remoteAddr}
Making links domain-relative without hardcoding current context path:
login
Dynamically defining the <base> tag (with a bit help of JSTL functions taglib):
<base href="${fn:replace(pageContext.request.requestURL, pageContext.request.requestURI, pageContext.request.contextPath)}/">
Etcetera. Peek around in the aforelinked HttpServletRequest and HttpSession javadoc to learn about all those getter methods. Some of them may be useful in JSP/EL as well.
To add to #BalusC's excellent answer, the PageContext that you are getting might not be limited to what you see in the specification.
For example, Lucee is a JSP Servlet that adds many features to the interface and abstract classes. By getting a reference to the PageContext you can gain access to a lot of information that is otherwise unavailable.
All 11 implicit EL variables are defined as Map, except the pageContext variable.
pageContext variable provides convenient methods for accessing request/response/session attributes or forwarding the request.
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.
How would I pass hidden parameters? I want to call a page (test.jsp) but also pass 2 hidden parameters like a post.
response.sendRedirect("/content/test.jsp");
TheNewIdiot's answer successfully explains the problem and the reason why you can't send attributes in request through a redirect. Possible solutions:
Using forwarding. This will enable that request attributes could be passed to the view and you can use them in form of ServletRequest#getAttribute or by using Expression Language and JSTL. Short example (reusing TheNewIdiot's answer] code).
Controller (your servlet)
request.setAttribute("message", "Hello world");
RequestDispatcher dispatcher = servletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
View (your JSP)
Using scriptlets:
<%
out.println(request.getAttribute("message"));
%>
This is just for information purposes. Scriptlets usage must be avoided: How to avoid Java code in JSP files?. Below there is the example using EL and JSTL.
<c:out value="${message}" />
If you can't use forwarding (because you don't like it or you don't feel it that way or because you must use a redirect) then an option would be saving a message as a session attribute, then redirect to your view, recover the session attribute in your view and remove it from session. Remember to always have your user session with only relevant data. Code example
Controller
//if request is not from HttpServletRequest, you should do a typecast before
HttpSession session = request.getSession(false);
//save message in session
session.setAttribute("helloWorld", "Hello world");
response.sendRedirect("/content/test.jsp");
View
Again, showing this using scriptlets and then EL + JSTL:
<%
out.println(session.getAttribute("message"));
session.removeAttribute("message");
%>
<c:out value="${sessionScope.message}" />
<c:remove var="message" scope="session" />
Generally, you cannot send a POST request using sendRedirect() method. You can use RequestDispatcher to forward() requests with parameters within the same web application, same context.
RequestDispatcher dispatcher = servletContext().getRequestDispatcher("test.jsp");
dispatcher.forward(request, response);
The HTTP spec states that all redirects must be in the form of a GET (or HEAD).
You can consider encrypting your query string parameters if security is an issue.
Another way is you can POST to the target by having a hidden form with method POST and submitting it with javascript when the page is loaded.
Using session, I successfully passed a parameter (name) from servlet #1 to servlet #2, using response.sendRedirect in servlet #1. Servlet #1 code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
String name = request.getParameter("name");
String password = request.getParameter("password");
...
request.getSession().setAttribute("name", name);
response.sendRedirect("/todo.do");
In Servlet #2, you don't need to get name back. It's already connected to the session. You could do String name = (String) request.getSession().getAttribute("name"); ---but you don't need this.
If Servlet #2 calls a JSP, you can show name this way on the JSP webpage:
<h1>Welcome ${name}</h1>
To send a variable value through URL in response.sendRedirect(). I have used it for one variable, you can also use it for two variable by proper concatenation.
String value="xyz";
response.sendRedirect("/content/test.jsp?var="+value);
Use this:
out.println("<script>window.location.href = \"hoadon?OrderId=" + getIdOrder + "\"\n</script>>");
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)
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