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

标签 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?

最佳答案

出于测试目的,我不会将 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 将包含“demo”

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

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

关于java - 如何从index.html获取servlet操作(请求参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37713934/

相关文章:

java - ListView 仅显示数据库中匹配条件集的 4 条记录中的 3 条

java - servlet 类的 doPost 方法没有给出所需的结果

java - 与 For 行为堆叠

java - 使用自定义登录对话框的 GWT 和 Spring 安全集成

javascript - 动画固定底部栏显示悬停

javascript - 单击按钮后,Bootstrap 5 模式未在 React.js 中显示

php - "Thank you"当有人输入 URL 时页面不应该显示,你会怎么做?

java - 如何在eclipse中访问图像文件(servlet/html)

javascript - 按 T​​AB 键从 javascript 调用 servlet

java - 声明 SQLite getWritableDatabase() 的正确位置