I am doing a simple Java Servlet POST request without using any HTML and only using Postman. And the response from getParameter() is always null.
Here is the servlet:
#WebServlet("/api/form")
public class FormServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String orderNumber = req.getParameter("testString");
System.out.println(orderNumber);
resp.getWriter().print(orderNumber);
}
}
And a picture with responses and how I am doing it:
EDIT
As was commented by Mukesh Verma.
All I had to do was add #MultipartConfig Annotation and I got the data.
This is not how method getParameter works. As stated in this question, you should call the servlet with the following URL:
http://localhost:8080/api/form?testString=test
Try using #MultipartConfig Annotation. It handles form-data mime type.
Changing Postman's radiobutton from form-data to x-www-form-urlencoded also does the trick and I am able to get the data.
Related
I have a post method that takes a Blob as one of its parameters.
My jsp has this
<input type='file' class='form-control' name ='receipt'/>
In my Servlet I have this
*/
#WebServlet("/upload")
#MultipartConfig
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
if(req.getParameterMap().containsKey("receipt")){
// String receipt = req.getParameter("receipt");
Part receipt =req.getPart("receipt");
System.out.println("reciept: " + receipt);
return;
}
receipt returns null for me.
I need to convert receipt to a blob.
I'm using import javax.servlet.http.Part;
and javax-servlet version 3.1
If you are on Servlet 3.0 or later then before using HttpServletRequest#getParts() method , you must annotate your servlet with #MultipartConfig.
I believe you are missing #MultipartConfig tag in your servlet class
#MultipartConfig annotation must be used to indicate that servlet or a form is receiving the Multi Part request from the client.
I am maintaining a Java servlet application and now have to extract the URL from the web service request to determine what action to take depending on what URL called the web service. I have found that it is something to do with HttpServletRequest which I have imported to the class. I have tried setting up the following inside the web service end point but it keeps telling me that the urlrequest is not initialised. What am I doing wrong?
HttpServletRequest urlrequest;
StringBuffer url = urlrequest.getRequestURL();
The HttpServletRequest you are using should be the input parameter HttpServletRequest of either doGet,doPut,doPost or doDelete.
Then Surely HttpServletRequest.getRequestURL will reconstruct the URL used by the client,excluding the query string parameters.
Your code is correct but it has to be accessed within the doPost(request, response), doGet(request, response) etc. methods of a class extending HttpServlet.
The reason for this is the when the service() method of HttpServlet is called, it populates the request and response objects for you given the client who prompted the request to your servlet.
You cannot define a variable in java and call a method on it without initializing it beforehand.
In the first line: HttpServletRequest urlrequest; you are just defining a variable. Since it is not initialized it is null and you cannot use it.
Remove this line and use the argument passed to the doGet (or doPost) method in your Servlet.
For example if your servlet is like this:
public class MyServlet extends HttpServlet {
...
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws Exception {
...
}
Instead of your code just add below line in the body of the doGet method:
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws Exception {
...
StringBuffer url = request.getRequestURL();
...
}
After this line you should be able to use the url variable.
I'm using HttpRequestHandler to inject Spring beans into Servlets:
#Component("myServlet")
public class MyServlet implements HttpRequestHandler {
#Autowired
private MyService myService;
HttpServlet has separate methods doGet, doPost etc for different request methods.
But HttpRequestHandler has only one:
public void handleRequest (HttpServletRequest req, HttpServletResponse resp)
So how to handle GET and POST requests in this method separately? I need to have different logic for different request methods.
UPDATE:
Also I have a question: is there possibility to restrict handleRequest method to support only POST requests by configuration and to sendHTTP Error 405 automatically for other requests?
The HttpServletRequest provides the method 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.
public void handleRequest (HttpServletRequest req, HttpServletResponse resp)
{
if(req.getMethod().equalsIgnoreCase("GET")){
//GET BODY
}
else if(req.getMethod().equalsIgnoreCase("POST")){
//POST BODY
}
}
i have a question on how a servlet call a method and pass the value extracted from the web request. A scenario in which a web request is processed in a web request, i need to call a method and pass in the values extracted from the web request. When the method returns a value, send the value in the web response. thanks
If I understand you right you need something like this:
public class MyNewServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getParameter("paramname");
String result = MyBusinessClass.myBusinessMethod(param);
response.getWriter().append("The answer is: " + result);
}
}
When request comes from browser, it will first read web.xml and call service method of appropriate servlet. Then service method decide to call doPost or doGet method on the basis of request. Once you get parameter , you need to create object of requestDispatcher and call forward method which will send your response.
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.
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.
No direct way.
Non-direct - check .getQueryString()
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
}
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?
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());
}
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
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;
}