2012-08-07 93 views
8

I have jsp page -傳遞值使用<a href>

<html> 
<head> 
</head> 
<body> 
     <% 
       String valueToPass = "Hello" ; 
     %> 
    <a href="goToServlet...">Go to servlet</a> 
</body> 
</html> 

And servlet -

@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> in order to pass values (like valueToPass or maybe add the value as argument in the ) to the servlet123 ?

Can I invoke specific method in servlet123 (like foo()) using the link in the jsp ?

EDIT:

How can I call servlet in URL ? My pages hierarchy is like the follow -

WebContent 
|-- JSPtest 
| |-- callServletFromLink.jsp 
|-- WEB-INF 
: : 

And I want to call the servlet123 in the folder src->control .

I tried <a href="servlet123">Go to servlet</a> but it not find the servlet when I press on the link .

2nd EDIT:

I tried <a href="http://localhost:8080/MyProjectName/servlet123">Go to servlet</a> and it work .

回答

6

與Servlet如果你想使用URL參數發送給servlet,你應該這樣做這樣

<a href="goToServlet?param1=value1&param2=value2">Go to servlet</a> 

而且他們檢索,這將是值在請求中可用。

關於你的第二個問題。我會說不。您可以在ulr中添加一個參數,如

<a href="goToServlet?method=methodName&param1=value1">Go to servlet</a> 

並使用該信息調用特定的方法。

順便說一句,如果你使用像Struts的框架,這將是更容易,因爲在Struts中,你可以綁定一個URL到一個特定的動作方法(假設「的servlet」)

編輯

您已經以這種方式定義你的servlet:

@WebServlet("/servlet123") 

你,你的servlet將可以在/ servlet123。請參閱doc

我已經測試你的代碼,它工作:

@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(); 
    } 
} 

然後,我打電話給在Servlet http://localhost:8080/myApp/servlet123(即對myApp你的應用環境,如果您正在使用一個)。

+0

謝謝,所以如果我使用像「goToServlet?param1 = value1&param2 = value2」這樣的使用URL,將會調用servlet中的哪個方法? doGet? – URL87 2012-08-07 07:10:33

+0

您應該使用doGet。看看這個答案:http://stackoverflow.com/a/2349741/980472 – jddsantaella 2012-08-07 07:17:34

+0

好的。最後Q,看我編輯的帖子。 – URL87 2012-08-07 07:25:03

1

<a href="url">urltitle</a> allows you to define a url. Calling a servlet from here is as good as calling it from a browser, just give the url as you would give it in browser to call the servlet like http://mysite.com?param1=val1&param2=val2

+0

感謝,請看到我的編輯在後 – URL87 2012-08-07 07:24:00

+0

現在我該如何找回在第二個servlet參數1和參數的值記住編碼的價值? – Sparker0i 2017-11-17 13:38:44