2016-06-18 74 views

回答

1

你的菜單項的鏈接,類似於此相關:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>simple Servlet</title> 
</head> 
<body> 
<ul> 
    <li><a href="action?action=doThat">that Action</a></li> 
    <li><a href="action?action=doThis">this Action</a></li> 
</ul> 

</body> 
</html> 

部署描述符:

<?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>action</servlet-name> 
     <servlet-class>de.so.ActionServlet</servlet-class> 
    </servlet> 
    <servlet-mapping> 
     <servlet-name>action</servlet-name> 
     <url-pattern>/action</url-pattern> 
    </servlet-mapping> 
</web-app> 

而servlet代碼:

package de.so; 

import java.io.IOException; 
import java.io.Writer; 
import javax.servlet.ServletException; 
import javax.servlet.http.*; 

public class ActionServlet extends HttpServlet 
{ 

    protected void doGet(HttpServletRequest request, 
         HttpServletResponse response) throws ServletException, 
      IOException 
    { 
     String action = request.getParameter("action"); 
     Writer out=response.getWriter(); 

     if (action == null || action.isEmpty()) 
     { 
      out.write("Action empty"); 
     } 
     else if (action.equals("doThis")) 
     { 
      out.write("perform this Action"); 
     } 
     else if (action.equals("doThat")) 
     { 
      out.write("perform that Action"); 
     } 
    } 
} 
+0

@Draken感謝你的答案。你的方式很棒!但我試圖找到如何行動?行動= doThat真的有效,特別是使用問號運算符。我用過?運算符,但作爲if-else語句的替代。再次感謝!! – Xaris

+0

不客氣:-)但我不是Draken :-)'?'不是一個運算符,而只是一個分隔符,它將URI從查詢字符串中分離出來 – JimHawkins

+0

對不起,我的錯誤。我第一次看到德拉肯的名字,並且急着,我不小心寫下了他的名字。原來如此。再一次非常感謝你!!! – Xaris