使用 Javascript/Jquery 访问 Servlet 响应属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17704321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing Servlet Response Attributes With Javascript/Jquery
提问by almel
I am using Java servlets with Tomcat to display a table of Places in HTML. The data in the table's rows consists of info like name, location, etc. and are obtained by taking the servlet response data and injecting it into the tags. Once this is done however, I need to use Javascript to manipulate the "td" elements based their values. So if one of the locations which went into a "td" element was "USA," my Javascript function would do something specific to the "USA" element, like make the surrounding border red, white and blue.
我在 Tomcat 中使用 Java servlet 来显示 HTML 中的位置表。表行中的数据由名称、位置等信息组成,通过获取 servlet 响应数据并将其注入标签中获得。然而,一旦完成,我需要使用 Javascript 来操作基于它们的值的“td”元素。因此,如果进入“td”元素的位置之一是“USA”,我的 Javascript 函数将执行特定于“USA”元素的操作,例如使周围的边框变为红色、白色和蓝色。
I do not want to send a request using $.ajax. I simply want to, within the scope of a script element, access the attributes returned by the servlet response like I do in the following way with JSP scriptlets
我不想使用 $.ajax 发送请求。我只是想在脚本元素的范围内访问由 servlet 响应返回的属性,就像我使用 JSP 脚本的以下方式一样
<% request.getAttribute("location"); %>
I'm kind of surprised I haven't found how to do this online because it seems like an daily action of anyone working with servlets and JS, but I've searched on SO and Google to no avail.
我有点惊讶我还没有找到如何在线执行此操作,因为这似乎是使用 servlet 和 JS 的任何人的日常操作,但我已经在 SO 和 Google 上进行了搜索,但无济于事。
回答by Luiggi Mendoza
As explained by @CarlosGavidia (peruvian fellow), scriplets run in server side while JavaScript (and other frameworks on top of it like jQuery or Dojo) runs in client side e.g. in browser client. Also, scriptlets usage is highly discouraged, detailed explanation here: How to avoid Java code in JSP files?
正如@CarlosGavidia(秘鲁人)所解释的那样,scriplets 在服务器端运行,而 JavaScript(以及它之上的其他框架,如 jQuery 或 Dojo)在客户端(例如浏览器客户端)运行。另外,非常不鼓励使用scriptlets ,这里有详细解释:How to avoid Java code in JSP files?
If you accessed to the last link, you would know that you should use ELand JSTLto access to your page context (PageContext), request (ServletRequest), session (HttpSession) and/or application (ServletContext) attributes (more related info: How to pass parameter to jsp:include via c:set? What are the scopes of the variables in JSP?).
如果您访问了最后一个链接,您就会知道您应该使用EL和JSTL来访问您的页面上下文 (PageContext)、请求 (ServletRequest)、会话 (HttpSession) 和/或应用程序 (ServletContext) 属性(更多相关信息:如何通过c:set传递参数给jsp:include?JSP中变量的作用域是什么?)。
With this background, now you're able to understand that you can't directly access to request attributes (or others from Java code) unless they are set as part of the DOM or injected in javascript code. Showing examples for both cases:
有了这个背景,现在您就可以理解您不能直接访问请求属性(或来自 Java 代码的其他属性),除非它们被设置为 DOM 的一部分或注入到 javascript 代码中。显示两种情况的示例:
Setting the request attribute as part of the DOM.
<input type="hidden" id="hidReqAttr" value="${location}" /> <script type="text/javascript"> function foo() { var fromJavaSide = document.getElementById("hidReqAttr").value; //fromJavaSide value will be ${location} } </script>
Injecting the request attribute directly on JavaScript.
<script type="text/javascript"> function foo() { var fromJavaSide = '<c:out value="${location}" />'; //fromJavaSide value will be ${location} as string } </script>
将请求属性设置为 DOM 的一部分。
<input type="hidden" id="hidReqAttr" value="${location}" /> <script type="text/javascript"> function foo() { var fromJavaSide = document.getElementById("hidReqAttr").value; //fromJavaSide value will be ${location} } </script>
直接在 JavaScript 上注入请求属性。
<script type="text/javascript"> function foo() { var fromJavaSide = '<c:out value="${location}" />'; //fromJavaSide value will be ${location} as string } </script>
Note that using any of these approaches meansthat you can manipulate the Java server variable value using JavaScript but will work onlyon JavaScript side and won't affectthe request attribute value set in the server side. In other words:
请注意,使用这些方法中的任何一种都意味着您可以使用 JavaScript 操作 Java 服务器变量值,但只能在 JavaScript 端工作,不会影响在服务器端设置的请求属性值。换句话说:
<script type="text/javascript">
function foo() {
var fromJavaSide = '<c:out value="${location}" />';
//fromJavaSide value will be ${location} as string
fromJavaSide = fromJavaSide + '_modified';
//last line affects only the JavaScript variable, not the request attribute value
}
</script>
So if one of the locations which went into a "td" element was "USA," my Javascript function would do something specific to the "USA" element, like make the surrounding border red, white and blue.
因此,如果进入“td”元素的位置之一是“USA”,我的 Javascript 函数将执行特定于“USA”元素的操作,例如使周围的边框变为红色、白色和蓝色。
Use a HTML component with an ID or apply a CSS class name to your <td>
to know where you will get your desired value. Using "USA"
as example:
使用带有 ID 的 HTML 组件或将 CSS 类名应用于您的内容,<td>
以了解您将从何处获得所需的值。使用"USA"
示例:
<td class="${location eq 'USA' ? 'usaStyle' : 'commonStyle'}">${location}</td>
<script type="text/javascript">
function foo() {
var usaTDs = document.getElementsByClassName('usaStyle');
//now you have all TDs with usaStyle that has your `USA` text
}
</script>
Based on your comment, you also want to access to request parameters (probably from a query String). Use ${param.parameterName}
to get them. More info in the EL link above, check the Implicit EL objectssection that explains about getting request parameters and other functionalities.
根据您的评论,您还想访问请求参数(可能来自查询字符串)。用${param.parameterName}
得到它们。上面 EL 链接中的更多信息,请查看解释有关获取请求参数和其他功能的隐式 EL 对象部分。
回答by Pradip Wawge
using ajax cal we can cal directly to our servlet class and servlet return string in json format(using gson lib) we can parse json using jquery parse method
$.ajax({
url: "controller/url",
success: function(result){
alert(result);
}});
回答by Carlos Gavidia-Calderon
HTML DOM manipulation should be done with JavaScript. JSP/Servlets are server-side programming techniques and objects like HTTPServletRequest
can′t be accessed through JavaScript: That instances live in the Servlet Container and JavaScript executes in the Client Browser.
HTML DOM 操作应该使用 JavaScript 来完成。JSP/Servlet 是服务器端编程技术和对象,例如HTTPServletRequest
不能通过 JavaScript 访问:实例存在于 Servlet 容器中,而 JavaScript 在客户端浏览器中执行。
On the other side, I see no problems in changing TD
Tag contents through pure JavaScript. You can ease this task using a toolkit like Dojo or JQuery.
另一方面,我认为TD
通过纯 JavaScript更改Tag 内容没有问题。您可以使用诸如 Dojo 或 JQuery 之类的工具包来简化此任务。