1

I need to send a particular parameters to Servlet from JSP page. E.g: if I click on the Facebook icon on the web page, then I should send "facebook" as parameter to my Servlet and my Servlet will respond according to the parameter received from JSP file or HTML file.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Jeevan Dongre
  • 4,627
  • 13
  • 67
  • 129

3 Answers3

5

This is a very open ended question, but the easiest way is to specify parameters in a query string.

If you have the following servlet:

/mysite/messageServlet

Then you can send it parameters using the query string like so:

/mysite/messageServlet?param1=value1&param2=value2

Within the servlet, you could check your request for parameters using getParameter(name) if you know the name(s), or getParameterNames(). It's a little more involved, specifically with consideration to URL Encoding and statically placing these links, but this will get you started.

String message = request.getParameter("message");
if ("facebook".equals(message))
{
    // do something
}

Storing links with multiple parameters in the querystring requires you to encode the URL for HTML because "&" is a reserved HTML entity.

<a href="/servlets/messageServlet?param1=value&amp;param2=value2">Send Messages</a>

Note that the & is &amp;.

pickypg
  • 22,034
  • 5
  • 72
  • 84
4

Just wrap the icon in a link with a query string like so

<a href="servleturl?name=facebook"><img src="facebook.png" /></a>

In the doGet() method of the servlet just get and handle it as follows

String name = request.getParameter("name");

if ("facebook".equals(name)) {
    // Do your specific thing here.
}

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
2

One way is to have hidden form variables in your jsp page that get populated on click.

<form action="post" ....>
<input type="hidden" id="hiddenVar" value="">
<a hfref="#" onclick="doSomething();">Facebook</a>
</form>
<script>
      function doSomething() {
              var hiddenVar= document.getElementById('hiddenVar');
              hiddenVar.value = "facebook";
              form.submit();

      }
 </script>

This gives you flexibility to control what gets passed to your servlet dynamically without having to embed urls in your href

Kal
  • 24,724
  • 7
  • 65
  • 65