Ank*_*kur 8 javascript java jsp servlets argument-passing
你能用一个链接调用一个servlet吗?例如
<a href="/servletName">link text</a>
Run Code Online (Sandbox Code Playgroud)
并且可能通过将参数添加到查询字符串来将参数传递给请求对象.
如果没有,我看到了这样的事情:
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(/MyServlet);
dispatcher.include(request,response);
Run Code Online (Sandbox Code Playgroud)
但是我该如何触发呢?例如,如果它是JavaScript代码,我可以将它放在jQuery单击函数中,或者如果这是一个servlet,我会将它放入一个方法中.
但是如何在JSP中调用此代码.据我所知,你不能用JavaScript事件调用Java代码.
Boz*_*zho 12
<a href="servletUrl?param=value">click</a>
Run Code Online (Sandbox Code Playgroud)
是完全合法的,并将工作.
这将doGet(..)调用servlet 的方法,并且可以使用参数获取request.getParameter("param")
Bal*_*usC 10
只是为了清除误解:
据我所知,你不能用Javascript事件调用Java代码.
您可以使用JavaScript代码(和事件)完美地调用Java代码.到目前为止,您只需要让JavaScript向服务器端发送一个完整的HTTP请求.基本上有三种方法.
第一种方法是模拟现有链接/按钮/表单的调用.例如
<a id="linkId" href="http://www.google.com/search?q=balusc">Link</a>
<script type="text/javascript">
document.getElementById('linkId').click();
</script>
Run Code Online (Sandbox Code Playgroud)
和
<form id="formId" action="http://www.google.com/search">
<input type="text" id="inputId" name="q">
</form>
<script type="text/javascript">
document.getElementById('inputId').value = 'balusc';
document.getElementById('formId').submit();
</script>
Run Code Online (Sandbox Code Playgroud)第二种方法是使用window.location来触发普通的GET请求.例如:
<script type="text/javascript">
var search = 'balusc';
window.location = 'http://www.google.com/search?q=' + search;
</script>
Run Code Online (Sandbox Code Playgroud)第三种方法是使用XMLHttpRequest对象来触发异步请求并处理结果.这种技术是"Ajax"的基本思想.这是Firefox兼容的示例:
<script type="text/javascript">
function getUrl(search) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var responseJson = eval('(' + xhr.responseText + ')');
var url = responseJson.responseData.results[0].unescapedUrl;
var link = document.getElementById('linkId');
link.href = link.firstChild.nodeValue = url;
link.onclick = null;
}
}
var google = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q='
xhr.open('GET', google + search, true);
xhr.send(null);
}
</script>
<p>My homepage is located at: <a id="linkId" href="#" onclick="getUrl('balusc')">click me!</a></p>
Run Code Online (Sandbox Code Playgroud)
这可以使用jQuery以更短和交叉浏览器兼容的方式重写.
只需http://www.google.com/search用您自己的servlet 替换即可使上述示例在您的环境中工作.
有关更多背景信息,您可能会发现本文也很有用.