Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing post variables using Java Servlets

What is the Java equivalent of PHP's $_POST? After searching the web for an hour, I'm still nowhere closer.

like image 219
Patrick Avatar asked Aug 07 '08 19:08

Patrick


People also ask

What is used for post method in servlet?

POST Method This message comes to the backend program in the form of the standard input which you can parse and use for your processing. Servlet handles this type of requests using doPost() method.

How do I get data in servlet which passed from HTML?

GET method type and doGet() method The doGet() method in servlets is used to process the HTTP GET requests. So, basically, the HTTP GET method should be used to get the data from the server to the browser. Although in some requests, the GET method is used to send data from the browser to the server also.

What is HttpServlet in Java?

A servlet is a Java class that runs in a Java-enabled server. An HTTP servlet is a special type of servlet that handles an HTTP request and provides an HTTP response, usually in the form of an HTML page.


3 Answers

Here's a simple example. I didn't get fancy with the html or the servlet, but you should get the idea.

I hope this helps you out.

<html>
<body>
<form method="post" action="/myServlet">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" />
</form>
</body>
</html>

Now for the Servlet

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {
  public void doPost(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {

    String userName = request.getParameter("username");
    String password = request.getParameter("password");
    ....
    ....
  }
}
like image 110
ScArcher2 Avatar answered Oct 06 '22 07:10

ScArcher2


Your HttpServletRequest object has a getParameter(String paramName) method that can be used to get parameter values. http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletRequest.html#getParameter(java.lang.String)

like image 36
Ryan Ahearn Avatar answered Oct 06 '22 06:10

Ryan Ahearn


POST variables should be accessible via the request object: HttpRequest.getParameterMap(). The exception is if the form is sending multipart MIME data (the FORM has enctype="multipart/form-data"). In that case, you need to parse the byte stream with a MIME parser. You can write your own or use an existing one like the Apache Commons File Upload API.

like image 26
McDowell Avatar answered Oct 06 '22 06:10

McDowell