How to determine if a parameter has been “posted” or “geted” from Java?

流过昼夜 提交于 2019-12-18 15:04:26

问题


In ASP, there's request.form and request.queryString attributes, but in Java. It seems like we have only one collection, which can be accessed via request.getParamaterMap, getParametersNames, getParameterValues etc.

Is there some way to tell which values have been posted and which ones have been specified in the URL?


PS:

What I'm trying to achieve is to make a page that can handle the following situation

  • Read the variables that came from the querystring (get)
  • Read a single post with a certain name ( "xml", for example ).
  • If that post is missing, read the whole body (with the request.getReader()).

I'm using tomcat 6.

According to what I've seen so far, if I issue a request.getReader(), posted values no longer appears in the getParamater collection, nevertheless querystring parameters are still there.

On the other hand, if I issue any of the getParameters methods, getReader returns empty string.

Seems like I can't have the cake and eat it too.

so, I guess the solution is the folowwing:

  • Read the body with getReader.
  • See if the xml post is there (downside, I have to manually parse the body.
  • If it is, get the http message body and get rid of the "xml=" part.
  • If it's not, well, just get the body.
  • Read the querystring parameters through request.getParameter

Any better idea?

  • PS: Does anybody knows how to parse the body using the same method used by HttpServlet?
  • PS: Here is a decoding ASP function. Shall I just rewrite it in Java?
  • PS: Also found (don't have a machine to test it right now)

Just to clarify things. The problem seems to be that with getParameter you get posted values as well as values passed with the URL, consider the following example:

<%@page import="java.util.*"%>
<%
  Integer i;
  String name;
  String [] values;

  for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {

    name = (String) e.nextElement();
    values = request.getParameterValues( name );

    for ( i=0; i < values.length; i ++ ) {
      out.println( name + ":" + values[i] + "<br/>" );
    }
  }
%>

<html>
<head><title>param test</title>
</head>
<body>
  <form method="post" action="http://localhost:8080/jsp_debug/param_test.jsp?data=from_get">
    <input type="text" name="data" value="from_post">
    <input type="submit" value="ok">
  </form>
</body>
</html>

the output of this code is

data:from_get
data:from_post

...

Seems like in order to find which parameter came from where, I have to check request.getQueryString.


回答1:


HttpServletRequest.getMethod():

Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT. Same as the value of the CGI variable REQUEST_METHOD.

All you need to do is this:

boolean isPost = "POST".equals(request.getMethod());

Also I'm really confused on why you wouldn't simply use request.getParameter("somename") to retrieve values sent as request parameters. This method returns the parameter regardless of whether the request was sent via a GET or a POST:

Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data.

It's a heck of a lot simpler than trying to parse getQueryString() yourself.




回答2:


No direct way. Non-direct - check .getQueryString()




回答3:


If you are writing a servlet, you can make that distinction by whether the doGet or doPost method is invoked.

public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException{

 //Set a variable or invoke the GET specific logic
   handleRequest(request, response);

}

public void doPost(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException{

 //Set a variable or invoke the POST specific logic
 handleRequest(request, response);

}


public void handleRequest(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException{

 //Do stuff with the request

}



回答4:


Why don't you start with checking for query string parameters, if you see none, asume a post and then dig out the form variables?




回答5:


I know it doesn't solve your problem, but if I remember correctly, when using Struts, the ActionForm will be populated if your variables are sent in the query string or in the post body.

I found the source code for the RequestUtils class, maybe the method "populate" is what you need:

http://svn.apache.org/repos/asf/struts/struts1/trunk/core/src/main/java/org/apache/struts/util/RequestUtils.java




回答6:


I did this inside my Filter so maybe someday someone can use this.

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest sreq = (HttpServletRequest)servletRequest;
    System.out.println(sreq.getMethod());
}



回答7:


You can use request.getMethod() to get any Method. I am using HandlerInterceptor for this.

check this code:

public class LoggingMethodInterceptor implements HandlerInterceptor {

Logger log = LoggerFactory.getLogger(LoggingMethodInterceptor.class);

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    log.info("[START]  [" + request.getMethod() + "] [" + request.getRequestURL() + "] StartTime: {} milliseconds",
            System.currentTimeMillis());
    return true;
}


来源:https://stackoverflow.com/questions/1009844/how-to-determine-if-a-parameter-has-been-posted-or-geted-from-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!