简体   繁体   English

如何获得特定的请求属性?

[英]How can I get specific Request Attributes?

So right now I have code that will display the from the url: 所以现在我有将显示url中的代码:

URL: 网址:

http://localhost:9080/MyWebApp/MyServlet?qty=1&item=100&desc=CD+ROMS&price=9.99&action=add&addToCart=Add+to+cart

What is shown: 显示内容:

    Recent Queries
    Item_100

And here is the code that will display that: 这是显示该代码的代码:

public String getRecentQueries(HttpServletRequest request)
{
    String queries = "";
    HttpSession session = request.getSession(false);
       if (session != null)
       {
          Enumeration e = session.getAttributeNames();
          if ( e.hasMoreElements() )
          {
             queries += "<h4>Recent Queries</h4><ul>";
          }
          while ( e.hasMoreElements() )
          {
             String name = (String) e.nextElement();
             String value =
                (String) session.getAttribute(name);
             queries += "<li><a href=\"" + value + "\">" + 
                name + "</a></li>";
          }
          queries += "</ul></p>";
       }
       return queries;
}

My question is, given the values in the url, how do I get something other than just ' item '? 我的问题是,给定URL中的值,我如何获取除“ item ”以外的内容? How would I get desc , or price ? 我怎么会得到desc ,还是price

Try this. 尝试这个。 You need to be pulling the parameter names and values directly from the request, not the attributes from the session. 您需要直接从请求中提取参数名称和值,而不是从会话中提取属性。

public String getRecentQueries(HttpServletRequest request)
{
    String queries = "";
    Enumeration e = request.getParameterNames();

    if ( e.hasMoreElements() )
    {
        queries += "<h4>Recent Queries</h4><ul>";
    }

    while ( e.hasMoreElements() )
    {
        String name = (String) e.nextElement();
        String value = (String) request.getParameter(name);
        queries += "<li><a href=\"" + value + "\">" + name + "</a></li>";
    }
    queries += "</ul></p>";

    return queries;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM