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.
-
URL query parameters? What have you tried? What hasn't worked? Show us some code. – Matt Ball May 14 '11 at 19:41
3 Answers
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¶m2=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&param2=value2">Send Messages</a>
Note that the &
is &
.

- 22,034
- 5
- 72
- 84
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:
-
-
2@ascanio: no, that would throw `NullPointerException` when `name` is `null`. – BalusC May 14 '11 at 19:47
-
@ascanio: `"facebook"` is just a `String` like others, but it's definitely not `null`. – BalusC May 14 '11 at 19:58
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

- 24,724
- 7
- 65
- 65