如何从index.html获取servlet操作(请求参数)

时间:2016-06-08 22:23:28

标签: java html servlets

我在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?

2 个答案:

答案 0 :(得分:1)

我不会命名一个servlet&#34; Servlet&#34;用于测试目的。可能是,在大世界的某个地方存在一个同名的基类......

所以我称之为&#34; SimpleServlet&#34;。

然后你有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=demoaction中的变量doGet()将包含&#34; demo&#34;

另外,我建议在调用方法之前检查action是否为null:

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

答案 1 :(得分:0)

从您的问题看来,在web.xml中使用<url-pattern>映射到Servlet的URL与您在href元素中<a/>属性中使用的URL不同。 index.html的。将该URL映射到一致的映射后,代码应该可以工作。

如果您使用JSP页面而不是简单的html页面,则可以将此值添加到href属性以无缝工作。这将动态地将应用程序的上下文路径添加到URL,并将阻止您静态键入上下文路径名。

<%= request.getContextPath() %>/list?action=list
相关问题