Pass values ββfrom jsp to servlet using
I have a jsp page -
<html> <head> </head> <body> <% String valueToPass = "Hello" ; %> <a href="goToServlet...">Go to servlet</a> </body> </html> And the servlet is
@WebServlet(name="/servlet123", urlPatterns={"/servlet123"}) public class servlet123 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } public void foo() { } } What should I write in <a href="goToServlet...">Go to servlet</a> to pass values ββ(for example, valueToPass or add value as argument c) to servlet123 ?
Is it possible to call a specific method in servlet123 (e.g. foo() ) using a link in jsp?
EDIT:
How can I call a servlet in a URL? The hierarchy of my pages is similar to the following:
WebContent |-- JSPtest | |-- callServletFromLink.jsp |-- WEB-INF : : And I want to call servlet123 in the src-> control folder.
I tried <a href="servlet123">Go to servlet</a> but did not find the servlet when I click on the link.
2nd EDIT:
I tried <a href="http://localhost:8080/MyProjectName/servlet123">Go to servlet</a> and it works.
If you want to send parameters to the servlet using the URL, you should do it this way
<a href="goToServlet?param1=value1¶m2=value2">Go to servlet</a> And they retrieve the values ββthat will be available in the request.
Regarding your second question. I will say no. You can add a parameter to ulr, something like
<a href="goToServlet?method=methodName¶m1=value1">Go to servlet</a> And using this information to call a specific method.
By the way, if you use a framework like Struts, it will be easier, since in Struts you can bind a URL to a specific Action method (say, "servlet")
Edited
You defined your servlet as follows:
@WebServlet("/servlet123") You, the servlet will be available on / servlet 123. See doc .
I checked your code and it works:
@WebServlet(name = "/servlet123", urlPatterns = { "/servlet123" }) public class Servlet123 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.write("<h2>Hello Friends! Welcome to the world of servlet annotation </h2>"); out.write("<br/>"); out.close(); } } Then I called the servlet at http://localhost:8080/myApp/servlet123 (being myApp is your application context if you use it).
<a href="url">urltitle</a> allows you to define a URL. Calling a servlet here is as good as calling it from a browser, just provide the URL as you would give it in the browser to call the servlet, for example http://mysite.com?param1=val1¶m2=val2 , etc.
Remember to encode the value if necessary