开发者

Accessing the ServletContext from JS

I figured out how to grab the ServletContext on the java end looking at this thread, but I still am unsure how to grab it in the JS. I was looking at this explanation for the JS. Do I have to pass the ServletContext as a request object (can I se开发者_开发百科e an example) or could I just access it in the JS? Any help much appreciated.


If you're talking about JavaScript as part of web pages, you can't access it at all. That JavaScript is being executed on the browser after the page loads. At this point, the ServletContext is long gone.

What you probably want to do is generate JavaScript based on the ServletContext. This is simply a matter of printing what you want in the JavaScript as constants that are rendered in to the page via the JSP that creates it, just like for HTML etc. At this point it's not JavaScript, it's simply text like anything else in the JSP page.


Unless you are doing server-side javascript you cannot get a handle to the ServletContext because it simply doesn't exist in the browser. What you can do, though, is to read required attributes from ServletContext and create dynamic Javascript in your JSP/Servlet etc.


JS runs on the client side from within browser. Java objects available in the container can be accessed from within the Java code written in JSP/Servlets.

ServletContext object cannot be directly accessed from within JS - simply because the process and the context in which JS runs is different from the VM/Context in which ServletContext object exists.

From your question it appears that you want to access object data accessible to JS - you can achieve this by using JS-Java bridge like DWR (Direct Web Remoting) - please have a look at the link - http://directwebremoting.org/dwr/index.html


Application implicit object is an instance of javax.servlet.ServletContext. It is basically used for getting initialization parameters and for sharing the attributes & their values across the entire JSP application, which means any attribute set by application implicit object would be available to all the JSP pages. in our JSP page, we used below in javascript function enclosed by tag

<script type="text/javascript">  
somefunction(){
var somevar = <%=application.getAttribute("attributeName")>
}
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜