【问题标题】:How to identify in servlet that call is coming from href link click?如何在 servlet 中识别调用来自 href 链接点击?
【发布时间】:2016-12-15 20:31:05
【问题描述】:

我有一个 JSP 页面,其中有一个如下所示的超链接:

<p class='posDash1'>
    <input type="hidden" name="export" value="export_csv">
    <a href="/admin/" name ="export"><img class="csvFile"  src="/images/excel_logo.gif"/>&nbsp;Export.csv</a>
</p>

现在,如果我单击此超链接,我需要在 servlet 中调用我的方法之一。所以在 href 中,我提供了我的 servlet 名称。这里一切正常,这意味着每当我单击此 href 时,我现在都可以调用我的 servlet 我不确定如何在 servlet 中识别此调用来自 href 链接单击。

所以我添加了一个输入隐藏值,我认为,我将能够识别出这个调用来自 href 点击链接,但不知何故它不起作用:

public void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {

    Response rr = null;

    // but this always come as null
    String export = req.getParameter(export);

    if(export.equals("export_csv)) {

        // do something here
    }

    // some code
}

并且每次导出变量值都以 null 出现,因此我无法确定此调用来自 href 链接单击。有什么办法可以解决这个问题吗?

【问题讨论】:

    标签: java jsp servlets


    【解决方案1】:

    &lt;input&gt; 元素只有在与&lt;form&gt; 一起使用时才会被序列化和发送。您可以改为将查询字符串添加到您的 href 值。

    <a href="/admin?export=export_csv" name ="export">
    

    【讨论】:

    • 感谢 Sotirios 的建议。添加之后,我接下来应该做什么?抱歉问了这么愚蠢的问题..
    • @TrekkieTechieT-T 与您之前尝试做的事情相同。通过带有密钥export 的请求将有一个请求参数可用。使用String export = req.getParameter("export");。显然,在其他情况下,这可能会返回 null,因此您必须进行检查。
    【解决方案2】:

    隐藏值仅适用于表单提交:

    <form action='/admin/' method='post'>
      <input type="hidden" name="export" value="export_csv" />
      <input type='submit' value='Export' />
    </form>
    

    如果你想要一个链接:

    <a href="/admin/?export=export_csv">Export</a>
    

    两者在 servlet 中的读取方式相同。

     request.getParameter("export");
    

    【讨论】:

      【解决方案3】:

      这让我的工作正常

          writer.printf(" <p class=history>%n");
          writer.printf("<input type=\"hidden\" name=\"history\" value=\"showHistory\">%n");
          writer.printf("<a href=\"http://localhost:8080/\"> %n");
          writer.printf("\t<a href=\"http://localhost:8080/?history=\"> <h5>Search History</h5>%n");
          writer.printf("</p>%n");
      

      然后我用这个看看有没有被点击它会通知我。

          if(req.getParameter("history") != null)
          {
              System.out.println("you clicked history! = "+ req.getParameter("history").toString());
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-20
        • 2015-12-12
        • 2020-08-31
        • 1970-01-01
        • 2021-10-21
        • 1970-01-01
        • 1970-01-01
        • 2020-07-14
        相关资源
        最近更新 更多