简体   繁体   English

从JSP页面调用Java类方法

[英]Calling a java class method from a JSP page

I need to call a certain java method when I click a button on a JSP page. 单击JSP页面上的按钮时,需要调用某个java方法。 How do I do this? 我该怎么做呢? I've tried writing a scriptlet into the button's onclick where I create an instance of the class and then use it to call the method, but it doesn't work. 我尝试将scriptlet写入按钮的onclick中,在其中创建该类的实例,然后使用它来调用该方法,但是它不起作用。

What you are trying to do is not possible. 您试图做的事是不可能的。 The button being clicked is an action that happens on the client, away from any server code. 单击的按钮是在客户端上发生的操作,它远离任何服务器代码。 The client doesn't know anything about your java code. 客户端对您的Java代码一无所知。

JSP is an acronym for Java Server Pages. JSP是Java Server Pages的首字母缩写。 It's a technology that provides you the means to combine static html and java code. 这是一项为您提供结合静态html和java代码的方法的技术。 When this is compiled, it will become nothing more than a servlet, a .class file. 当它被编译时,它将只不过是一个servlet,一个.class文件。 This outputs html when it's called. 调用时将输出html。 This html is then handed to the client. 然后将此html交给客户端。 The content handed to the client has no java logic in it. 传递给客户端的内容中没有Java逻辑。 All the java code was used for the generation of this content, while still on the server. 所有Java代码都用于生成此内容,同时仍在服务器上。 After it's generated, it's done, now you only have html, css, javascript. 生成之后,就完成了,现在只有html,css和javascript。

What you need to do is to use some javascript. 您需要做的是使用一些JavaScript。 Assign a click listener to the button you need and make an AJAX call to the server. 将点击侦听器分配给所需的按钮,然后对服务器进行AJAX调用。 Depending on the response you get (from the server to the client), you apply some changes, again, with javascript. 根据获得的响应(从服务器到客户端),再次使用javascript应用一些更改。

There are many ways to apply a listener for the button in question. 有许多方法可以将侦听器应用到相关按钮。

  1. Inline function 内联功能

    <button onclick="myFunction()">Click me</button>

  2. Event listener 事件监听器

    document.getElementById("myBtn").addEventListener("click", displayDate);

Take a look at this and this 看看这个这个

Of course you can use js libraries like jQuery , that provide you hassle free functionality in a few lines of code. 当然,您可以使用jQuery之类的js库,只需几行代码即可为您提供轻松的功能。

If you know only java, and want to get rid off as much of the other technologies as possible, then you could check Google Web Toolkit . 如果您只知道Java,并且想摆脱更多其他技术,则可以查看Google Web Toolkit Basically is a compiler for java to javascript code. 基本上是Java到javascript代码的编译器。

除了以前在服务器端而不是在浏览器中执行Java代码的答案外,如果确实有要在服务器上执行的Java代码,则可以从HTML表单或Ajax调用中发回servlet,有些端点/服务或使用其他Web框架,然后从那里执行代码。

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

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