Sending multiple parameters to servlets from either JSP or HTML

16,390

Solution 1

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:

Solution 2

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;.

Solution 3

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

Share:
16,390
Jeevan Dongre
Author by

Jeevan Dongre

Geek under construction, Google fanboy, passionate learner, startup lover, business and tech savya, social media addict, biker, musician, extrovert, realistic, seminal, approachable.

Updated on November 20, 2022

Comments

  • Jeevan Dongre
    Jeevan Dongre over 1 year

    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.

    • Matt Ball
      Matt Ball almost 13 years
      URL query parameters? What have you tried? What hasn't worked? Show us some code.
  • ascanio
    ascanio almost 13 years
    here you mean if (name.equals("facebook"))
  • BalusC
    BalusC almost 13 years
    @ascanio: no, that would throw NullPointerException when name is null.
  • BalusC
    BalusC almost 13 years
    @ascanio: "facebook" is just a String like others, but it's definitely not null.