0
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;

public Test() {
    super();
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();

    out.println("<HTML><HEAD><TITLE>MovieDB</TITLE></HEAD>");
    out.println("<BODY><H1>MovieDB</H1>");

    out.println("<a href = '#' onclick = 'on_Click();'> Call Function </a>");

}

public void on_Click()
{
    System.out.println("HELLO");
}
}

I just want the HTML Link on my page to call my java function on_Click(), what is a good way to do this?

4

2 回答 2

0

The onclick is not Java. It's JavaScript. It's a completely different language than Java. The only things which they've in common are the first 4 characters of the language name, some keywords and a some syntax. But that's it.

Just let the link point to an URL which matches the URL pattern of the servlet mapping. Imagine that you've mapped your servlet on an URL pattern of /foo/*, then just use

<a href="foo">Call function</a>

This will just call the servlet's doGet() method.

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Hello");
}

If you want to reuse the same servlet for multiple actions, just pass some action identifier along as request parameter

<a href="foo?action=bar">Call function</a>

with in doGet() of servlet

String action = request.getParameter("action"); // "bar"

or as path info

<a href="foo/bar">Call function</a>

with in doGet() of servlet

String action = request.getPathInfo().substring(1); // "bar"

No need for weird JavaScript approaches/workarounds.

See also:


Unrelated to the concrete problem, HTML belongs in JSP, not in Servlet.

于 2013-02-01T00:32:14.807 回答
0

A servlet runs on your server, while HTML runs on the user's computer so you'll need to use javascript/ajax to send a request to your server to execute your on_Click function.

于 2013-02-01T00:32:29.050 回答