2016-06-18 39 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