Reputation: 551
I have, what I believe, is an extremely simple problem, yet all of my attempts to resolve it have failed.
In a nutshell: I have a JSP file with a form that invokes a Java Servlet. The servlet processes the input and returns a variable (attribute) and redirects back to the same jsp. I want to the jsp to process the returned attribute using JavaScript, NOT a scriptlet.
JSP Code (test.jsp):
<html>
...
<%@page language="java"
import="java.sql.*"
import="java.util.*"
%>
...
<body>
<script type='text/javascript'>
var name = session.getAttribute("test");
alert(name);
</script>
...
</body>
</html>
And the Servlet code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
request.getSession().setAttribute("test", "value");
String redirectedPage = "/test.jsp";
RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher(redirectedPage);
reqDispatcher.forward(request,response);
}
I believe that the problem stems from my declaration of the session variable:
var name = session.getAttribute("test");
I have also tried:
var name = (String) session.getAttribute("bob");
and:
String name = (String) session.getAttribute("bob");
I can access this attribute from within my form using a scriptlet (<% %>), but that doesn't allow me to modify/process the returned attribute, which I need to do.
Any help is greatly appreciated. If you feel this question has already been asked/addressed (I've searched), please POLITELY let me know.
Upvotes: 1
Views: 1335
Reputation: 11553
You can not access the session from javascript, but you can of course create your javascript on the server side.
<script type='text/javascript'>
var name = '<%= session.getAttribute("test") %>';
alert(name);
</script>
If you don't have 100% control of the actual value (and maybe even then) it's is a good idea to escape the string. Otherwise someone might inject values that breaks your page (best case) or enables some XSS to steal user data or hijack user session.
Using Apache commons StringEscapeUtils (JavaDoc) It would look like this
<script type='text/javascript'>
var name = '<%= StringEscapeUtils.EscapeJavaScript((String)session.getAttribute("test")) %>';
alert(name);
</script>
If you are going to use this a lot (or maybe just even once) I'd recommend creating a tag that takes the attribute name and outputs a javascript safe string. Maybe as <MyJsTags:AttributeAsString name="test"/> to avoid script lets in your JSP and it also makes it easier if you want to impose new functionality when accessing the attribute.
Upvotes: 4