2016-06-08 20 views
0

我有index.html中:如何從servlet的動作(請求參數)的index.html

<li><a href="list?action=list">List</a></li> 

和servlet類

public class Servlet extends HttpServlet { 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
    String action = request.getParameter("action"); 
    if (action.equalsIgnoreCase("List")){ 
      // do something..... 
     } 
    } 
} 

的web.xml

<servlet> 
     <servlet-name>Servlet</servlet-name> 
     <servlet-class>ru.proj.top.web.Servlet</servlet-class> 
     <load-on-startup>0</load-on-startup> 
    </servlet> 
    <servlet-mapping> 
     <servlet-name>Servlet</servlet-name> 
     <url-pattern>/list</url-pattern> 
    </servlet-mapping> 

servlet中的操作爲空。

如何將此參數從index.html發送到servlet?

+0

請顯示您的'web.xml'。我想對URL映射存在一些誤解。 – JimHawkins

回答

1

我不會爲測試目的命名servlet「Servlet」。可能是,在大世界的某個地方存在一個同名的基類...

所以我把它稱爲「SimpleServlet」。

然後你有這個web.xml(要知道完全合格的類名):

<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns="http://java.sun.com/xml/ns/javaee" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
     version="3.0"> 

    <servlet> 
     <servlet-name>simpleServlet</servlet-name> 
     <servlet-class>de.so.SimpleServlet</servlet-class> 
    </servlet> 
    <servlet-mapping> 
     <servlet-name>simpleServlet</servlet-name> 
     <url-pattern>/list</url-pattern> 
    </servlet-mapping> 
</web-app> 

現在,如果你調用 http://localhost:8080/simpleServlet/list?action=demo, 在doGet()變量action將包含 「演示」

此外,我建議檢查action爲空之前調用其上的方法:

String action = req.getParameter("action"); 
    if (action != null) 
    { 
     // do something 
    } 
    else 
    { 
     // do something else 
    } 
+0

是的,這正是我所做的,但我想從index.html發送操作。 謝謝。 – Geha

+0

請將'index.html'中屬於'List'的URL(如瀏覽器中顯示的,不是HTML源代碼)複製到您的問題中。部署後,您的servlet的路徑是什麼? – JimHawkins

+0

的http://本地主機:8080 /頂/ list動作=名單,現在它的工作原理

  • List
  • 謝謝! – Geha

    0

    從您的問題看起來像web.xml中映射到Servlet <url-pattern>的url與index.html中的元素的href屬性中使用的url不同。將該URL映射更改爲一致之後,代碼應該可以工作。

    如果您使用JSP頁面而不是簡單的HTML頁面,則可以將此值添加到href屬性中以無縫工作。這將動態地將應用程序的上下文路徑添加到url,並會阻止您靜態鍵入您的上下文路徑名。

    <%= request.getContextPath() %>/list?action=list 
    
    +0

    不,它是一樣的。我已經添加了web.xml – Geha

    +0

    @Geha我已經更新了我的答案 – Kaustav

    相關問題