This is an error that came up after I got a previous question he开发者_如何学Pythonre answered. Essentially I'm trying to bring the absPath of the folder with me so I can make some Files at runtime regardless of where my code is located. I was recommended to use
getServletContext().getRealPath("/");
To find the correct path.
I tried it in my JSP page, but I get an unterminated string literal right when I create the absPath variable. Here is the script I try to run.
<script type="text/javascript">
var RemoteUserId = "<%=(request.getRemoteUser()==null)? "blah" : request.getRemoteUser()%>";
var contextPath = "<%= request.getContextPath()%>";
var extPath = "<%=extPath%>";
var absPath = "<%=getServletContext().getRealPath("/")%>";
var env='<%=string1%>';
</script>
What am I missing? Do I have to escape the returned path name, or did I misinterpret when I was supposed to use this.
Edit** This is what the source shows upon accessing the page
(slightly tweaked so I'm not showing my full C: path)<script type="text/javascript">
var RemoteUserId = "blah";
var contextPath = "/TRACK";
var extPath = "http://xxx/sales/it/tlp/ext-3.2.1";
var env='null';
var absPath = "C:\Documents and Settings...\TRACK\";
</script>
Like as in Java, backslashes are escape characters in JS. You need to escape them to represent a literal backslash. In other words, your absPath
variable must end up as
var absPath = "C:\\Documents and Settings...\\TRACK\\";
You could do this by
var absPath = "<%=getServletContext().getRealPath("/").replace("\\", "\\\\")%>";
But still, it makes no sense to me to pass a Java variable back to Java via JavaScript. Just access it in the Java side when the code is about to process the request. Imagine that you're using a servlet to process the request, just do
String absPath = getServletContext().getRealPath("/");
instead of
String absPath = request.getParameter("absPath");
(or whatever you're doing to get the absPath
back in your Java code)
Also note that all the JavaScript code is fully controllable/spoofable/hackable by the client. The client is able to edit JavaScript variables while the code is running. The client could for instance change the path before it is been used. Keep this in mind!
精彩评论