How to set a cookie value within JSP using an EL expression? - java

I'm trying to set a cookie value within a JSP without using Java code directly. I know I could do it by creating a custom tag lib for that, but I wanted to keep it simple so I'm trying to do that the same way I access cookies: with EL expressions.
I know I can read the value of a cookie using JSP EL with the expression ${cookie['cookieName'].value}, but how can I set a particular value to that cookie using EL? I found solutions using java code in the JSP, but I want to avoid that.
So far I found ways to set variables using the c:set tag, but that doesn't accept expressions as the 'var' parameter so I can't do something like:
<c:set var="${cookie['cookieName'].value}" value="123" />
I think the way to go is , but I don't know what expression to use for the var part of it, or how to write it so I can set the cookie value instead of just a variable.
Any help is appreciated!

There is no standard expression to set cookie in JSP. You can use custom tag if you want OR use JSP script-less
<%
javax.servlet.http.Cookie cookie
= new javax.servlet.http.Cookie("name", "value");
// cookie.setXXX()
response.addCookie(cookie);
%>
NOTE: Make sure cookie is added BEFORE the response is committed.

Related

Fetchinng JSON data from servlet to display on JSP [duplicate]

I have a form in JSP. I have to populate it based on the request object (from the servlet). How do I use Java Script for accessing request object attributes or if you can suggest me any other better way to populate form dynamically?
You need to realize that Java/JSP is merely a HTML/CSS/JS code producer. So all you need to do is to just let JSP print the Java variable as if it is a JavaScript variable and that the generated HTML/JS code output is syntactically valid.
Provided that the Java variable is available in the EL scope by ${foo}, here are several examples how to print it:
<script>var foo = '${foo}';</script>
<script>someFunction('${foo}');</script>
<div onclick="someFunction('${foo}')">...</div>
Imagine that the Java variable has the value "bar", then JSP will ultimately generate this HTML which you can verify by rightclick, View Source in the webbrowser:
<script>var foo = 'bar';</script>
<script>someFunction('bar');</script>
<div onclick="someFunction('bar')">...</div>
Do note that those singlequotes are thus mandatory in order to represent a string typed variable in JS. If you have used var foo = ${foo}; instead, then it would print var foo = bar;, which may end up in "bar is undefined" errors in when you attempt to access it further down in JS code (you can see JS errors in JS console of browser's web developer toolset which you can open by pressing F12 in Chrome/FireFox23+/IE9+). Also note that if the variable represents a number or a boolean, which doesn't need to be quoted, then it will just work fine.
If the variable happens to originate from user-controlled input, then keep in mind to take into account XSS attack holes and JS escaping. Near the bottom of our EL wiki page you can find an example how to create a custom EL function which escapes a Java variable for safe usage in JS.
If the variable is a bit more complex, e.g. a Java bean, or a list thereof, or a map, then you can use one of the many available JSON libraries to convert the Java object to a JSON string. Here's an example assuming Gson.
String someObjectAsJson = new Gson().toJson(someObject);
Note that this way you don't need to print it as a quoted string anymore.
<script>var foo = ${someObjectAsJson};</script>
See also:
Our JSP wiki page - see the chapter "JavaScript".
How to escape JavaScript in JSP?
Call Servlet and invoke Java code from JavaScript along with parameters
How to use Servlets and Ajax?
If you're pre-populating the form fields based on parameters in the HTTP request, then why not simply do this on the server side in your JSP... rather than on the client side with JavaScript? In the JSP it would look vaguely like this:
<input type="text" name="myFormField1" value="<%= request.getParameter("value1"); %>"/>
On the client side, JavaScript doesn't really have the concept of a "request object". You pretty much have to parse the query string yourself manually to get at the CGI parameters. I suspect that isn't what you're actually wanting to do.
Passing JSON from JSP to Javascript.
I came here looking for this, #BalusC's answer helped to an extent but didn't solve the problem to the core. After digging deep into <script> tag, I came across this solution.
<script id="jsonData" type="application/json">${jsonFromJava}</script>
and in the JS:
var fetchedJson = JSON.parse(document.getElementById('jsonData').textContent);
In JSP file:
<head>
...
<%# page import="com.common.Constants" %>
...
</head>
<script type="text/javascript">
var constant = "<%=Constants.CONSTANT%>"
</script>
This constant variable will be then available to .js files that are declared after the above code.
Constants.java is a java file containing a static constant named CONSTANT.
The scenario that I had was, I needed one constant from a property file, so instead of constructing a property file for javascript, I did this.
In JSP page :
<c:set var="list_size" value="${list1.size() }"></c:set>
Access this value in Javascipt page using :
var list_size = parseInt($('#list_size').val());
I added javascript page in my project externally.

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

Access properties of 1 java bean in session using c:out tag

I am trying to output text value of a property of a bean in session in a JSP. I need to output it between tag. I am struck up on the syntax. Here is my code till now
<%EditTicketBean etlBean= (EditTicketBean)session.getAttribute("etBeanInServlet");
<textarea><c:out value = "${etlBean.ticketDesc}" />
However this does not work. If I use out.println it works
<textarea><%out.println(etlBean.getTicketDesc());%> </textarea>
What is the correct syntax for using this JSTL tag
Why are you mixing JSTL and scriplets? You can't access the variables set in scriplets, inside an EL. Better option is to avoid that scriplet alltogether, and just use EL, to access attributes from session.
You can directly use the EL expression:
<textarea>${etBeanInServlet.ticketDesc}</textarea>
you can also explicitly specify that you are fetching the attribute from session scope (only when there is conflict between variables set in various scopes) like so:
<textarea>${sessionScope.etBeanInServlet.ticketDesc}</textarea>
and finally using using JSTL <c:out> tag, which will escape XML for you:
<textarea><c:out value="${etBeanInServlet.ticketDesc}" /></textarea>

Change JSP custome attribute value using javascript for JSP custome tag

I have developed JSP custom tag named <ctn:input mandatory = true> with one custom attribute named mandatory.
Now i want to change mandatory value to false on click event of some other tag.
I am not able to change it using document.getElementById(id).mandatory = "false".
Is it possible ? how ?
<ctn:input mandatory = true> is server side stuff and client will not recieve this as HTML dom so your java script won't play with it. You need to find out some other way for the same
With javascript you can only modify values in the rendered html. It won't effect your backend coding.
In this case you can't use javascript to change value...but you can use
<c:if > </c:if>
inside ur attribute value. for ex.
<ctn:input mandatory = "<c:if test='{yourCondition}'>true </c:if>">
or we can use choose here too...EX.
this will select true if your condition is fulfilled of else it will set "false"
<ctn:input mandatory = "<c:choose><c:when test="${condition/variable}">true </c:when><c:otherwise>false</c:otherwise>">

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