Into the Web – Part 5

Hello everyone, today we will see how to write and compile our GreetingServlet class. In the previous part of the series we saw the code template of our servlet class. Did you notice the doGet() method body ? There are only two comments and nothing else is written in the method body. Before start writing the code we have to take care of a few things like defending the invalid inputs, making up the result based on the valid and invalid inputs etc.

Understanding the inputs
The input to our doGet() method comes via the request. Yes – The parameter and value pair the client sent to the server while requesting is the input. Here the input the client sent to the server is any random number from the set (0, 1, 2).Β  So two things are clear here – the input is an integer and its range.

Since we are clear about the input. Now think about the doGet() method. We first write a defensive code to check if the input meet the expectation – a random number from set (0, 1, 2). The server will send a response to the client with a message – “Oops! invalid input.” if the input do not meet the expectations.

Making up the response
There are many methods available in HttpServletResponse class and to move forward with our development we need to two methods setContentType() and getWriter(). The setContentType() method takes String as argument and it is used to set the content type. Say “text/html” if we are going to put html content in the response.Β Alright – what is the use of second method ? Here we have to sent a text message with some opening and closing HTML tags. This is simply character data and to send this we need a PrintWriter object. We accquire the PrintWriter object from the response object by using getWriter() method.

Okay! we got the PrintWriter object. Now what ? We have to put our message (greetings if inputs are fine, error message if input is invalid). Once we accquire the PrintWriter object, we use the write() method to put the text in the response πŸ™‚

If we open something, we have to close the same. The samething we have to do in the case of PrintWriterΒ object we retrived from response – close it when it is done.

The complet code is given below…

Aah wait! We missed one thing. How do we read the parameter value from the request object ? For this we need the parameter name which is “randomNumber” and a method called getParameter()Β which accept the parameter name and return the the value. This method is available in the request object.

Alright lets go through the code!

The code above take care of every possible scenario we discussed above and set the message accordingle πŸ™‚

Alright then. I hope everyone understood the below discussed things. We will see how to compile the GreetingServlet.java file and use it in the web application in the next and final part of Inot the Web.

Please post your thoughts and comments here πŸ™‚

Advertisements

Into the Web – Part 4

In the previous part we have seen how to send a GET request to the server from your web page. Alright! – Now what ? We will see how the server accept the request with the help of Servlets!

The Lifecycle
When a web server receive the request for a servlet, the server maps the request to a servlet. The servlet is dynamically retrieved and loaded into the address space of server. First the class is loaded and then a single instance is created. Once the servlet instance is loaded, the next job is to initialize the instance. Server do this by invoking the init() lifecycle method of the servlet.

Next, the main responsibility of the servlet comes into picture – which is processing the request. The server process the request by invoking service() life cycle method of the servlet. Servlet can read the data from the request an write a response for the client. The servlet will remain in the server address space and process any other requests – For each request it call the service() method.

The last method is destroy(), which is called by the server when it is time to remove the servlet from the memory. The servlet use this method to clean up the resources like file handles, threads, memory etc.

Interface and Classes
The javax.servlet package provides the Servlet interface and it provides the above discussed lifecycle methods. All of the methods in the Servlet interface except the service() method is implemented by the GenericServlet class which is protocol independent and can handle all type request. If we write our servlet class by extending GenericServlet, we have to override the service() method.

We are not going to develop our GreetingServlet class by extending GenericServlet. Instead of this we will use HttpServlet class – which extends the GenericServlet and implement the service() method and based on the method type it invokes the HTTP specific methods doGet(), doPost() etc. While extending the HttpServlet class, we do have to provide an implementation for any of the doXYZ() methods. Since our GreetingServlet class is supposed to handle the GET request, the below given code shows how to do this

Remember the things we discussed in the last part ? Yes – We have to send a random greetings message to the client. We do three things inside the doGet() method.

  • Set the content type of the response
  • Select message based on the index value passed as the parameter
  • Write down the message in the response by

We will see how this things can be done in the next part. Stay tuned πŸ™‚

Please provide your thoughts and comments, about this topic here πŸ™‚

Now Supports Gist!

Happy to announce that we support syntax highlighting in code snippets using GitHub Gist πŸ™‚

Moving forward you will see syntax highlighted code snippets in our tutorials.

So what is Gist ? – Its about sharing our Work! we can share a file, parts of the source code or full application.

Below given is a java program to display the famous “Hello World!” message in the console screen. See the syntax hightlighting πŸ˜‰

Isn’t it cool ? We just write the code and the syntax highliting will be taken care by Gist based on the file extension and inserting the same into wordpress using a single line of text πŸ™‚

Into the Web – Part 3

Our next aim is to create Servlet and see how it respond to client request and send response back to client. So we’ve got two tasks. One – Send a request and two – Receive the response. Here, in this part of “In to the Web” we will see how to create an HTML page which sends a request to the servlet.

When client issue the “localhost:9999/helloworld” URL, the server will return the “index.html” file. This HTML file will display the greeting. When the file first loads, it will send a request to the server targeting GreetingServlet. We will do this with the help of AJAX and jQuery. The response from the servlet is a set of HTML tags. We will insert the HTML tags received in the “index.html” file. The request will have a random number as a parameter, which the servlet use as an index to pick a greeting message.

Hope you are clear with my explanation. So by the end of this part we will see the following.

  • How to send a request to server without refreshing the page
  • How to add a parameter to the request
  • How to add the HTML content in the response to the page

Okay, let me begin πŸ™‚

Generating a random number…

function getRandomInteger(limit) {
 return Math.floor(Math.random() * limit);
}

The function simply takes an integer limit as an argument and returns any number between 0 and limit – 1. The function includes 0 and excludes limit. We have to use this random number as a parameter in the request. The servlet will use this number to randomly pick a greeting message.

Sending a request and receiving a response…

$(function() {
 // ready handler
 randomInteger = getRandomInteger(3);
 $.get('greetings', {randomNumber: randomInteger}, function(responseData) {
  $('#divMessage').append(responseData);
 });
});

The code here is trying to send a GET request to server. This code will be executed immediately when the document is ready. First the code stores a random number to use in the request. Second it creates the GET request. As a last step it process the response from the server.

The first argument of the get() function is our servlet name. the second parameter is a set of request parameters and third one is a response handler. The response handler here takes an argument which is the response from the server. As already mentioned, the response will be a set of HTML tags. Here we will append this tags to and empty div tag with id=”divMessage” defined in the HTML page.

The complete source code of “index.html” is given below πŸ™‚

intothewebp3_img1

Yes, we saw “How to send a request and How to process the response” πŸ™‚

What is next ?? We will see how to develop the Servlet in the upcoming part. Stay tuned πŸ™‚

Into the Web – Part 2

When we look into the code we write, we always go through an indefinite thought process and it stops at simple question in the end “How I can make it Better?”. The word “Better” will stay with you and it will give you some kind of superpower to analyze and breakdown the things you did and you will eventually find an even “Better” way to write the same code.

Now think the the scenario mentioned in the previous part where a server returns some content when client access the web application. Here we had only one static HTML file called “index.html” which always displays the “Hello World!” text.

Now apply the thought process. “How I can make it Better?”

Yes – It would be nice if the server responds with different content every time client sent a request to server. Say user should see a different greetings whenever client send the request –Sounds Good πŸ™‚

Now we have a problem and we have to find a solution.We will see how to do this with the help of Servlets.

Understanding the Deployment Descriptor
As the name says, It describes how a web application should be deployed. Since we use Java language for writing the web application, the deployment descriptor is written using XML syntax and we name it as “web.xml” and store it in “WEB-INF” directory.

Our next step is adding a servlet information in the “web.xml” file. To do this we have two XML elements: servlet and servlet-mapping. We declare the servlet using the servlet element and specify the URL mapping using servlet-mapping element.

<servlet>
    <servlet-name>welcome_greeting</servlet-name>
    <servlet-class>GreetingServlet</servlet-class>
</servlet>

servlet-name element is used to give our servlet a meaningful name and servlet-class element is used to specify the actual servlet Java class (Without extension).

<servlet-mapping>
    <servlet-name>welcome_greeting</servlet-name>
    <url-pattern>/greetings</url-pattern>
</servlet-mapping>

servlet-name element is used specify the name of the servlet to which we can map the URL pattern which is specified using element url-pattern. The URL pattern we give here is used to resolve the URLs. Here we have used pattern “/greetings”. So if we apply URL “localhost:8080/helloword/greetings” we will see the response from our GreetingServlet. The complete “web.xml” file is given below.

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 <!-- To save as "tomcat_home\webapps\helloworld\WEB-INF\web.xml" --> 
 <!-- Note: All <servlet> elements MUST be grouped together and placed IN FRONT of the <servlet-mapping> elements --> 
<servlet>
    <servlet-name>welcome_greeting</servlet-name>
    <servlet-class>GreetingServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>welcome_greeting</servlet-name>
    <url-pattern>/greetings</url-pattern>
</servlet-mapping>
</web-app>

That is all for today and we will see how to write the GreetingServlet class in the coming part using Java language and servlet API πŸ™‚

Into the Web – Part 1

It all started a few months back that I was trying to create a java application to track my daily activities and to learn some of the interesting java libraries and frameworks. But during the process I realized that instead of focusing on desktop based applications, it would be nice if I develop a small web application for that. And the best part is I never explored web development too much and it was challenging, because web development is something big “The technologies used in web development”. All I knew was a set of HTML tags and basic JavaScript and some other areas.

As a first step I started searching in the internet and some of the books about the web application development. Meanwhile during the searching process I came across Servlets “It is basically an executable which runs on the server side”. I learned about the basics of servlets, the related java classes and finally the request response programming model. Like every beginner I started with the “Hello World” program. So here I would like to tell you about my first experience “A servlet which return some HTML content on request.

Setting up the Server
Every web application require a server and to setup a server in my local I used the Appache Tomcat. Tomcat is simply an open source Java servlet container. Download the latest version of the Tomcat server from http://tomcat.apache.org/.

  1. Install the latest stable version of tomcat server
  2. Create a project folder “C:\projects\” and extract the downloaded file here
  3. Rename the folder “apache-tomcat-8.5.**” to “tomcat”
  4. Now we have our tomcat home ready and we will refer directory “C:\projects\tomcat” as tomcat_home

Starting and Stopping the Server
Starting and stopping the tomcat server is easy. We do have two executable files under “tomcat_home\bin\” directory. To start we do use “startup.bat” and to stop we do use “shutdown.bat”
After starting the server we can test this by opening a browser session and typing in “localhost:8080/”. If we are getting a tomcat home page then you are done, the server is up and running. πŸ™‚

Getting started with Web Application Development
Our web application require a root directory and we have to place this root directory under “tomcat_home\webapps\” directory. Let me tell you the steps one by one.

  1. Create a root directory called “helloworld” under “tomcat_home\webapps\” directory.
  2. Now create a new directory called “WEB-INF” under this root directory. We will store the web descriptor file under this directory
  3. Create a new directory called “classes” under the “WEB-INF” directory to store our servlet classes

Now create a new web deployment descriptor file named “web.xml”. The deployment descriptor works like a configuration file and it describe how the application or components should be deployed. The default content of the “web.xml” is given below.<!– Note: All elements MUST be grouped together and placed IN FRONT of the elements –>

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 <!-- To save as "tomcat_home\webapps\helloworld\WEB-INF\web.xml" --> 
 <!-- Note: All <servlet> elements MUST be grouped together and placed IN FRONT of the <servlet-mapping> elements --> 
</web-app>

Okay, now we need to see if the setup is correct or not by restarting the server. If we are getting the below given messages in the console then we are good and our application is deployed successfully πŸ™‚

29-Sep-2017 21:26:43.902 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [C:\Projects\tomcat\webapps\helloworld]
29-Sep-2017 21:26:43.933 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [C:\Projects\tomcat\webapps\helloworld] has finished in [30] ms

Accessing our Web Application
Once the server is up and running we can access the web application by issuing URL “localhost:8080/helloword/” where “8080” is the default port number. We can change this default port number by editing the “server.xml” file available under “tomcat_home\conf\” directory.

Now create a new HTML file “index.html” and save it under “tomcat_home\webapps\helloworld\” directory. In this HTML file we will write HTML tags that are required to display “Hello World” message. The structure of “index.html” is given below.

<html>
    <body>
        <h1>Hello World!</h1>
    </body>
</html>

After saving this file under application root directory which is “tomcat_home\webapps\helloworld”, open a new browser session and issue the below given URL

localhost:8080/helloworld/

Actually this one is a directory request and if out root directory have “index.html”, the server will redirect the request to “index.html” and the browser will display “Hello World!” message. πŸ™‚ You can use the below given URL too.

localhost:8080/helloworld/index.html

That is all for today. We will see how to write a servlet class and use it to process a request and send a response in the next part of “Into the Web”.

Developing a Mini Calculator Part -4

Hello, this is the final part of article on Developing a Mini Calculator. Here we will see how different modules interact with each other and the importance of central module called “Core” in detail.

About Core module in detail

As I mentioned in the previous topics this module is most important part of our calculator application, because it maintain the application state and do connect other modules with each other using messaging system. Input service, output service, calculation logic and history recorder send message to and receive message from core module. Core module do the state change using the messages received from input service and calculation logic.

How Core and other modules work together ?

Input Service generate message based on the key pressed by the user and send the message to core module. The message will have identifier to identify the message, key details. Core will process the message, do some state change and send required messages based on the state change to other modules. Below I will give you a example simple scenario.c

Example: “65+56=”

So once user press “=” operator key calculator should display result “121”.

  1. User enter key 6: This will send message to core module. It will be store as first operand
  2. User enter key 5: Since no operator is entered, core will append “5” to previously entered number “6” and make “65” the first operand
  3. User enter “+” operator key: When processing this key press, core will do a state Β that tell operator is entered now it will accept the second operand. If user press any other operator key to change the operation, this will be taken care by core module using the previous state change.
  4. The same way “56” will be accepted
  5. Now core have first operand, operator and second operand. If user press the next operator key (-,+,*,/), core will send a message to calculation logic including this details. Calculation logic do the required calculation and send back the result to core.
  6. The result given by calculation logic will be the new first operand. The same can be treated as final result as well based on the past input.
  7. In the above steps, core will send the state changes to output service. Output service will display the state changes received to screen.

THE END

Hope you liked the final part πŸ™‚ .

Please access the previous topics here
Developing a Mini Calculator Part – 1
Developing a Mini Calculator Part – 2
Developing a Mini Calculator Part – 3