0

I have an HTML form and want to use Java on the backend. When the form is submitted, I am trying to send a request to an API on the same server. The API request I'm trying to send using a Java SDK requires me to obtain the parameters entered on the HTML form. How can I do this within doPost() in the servlet? Is it possible to use HttpHandler within my servlet doPost() to accomplish this with the POSTed parameters?

Jay S
  • 3
  • 3

1 Answers1

0

Here's a generic form

<form name="loginForm" method="post" action="loginServlet">
Username: <input type="text" name="username"/> <br/>
Password: <input type="password" name="password"/> <br/>
<input type="submit" value="Login" />
</form>

Here, loginServletis your servlet URL.

Your servlet class should extend HttpServlet, and your doPost() method should look like this. Remember to specify your servlet URL inside @webServlet. Alternatively, you can declare and map your servlet inside your web.xml file.

@WebServlet("/loginServlet")
protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    // code to process the form...
}

In the body, you can grab the parameters like so

String username = request.getParameter("username");
String password = request.getParameter("password");

Now you have obtained the form parameters.

Credit to CodeJava http://www.codejava.net/java-ee/servlet/handling-html-form-data-with-java-servlet

Eric Guan
  • 15,474
  • 8
  • 50
  • 61
  • he can also use `request.body` to pass along the parameters without explicitly naming them all. Makes it easier if the form gets updated down the line. – encrest Jul 07 '15 at 03:01
  • Thanks, I understood this but I'm trying to do something more. Within the servlet, I need to be able to use the POSTed parameter values to send another request to an API and get the response. How would I do this within the servlet? @encrest – Jay S Jul 07 '15 at 03:05
  • It depends on what parameters the java SDK you're using takes. If the interface takes a username and password as parameters, then you'd have to get the parameters the way Eric does in his response. – encrest Jul 07 '15 at 03:16