I am trying to get attribute of spanId and set Attribute by using request. Then I want to pass the output. Although the first input is has value, it still return me null.
Below are my codes. Help will be appreciate! :)
<input id="spanId" name="spanId">
<%
String spanId = request.getParameter("spanId");
request.setAttribute("spanId",spanId);
%>
<%= request.getParameter("spanId") %>">
Use the getAttribute method instead of getParameter() like
<%= request.getAttribute("spanId") %>">
Just think if you are setting an attribute to request object how you can get it? by using getAttribute.... String spanId = request.getAttribute("spanId").
Also request attribute has request scope (scope lasts only till 1 request).
More on this over here http://docs.oracle.com/javaee/1.4/api/javax/servlet/jsp/JspContext.html
Avoid using scripting elements in your JSP.. remember you are tightly coupling your presentation and business logic.
Related
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'm trying to pass a parameter with <portlet:actionURL> to a portlet in liferay, but it turns out that, using EL to pass values in not working, however, using JSP expression tag is working fine.
Here's my relevant code:
<%
ResultRow row = (ResultRow)request.getAttribute(WebKeys.SEARCH_CONTAINER_RESULT_ROW);
Course course = (Course) row.getObject();
long groupId = themeDisplay.getLayout().getGroupId();
String name = Course.class.getName();
String primaryKey = String.valueOf(course.getPrimaryKey());
%>
<liferay-ui:icon-menu>
<c:if test="<%= permissionChecker.hasPermission(groupId, name, primaryKey, ActionKeys.UPDATE)%>">
<portlet:actionURL name="editCourse" var="editURL">
<portlet:param name="resourcePrimaryKey" value="${primaryKey}"/>
</portlet:actionURL>
<liferay-ui:icon image="edit" message="Edit" url="${editURL}" />
</c:if>
</liferay-ui:icon-menu>
As you see, in <portlet:param> tag, I have used EL for passing value attribute. But it doesn't work, and I receive the value as 0 for "resourcePrimaryKey" in my action method, when I do:
long courseId = ParamUtil.getLong(request, "resourcePrimaryKey");
// courseId is 0 here
However, if I use JSP expression tag in place of EL, it works fine:
<portlet:actionURL name="editCourse" var="editURL">
<portlet:param name="resourcePrimaryKey" value="<%= primaryKey %>"/>
</portlet:actionURL>
Now, I get the required value for "resourcePrimaryKey".
Can anyone figure what's going on here? Surprisingly, EL at other place work fine, as you see - ${editURL} value for url attribute, is working fine, and redirecting to the corresponding url.
I came across this thread on apache mail archive regarding the same issue, but that doesn't really solve the problem.
A variable in the scriptlet cannot be used directly in an EL, you would first need to set it like:
<c:set var="primKey"><%=primaryKey %></c:set>
and use ${primKey} or set it as a request attribute:
request.setAttribute("primKey", primaryKey);
Clearly, better would be to directly use the expression.
Also regarding the ${editURL} working, it is a portlet jsp tag which sets the variable in the page context so that it is available to the EL.
Our el wiki is a good place to know these things, look out for the heading Make objects available to EL for this question :-)
I have a session variable in java file.(TestConnection.java)
session.setAttribute("CONNECTION_DBNAME", dbName);
How to read CONNECTION_DBNAME value into javascript file.(utility.js)
First access the variable in scriptlet.
<%
String param= (String)session.getAttribute("CONNECTION_DBNAME");
%>
Then use like this.
<script>
var X = '<%=param%>';
</script>
then you can access the name using x.
<script>
<%
String dbname=(String)session.getAttribute("CONNECTION_DBNAME");
%>
</script>
this code is usefull to you..
You can use hidden element in JSP to get the value from session like:-
<textarea id="txtData" style.display='none'><%=session.getAttribute("CONNECTION_DBNAME") %></textarea>
afterwards you can get the value in your javascript by var dbConnName=document.getElementById("txtData").value;
and you are done.
Scriptlets were OUTLAWED more than a decade ago!
A better way...
in jsp, include the values in a hidden div:
<div id="javaValues" style="display: none;">
<div id="employee">${employee}</div>
<div id="dept">${dept}</div>
</div>
Use <div>'s rather than <input type="hidden">, since they will not interfere with your form-postings.
In javascript (assuming jQuery) you can then access the values, for example:
var employee = $("#employee").html().trim();
var dept = $("#dept").html().trim();
You cannot access variables in the session from the client. You could provide an Ajax call for the client to dynamically retrieve the value, or leave the value set in a script block.
JSF:
<script>var dbName = "#{myBean.value}";</script>
(Literally from session, the key is the quotes need to be there if it's a string):
<script>var dbName = "#{session.getAttribute('CONNECTION_DBNAME')}";</script>
However, you should reconsider before going in this direction because it makes little sense to give JavaScript access to your database through such a mechanism. Unless your database is publicly exposed, then you appear to be down the path of exposing your database connection details, which the client should not need or have. Your server/page should serve as a relay to get this information.
Now, if this is an admin console, then you probably still don't want it in JavaScript, but displaying the settings is acceptable. Regardless, you probably don't need them in the Session unless the connection details are user specific.
This is probably due to my misunderstanding and incomplete information of JSP and JSTL. I have a web page where I have input elements such as
<input name="elementID" value="${param.elementID}"/>
When I am trying to save the form, I check for that elementID and other elements to conform to certain constraints "numeric, less than XXX". I show an error message if they don't. All the parameters are saved and user does not need to type it again after fixing the error.
After saved, when I am redirecting to the same page for the object to be edited, I am looking a way to set the parameter like request.setParameter("elementID",..) Is there a way to do this ? However the only thing I can find is request.setAttribute.
HTTP responses does not support passing parameters.
JSP/Servelets allows you to either use request.setAttribute or session.setAttribute for that purpose. Both methods are available when processing the page you're redirecting to, So basically, you got it right...
Also, from what you describe, you may want to check client-side validation: don't submit the form until you're validating it using client-side scripting (javascript)
After the servlet processes the form, (ie. saves the user input in the database), have the servlet forward (not redirect, because that would lose the request params) the request to the same jsp which contains the form. So there is no need to set the params since the servlet is just passing back the same request object.
The jsp which contains the form should have inputs similar to this:
<form>
...
<input type="text" value="${elementid}"/>
...
</form>
The syntax ${varname} is EL. So if the elementid already has a value, it that textfield will contain that value. Alternatively if you have not used EL and/or JSTL, you use scriptlets (but that is highly unadvisable, EL and/or JSTL should be the way):
<form>
...
<input type="text" value="<%= request.getParameter("elementid") %>"/>
...
</form>
I had to include <%# page isELIgnored="false"%> to my jsp to allow code like ${elementid} to work
I am redirecting to a JSP that has to print the whole incoming query string. Like in this other question, Request parameter in jsp page, I do not want to access one parameter but the whole query string which I would accomplish in a scriptlet like: <%= request.getQueryString() %>
Thanks!
You can get the paramater object by OGNL stack value #parameters
http://struts.apache.org/2.0.14/docs/ognl-basics.html
If you want to iterate it, you can do something like ( this example create hidden input for each param)
<s:iterator value="#parameters" var="param">
<s:hidden name="%{#param.key}" value="%{#param.value}" />
</s:iterator>
You can user s:iterator tag in struts2 and you can get your string value in Jsp by OGNL lang which is supported by Struts2 without writing code in Scriptlet.
Please check below links for your reference.
http://www.vaannila.com/struts-2/struts-2-example/struts-2-ognl-expression-language-example-1.html
http://www.vaannila.com/struts-2/struts-2-example/struts-2-iterator-tag-example1.html