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.
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 &
.
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:
- Servlets info page
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
精彩评论