Tuesday, September 30, 2014

Calling a Servlet Using JQuery Ajax

When developing web applications it is very common to use Ajax to call a Servlet and get a desired response.
In this lesson I will show you how to use JQuery to send an Ajax call to a Servlet.

1. First create a new web applications(In eclipse : New => Dynamic Web Project)
2. Right click on the src folder and create a new Servlet(New => Servlet). I name the servlet as MyServlet.
3. Change the servlet so that it prints some meaningful text. My servlet is as below.

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

@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
       
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter pw = response.getWriter();
pw.println("Hello from server via GET...!");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter pw = response.getWriter();
pw.println("Hello from server via POST...!");
}
}

4. Right. Servlet is created. Now I need to call this servlet from JQuery.
5. Create a new JSP page in web apps folder. I name it as index.jsp.
6. Now change the contents of the page as below.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
   $('#btn').click(function() {
    $.ajax({
           type:"POST",
           url:"MyServlet"
       })
       .done(function (data) {
    alert(data);//data object represents the response
       });
   });
});
</script>
</head>
<body>
<input type="button" value="Call Servlet" id="btn"/>
</body>
</html>

7. That is all. Now run the application in tomcat server and click the "Call Servlet" button and you will get an alert saying "Hello from server via POST...!". The POST method has been called.
Now change the parameter 'type:"POST"' to 'type:"GET"'. Now your message will be "Hello from server via GET...!". It means the GET method has been called.

Note - 1 :- By default this ajax call is asynchronous. It means after the ajax call is executed the rest of the code continues executing without waiting for the response from the servlet. If you want to get rid of this asynchronous behavior, just add the parameter  'async:false' as below.

$.ajax({
type:"POST",
url:"MyServlet",
async:false
})

Note - 2 :- JQuery has below two shorthands to call GET and POST requests. If you want you can use them instead of above $.ajax function.

$.get('MyServlet', function(data) {
//alert(data);
});

$.post('MyServlet', function(data) {
//alert(data);
});

Tuesday, September 16, 2014

Placing two DIVs horizontally one after another in same row

In this tutorial I am going to show you how to place two DIVs near each other one after another as in below image.
Note that in this tutorial I am using inline styles so that anyone can understand easily.

If we just add two DIVs in to a HTML page those will be displayed in two rows as below.

<div style="border:solid 2px green;width:200px;height:100px;">
    First DIV
</div>
<div style="border:solid 2px blue;width:200px;height:100px;">
    Second DIV
</div>



Now lets see how we can place the first these DIVs side by side. It is really easy. What you need is to add the style "float:left" to both DIVs.

<div style="border:solid 2px green;width:200px;height:100px;float:left;">
    First DIV
</div>
<div style="border:solid 2px blue;width:200px;height:100px;float:left;">
    Second DIV
</div>



Wow! seems working. Wait...
Now add a third DIV after these two DIVs as below.

<div style="border:solid 2px green;width:200px;height:100px;float:left;">
    First DIV
</div>
<div style="border:solid 2px blue;width:200px;height:100px;float:left;">
    Second DIV
</div>
<div style="border:solid 3px red;width:250px;height:150px;">
    Third DIV
</div>

Output will be as below.

Oops.. something has gone wrong. You can see the third DIVs is overlapped with the first two DIVs. Actually this is the expected behavior with "float:left" style.
Any content you add after a component which is floated, will be overlapped with the floated components.
How can we overcome this issue? Just add another DIV after the first two DIVs and set the style of that DIV to "clear:both".
Any content you put after this DIV will not be overlapped.

<div style="border: solid 2px green; width: 200px; height: 100px; float: left;">
    First DIV</div>
<div style="border: solid 2px blue; width: 200px; height: 100px; float: left;">
    Second DIV</div>
<div style="clear: both;" />
<div style="border: solid 3px red; width: 250px; height: 150px;">
    Third DIV
</div>

Now you get the desired output.



Monday, September 15, 2014

JUnit Hello World example with Eclipse

This kick start guide will show you how to create and execute JUnit test cases with eclipse.

First create a new project in Eclipse. Then create a new class. I name the class as HelloWorld.java and create it inside the package com.example. I modify the HelloWorld class so that it looks like below.

package com.example;
public class HelloWorld {
  private String helloMessage;

  public HelloWorld(String message) {
    this.helloMessage = message;
  }

  public String sayHello() {
    return helloMessage;
  }
}

Right. Now what we need to do is create a JUnit test case to verify the functionality of this class.
Create another package in src folder and name it as com.tests(You may use any name).
Now right click on the newly created package and point to New ⇨ JUnit Test Case.

Set the name as HelloWorldTest. In "Class under test" text box browse and select the class HelloWorld which we created before. Click Next. Select the sayHello() method as below and click Finish. Note that test methods are generated only for the methods that you select here. If you want you can also select the HelloWord() also.



Now the generated test class will look like this.
package com.tests;

import static org.junit.Assert.*;
import org.junit.Test;

public class HelloWorldTest {
  @Test
  public void testSayHello() {
    fail("Not yet implemented");
  }
}

Now we can modify above auto generated method to add out  testing logics. I modify my HelloWorldTest class as below.

package com.tests;

import static org.junit.Assert.*;
import org.junit.Test;
import com.example.HelloWorld;

public class HelloWorldTest {
  String helloMessage = "Hello JUnit World!"; 
  HelloWorld hello = new HelloWorld(helloMessage);

  @Test
  public void testPrintMessage() {
     assertEquals(helloMessage, hello.sayHello());
  }
}

Ok, I have completed my test class now. Please take a look at testPrintMessage() method. What it does is, compares the String returned by the hello.sayHello() method with the String we set in constructor. As we know those should be the same. If those were different it means something has gone wrong.
assertEquals() method throws an error if the results were not the same.

Now right click the HelloWorldTest class and select Run As ⇨ JUnit Test. You will see that a tab like below will be opened and show the result of the test.



If we had multiple methods in our HelloWorldTest class there would be more lines in this report.If any of the methods failed those will be marked in red.
We can fail the test by modifying our class as below.

package com.tests;

import static org.junit.Assert.*;
import org.junit.Test;
import com.example.HelloWorld;

public class HelloWorldTest {
  String helloMessage = "Hello JUnit World!"; 
  HelloWorld hello = new HelloWorld(helloMessage + "abc");

  @Test
  public void testPrintMessage() {
     assertEquals(helloMessage, hello.sayHello());
  }
}

Now run the test again and the output will look like this.



The JUnit API class org.junit.Assert consists with lot more other important methods such as
     ● assertNotEquals();
     ● assertTrue();
     ● assertFalse();
     ● assertThat();

You can find the complete list in API documentation.
http://junit.sourceforge.net/javadoc/org/junit/Assert.html

Monday, September 8, 2014

Word Wrapping inside a table cell

You may have faced situations where you need to place long texts inside a small HTML table cell. You may need to keep the width of the cell fixed and wrap the text so that it breaks at the border of the cell. Everything will work fine as long as all the words in the text are shorter than the cell width. But what happens if you have longer words. Yes the cell will get expanded to display the word in a single line.
How to avoid this behavior and let the word break and span in two or multiple lines. You will first try something like this.

<table border="1" width="40%">
  <tr>
    <td style="width:50px;word-wrap: break-word">Is this extraodinary??????????</td>
    <td> </td>
  </tr>
  <tr>
    <td> </td>
    <td> </td>
  </tr>
</table>

 But this does not work. The whole part "extraodinary??????????" will display in the same line.


How to overcome this behavior? Simple, just make the layout of the table fixed by adding the style "table-layout:fixed" to the table.

<table border="1" width="40%" style="table-layout:fixed;">
  <tr>
    <td style="width:50px;word-wrap: break-word">Is this extraodinary??????????</td>
    <td> </td>
  </tr>
  <tr>
    <td> </td>
    <td> </td>
  </tr>
</table>

Wow... Now it works. Now the output will look like this.


Note:- To be this worked in most browsers you may need to assign a width to the table.