简体   繁体   English

如何在单击html元素时从jsp调用java方法?

[英]How to call a java method from a jsp when a html element is clicked?

As title says, how do I call a java class method from a jsp, when certain element is clicked (by example an anchor)? 正如标题所说,当点击某个元素时(例如锚点),如何从jsp调用java类方法? (Without reloading the page) (无需重新加载页面)

If this can be done, how I pass the method, some part of the html code of the page that invokes it? 如果可以这样做,我如何传递方法,调用它的页面的某些部分html代码?

Im using jsp, servlets, javascript, struts2 and java, over Jboss AS. 我在jboss AS上使用jsp,servlets,javascript,struts2和java。

What you want to do is have javascript fire off an AJAX request when the said element is clicked. 你想要做的是在单击所述元素时使用javascript触发AJAX请求。 This AJAX request will go to the server which can then invoke any java code you want. 这个AJAX请求将转到服务器,然后服务器可以调用你想要的任何java代码。

Now you can build this all yourself or you could use one of the many off the shelf solutions. 现在您可以自己构建这个或者您可以使用众多现成解决方案中的一个。 I would recommend Googling around for a JSP Ajax tag library. 我建议使用Google搜索JSP Ajax标记库。 Like this one http://ajaxtags.sourceforge.net/ . 喜欢这个http://ajaxtags.sourceforge.net/

As Marko pointed out , you might need to read some more about the client/server separation in web programming. 正如Marko指出的那样 ,您可能需要阅读有关Web编程中客户端/服务器分离的更多信息。 If you want a framework to help you do remote Java invocation from Javascript, have a look at DWR . 如果您想要一个框架来帮助您从Javascript进行远程Java调用,请查看DWR

You can use a Ajax call to do it . 您可以使用Ajax调用来执行此操作。 Now when the HTML object is clicked call a java-script. 现在,当单击HTML对象时,请调用java脚本。 Then in the JavaScript make a Ajax call to the servlet something like this 然后在JavaScript中对servlet进行Ajax调用

    $.get("Query?ID="+id ,function(RespValue) 
         {


}

Here Query is my servlet mapping defined in web.xml and Id is the parameter i am passing you can sent multiple parameters too. 这里Query是我在web.xml中定义的servlet映射,Id是我传递的参数,你也可以发送多个参数。 and RespValue is the response value returned from the servlet. 和RespValue是从servlet返回的响应值。 In the servelt write a do Get method and execute your java code. 在servelt中编写一个do get方法并执行你的java代码。 If you want to return some value use the function(RespValue) else remove it. 如果要返回某个值,请使用函数(RespValue),否则将其删除。

You can't execute server side java code in client browser. 您无法在客户端浏览器中执行服务器端Java代码。

What you can do is to perform new http request that will perform some action on server and return the action result. 您可以做的是执行新的http请求,该请求将在服务器上执行某些操作并返回操作结果。

Given the tone of the question better go read some JSP tutorial. 鉴于问题的基调更好,请阅读一些JSP教程。 No forum post answer will explain it better. 没有论坛帖子回答会更好地解释它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM