Last updated on April 20th, 2022 at 08:57 am

Here is a simple approach on how to post a form data to a Servlet, get the response from the external URL and then display it on the browser.

Note this tutorial has been updated to reflect the deployment on latest version of Tomcat 10 (at the time of writing)

My Servlet will be processing an external URL [http://Your_Server_Name/post.php] which is basically a php file that will accept POST request and authenticates with AD / LDAP. Once authenticated it will provide the response as Successful or Not. I am using Tomcat 10 for this tutorial.

We also added a logic on how to redirect to a different page after the post request is completed.

First create a simple HTML form page login.html, This accepts Username/Password

<html>
<body>
<form method="POST" action="/hello/processme">
<h2>Please Enter Your Username and Password</h2>
Username:-<input type="text" name="Username" />
<p>Password:-<input type="password" name="Password" />
<input type="submit" />
</form>
</body>
</html>

Next step is to create a servlet which will process the request from the above HTML form and send it to an external URL. For the demo I have created an external PHP page (https://demo.mistonline.in/from_servlet.php ) that accepts Post parameters named Username and Password. We are also writing a logic in the servlet to display the results of that post request. Make sure to update this variable String url = “”; with the URL of your choice.

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.annotation.*;  // Tomcat 10
import java.util.Properties;
import java.io.*;
 
@WebServlet("/processme") // Configure the request URL for this servlet (Tomcat 7/Servlet 3.0 upwards)
public class HttpRequest extends HttpServlet {
public void doPost(HttpServletRequest request,HttpServletResponse response)
      throws ServletException, IOException {
        PrintWriter out = response.getWriter();
InputStream input = null;
  try {
             String USER_AGENT = "Mozilla/5.0";
 
                out.println("HTTP Post Request Test:-");
               String url = "";
                URL obj = new URL(url);
                HttpURLConnection con = (HttpURLConnection) obj.openConnection();
 
                //add request header
                con.setRequestMethod("POST");
                con.setRequestProperty("User-Agent", USER_AGENT);
                con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
                //Data to be posted
                 
                String getData = request.getParameter("Username");
                String getPass = request.getParameter("Password");
                String urlParameters = "Username="+getData+"&Password="+getPass;
 
                // Send post request
                con.setDoOutput(true);
                DataOutputStream wr = new DataOutputStream(con.getOutputStream());
                wr.writeBytes(urlParameters);
                wr.flush();
                wr.close();
 
                int responseCode = con.getResponseCode();
                out.println("\nSending 'POST' request to URL : " + url);
                out.println("Post parameters : " + urlParameters);
                out.println("Response Code : " + responseCode);
 
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer responseD = new StringBuffer();
 
                while ((inputLine = in.readLine()) != null) {
                        responseD.append(inputLine);
                }
                in.close();
 
                //print result
                out.println("Response From The URL: "+responseD.toString());
 
         
        }
        catch (IOException ex) {
                ex.printStackTrace();
        } finally {
                if (input != null) {
                        try {
                                input.close();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }
                }
        }
}
}

Update the String USER_AGENT = "Mozilla/5.0"; to anything of your choice.

Compile the above code and deploy it on your Application server.

As you might have noticed in the above code we are calling HttpRequest to using URL “/processme” via annotation @WebServlet("/processme"), which is applicable to Tomcat 7 onwards. In other words, the full URL shall be http://ip_addr:port/<your_app>/processme to trigger this HttpRequest

If you are using traditional method of web.xml, Make sure you modify web.xml file according to the servlet information.

<servlet>
    <servlet-name>HttpRequest</servlet-name>
    <servlet-class>HttpRequest</servlet-class>
  </servlet>
<servlet-mapping>
    <servlet-name>HttpRequest</servlet-name>
    <url-pattern>/HttpRequest.do</url-pattern>
  </servlet-mapping>

Once done load the login.html file and see the magic.

Sample output screenshot below

How to redirect to a different page after post?

You may also try to add a window.location option available in Javascript if you would like to redirect to a page. Add this to the HttpRequest before we define post URL variable like below. Change the value from 3000 (3 seconds ) to anything of your choice for the delay.

//Add Redirect start
String javascript="<script>setTimeout(function(){ window.location = 'http://localhost:8080/index.html'; },3000)</script>";
out.println(javascript);
//Add Redirect end
out.println("HTTP Post Request Test:-");
String url = "";

Leave a Reply

Your email address will not be published. Required fields are marked *