9

Is there a way to call a Java Servlet on click of hyperlink without using JavaScript?

John Topley
  • 113,588
  • 46
  • 195
  • 237
sarah
  • 2,387
  • 13
  • 43
  • 50
  • 3
    well, new comments appear as a yellow envelope up there, so you do read them - go and accept the answer that has helped you, or don't expect many people helping you in the future. – Bozho Dec 15 '09 at 18:52

4 Answers4

24

Make the hyperlink have a URL that you have a servlet mapping defined for in the web.xml file.

The servlet-mapping element defines a mapping between a servlet and a URL pattern. The example below maps the servlet named myservlet to any URL that starts with /foo:

<servlet>
  <servlet-name>myservlet</servlet-name>
  <servlet-class>com.stackoverflow.examples.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>myservlet</servlet-name>
  <url-pattern>/foo/*</url-pattern>
</servlet-mapping>
  • For this example, a hyperlink such as <a href="/foo/test.html">Click Me</a> would invoke the servlet.
John Topley
  • 113,588
  • 46
  • 195
  • 237
6
  1. you declare your servlet in web.xml by setting its name, class and url-pattern (let's say your url-pattern is /myServlet)
  2. write <a href="/myServlet">mylink</a>
  3. override the doGet(..) method of the servlet to do whatever you want
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
3

Think that you've defined a servlet "callme" and web.xml has been configured for this servlet. Use the following syntax to call it using hyperlink

web.xml

<servlet>
<description>callme Functions</description>
<display-name>callme</display-name>
<servlet-name>callme</servlet-name> <servlet-class>com.test.Projects.callme</servlet- 
class>
</servlet>

<servlet-mapping>
<servlet-name>callme</servlet-name>
<url-pattern>/callme</url-pattern>
</servlet-mapping>

in JSP:

<a href="<%=request.getContextPath()%>/callme">Call the servlet</a>
Warrior
  • 39,156
  • 44
  • 139
  • 214
1

What exactly do you mean with "call a Java Servlet? The most normal (i.e. without any JavaScript magic) browser behaviour for clicking on a link is to send a HTTP request to fetch the document at the URL specified in the link and display it - and Servlets exist to respond to HTTP requests.

So you don't have to do anything special at all. Just have a regular HTML link and make sure that the servlet you want to "call" corresponds to that link's URL. Of course the next question is what that Servlet returns and what you want the browser to do with it.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720