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?
The
onclickis 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 useThis will just call the servlet’s
doGet()method.If you want to reuse the same servlet for multiple actions, just pass some action identifier along as request parameter
with in
doGet()of servletor as path info
with in
doGet()of servletNo need for weird JavaScript approaches/workarounds.
See also:
Unrelated to the concrete problem, HTML belongs in JSP, not in Servlet.