This tutorial will cover a Http Client server application GET/POST in Java Example. The goal of this tutorial is to create a GUI application that connects to the web and shows addition of two numbers. This is tutorial part one for creating the server side application. Part one will cover the web application. The next part will show the GUI creation. and In this tutorial, I am using NetBeans IDE and Glassfish Server. The focus of this application is the following:

  • Create Web application that can add two numbers
  • Create Java application that can take input from webserver

 

The first part is to create Web server application for our client server application. Create a new web application from File > New Project > Java Web and select Web application. Then click Next and type in Project name.

Now click Next and select Glassfish Server and click finish

You will see that a new web application project have been created. Do a right-click on the project and click on run. You will see that your configured browser have started a localhost link using Glassfish Server. My application is showing http://localhost:8080/ClientServerWeb/  according to above project settings. If the server started and localhost url is showing demo web page, then we are in right track. Next step is to start coding out server side application that can return addition of two number using http.

Http Client server application GET/POST in Java Example


Do a right-click on the project and click on New>Servlet . Type in class name as MyServlet Package name as com.web.server then click next and Finish. You will see some auto generated code for your class. At first check that java package name and imports looks like following. Or else import the missing ones. :

package com.web.server;
import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.Double.sum;
import static java.lang.System.out;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

Now delete any following from auto generated code:

            /* TODO output your page here. You may use following sample code. */
            out.println("");
            out.println("");
            out.println("");
            out.println("");            
            out.println("");
            out.println("");
            out.println("

Servlet test at " + request.getContextPath() + "

"); out.println(""); out.println("");

Add the following piece of code at the place of deleted code:

      
 
            String number1param = request.getParameter("num1");
            String number2param = request.getParameter("num2");
// check that number1param and number2param  is not null and continue
            if (number1param != null && number2param != null) {

                double number1 = Double.parseDouble(number1param);
                double number2 = Double.parseDouble(number2param);
                double sum = number1 + number2;

                out.print("The sum of two number is : " + sum);

            } else {
                out.print("Enter two parametere num1 and num2");
            }
        } finally {
            out.close();

Here we declared number1param and number2param to get the value of variable num1 and num1. Then we added a condition to check that number1param and number2param are not null and continue. Then we did a simple mathematical calculation of the numbers and printed the output.

At this point your code will look like the code below:

/*
Http Client server application GET/POST in Java Example 
By Garnel K at www.bytetips.com
 */
package com.web.server;

import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.System.out;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Garnel K
 */
@WebServlet(name = "MyServlet", urlPatterns = {"/MyServlet"})
public class MyServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP GET and POST
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            String number1param = request.getParameter("num1");
            String number2param = request.getParameter("num2");

            if (number1param != null && number2param != null) {

                double number1 = Double.parseDouble(number1param);
                double number2 = Double.parseDouble(number2param);
                double sum = number1 + number2;

                out.print("The sum of two number is : " + sum);

            } else {
                out.print("Enter two parametere num1 and num2");
            }
        } finally {
            out.close();
        }
    }

    // 
    /**
     * Handles the HTTP GET method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP POST method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// 

}

 
Now right click on the file and click on Run file and type in /MyServlet?num1=1&num2=2 and click OK.

You will see a URL like this http://localhost:8080/ClientServerWeb/MyServlet?num1=1&num2=2 and the web page output like The sum of two number is : 3.0 You have successfully created a server side web application that takes two-parameter and shows the result of the addition. The next tutorial will show how to connect the GUI application to provide input parameters.

By Garnel

I like to write about Tips And Tutorials related topics and I blog about my personal interests. I am trying to learn the ways to Promote Blog. Sharing my limited knowledge with the world. Blogging about Tips, Tutorials, and Tweaks for Computers, Internet, Operating System, Windows Xp, Windows Vista, Office Applications, Gadgets, Science, and Technology. And Having Fun..

Leave a Reply

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

14 − ten =