Follow

Welcome to TechYari!

Tutorials on webdesign, web development and more...

Introduction

In this tutorial I am going to show you how to create an awesome Live Weather App using jQuery, jQuery UI autocomplete, Open Weather Map API and BigVideo.js.

OpenWeatherMap has a free API which provides weather details for almost every city around the world. I don't say that it's accurate but it's quite good to achieve what we need.

This application is compatible only with modern desktop browsers (built with Google Chrome not tested on others) as we are going to have an html5 video background and currently mobile devices do not support auto play for videos. There is a solution for this but we will park it for now.

live-weather-app-in-j2ee-using-jquery-json

weather-app-evening-background

weather-app-night-background

Requirements:

Open Weather Map API 

OpenWeatherMap provides a free api which can be called from below url (I have not used appid here, but it works without that as well):

URL : http://api.openweathermap.org/data/2.5/find?q=cityname&mode=json

here we are passing two parameters, city name & the response format we need from the server i.e. json in our case. You can use xml as well.
Below is a sample result for query using Mumbai as a city name :

{"message":"accurate","cod":"200","count":1,"list":[{"id":1275339,"name":"Mumbai","coord":{"lon":72.847939,"lat":19.01441},"main":{"temp":302.47,"temp_min":302.47,"temp_max":302.47,"pressure":1018.69,"sea_level":1019.47,"grnd_level":1018.69,"humidity":86},"dt":1398078846,"wind":{"speed":4.01,"deg":301.501},"sys":{"country":"IN"},"clouds":{"all":0},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01d"}]}]}


Step 1 : Creating the Layout 

To create our layout we will us html5 based bootstrap template from http://www.initializr.com/ . Place all the videos, js and css files in required folders according to the index.html file code below, you can also download the source and see the structure of files and folders.


<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/bootstrap-theme.min.css">
        <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
        <link rel="stylesheet" href="css/main.css">

        <script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script>
    </head>
    <body>
        <!--[if lt IE 7]>
            <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->
        

        <div class="result">
                <div class="search">
                <input class="city_names" id="city_names" name="city_names" placeholder="Enter city name here"/>
                <input type = "button" name="submit" value="Search" id="submit" class="submit"/>
                </div>
                <div class="main">
                    <span class="city"></span>
                    <span class="country"></span>
                    <div class="temp"></div>
                    <div class="message"></div>
                </div>
          </div>

      
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.0.min.js"><\/script>')</script>
        <script src="js/vendor/jquery-ui.min.js"></script>

        <script src="js/vendor/bootstrap.min.js"></script>
        <script src="js/vendor/imagesloaded.pkgd.min.js"></script>
        <script src="js/vendor/video.js"></script>
        <script src="js/vendor/bigvideo.js"></script>
        <script src="js/main.js"></script>

    
    </body>
</html>


Step 2 : Styling the page with css

So we have our layout ready with an input tag to get the city name and few empty html elements to render the data provided by api call. All of this is going to be done dynamically using jquery. But before moving to that lets style our page a bit, below is the code for main.css


.result{
  position:fixed;
  z-index: 100;  
  top:50%;  
  left:50%;  
  margin:-100px 0 0 -100px;  
  width:360px;  
  height:460px; 
}
.submit{color:black;}
.search{text-align: center;}
.main{text-align: center;color: white; }
.city{font-family: fantasy;
font-size: 76px;}
.country{font-family: fantasy;}
.temp, .t{font-weight: 700;
font-size: 72px;}
.temp-high{font-weight: bold;}
.temp-low{font-weight: bold;}


Step 3 : Configure the autocomplete for city names

You might have noticed that we have an input field on index page but it does not have any form, as we are going to use jQuery to submit the data to the sever on click event of submit button. Before doing that we need to configure one more thing i.e. "Autocomplete". We would like to show our users all the available cities as a dropdown list when they type on input. We will also show them the country code with the city to make it more convenient for them. to achieve this we will use the same api from openweathermap and just return the matching city names as label from the success of ajax call. below is the code for autocomplete..


$(document).ready(function(){
 $( ".city_names" ).autocomplete({
  source: function( request, response ) {
   $.ajax({
    url: "http://api.openweathermap.org/data/2.5/find",
    dataType: "jsonp",
    data: {
     q: request.term,
     mode: "json"
    },
    success: function( data ) {
     // Fix for IE 8 as forEach function not supported yet below IE 9
     if (typeof Array.prototype.forEach != 'function') {
         Array.prototype.forEach = function(callback){
           for (var i = 0; i < this.length; i++){
             callback.apply(this, [this[i], i, this]);
           }
         };
     }

     var parsed = data.list;
     var newArray = new Array(parsed.length);
     var i = 0;
       parsed.forEach(function (entry) {
                     var newObject = {
                         label: entry.name+" "+entry.sys.country
                     };
                     newArray[i] = newObject;
                     i++;
                 });

       response(newArray);
    },
    error: function (message) {
                 response([]);
             }
   });
  },
  minLength: 2,
  open: function() {
   $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
  },
  close: function() {
   $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
  }
 });
 
});


Step 4 : Geting the weather data from OpenWeatherMap API

To get weather data via api call we need to pass either city name, latitude,longitude or city id. This is not a practical scenario and just a demo so to keep things simpler our we will pass city name (This can have issues in terms of usability when their are multiple cities with the same name for a given country). 

OpenWeatherMap API provides all type of data for a location, we are only interested in current temperature in celcius format. Below is the code for submit button click event


$('.submit').click(function(){
 
 var city = $('.city_names').val();
 //console.log(city);
 $.ajax({
     url: "http://api.openweathermap.org/data/2.5/find",
  
     // name of the callback parameter
     jsonp: "callback",
  
     // tell jQuery we're expecting JSONP
     dataType: "jsonp",
  
     //what we want
     data: {
         q: city,
         units:"metric",
         mode: "json"
     },
  
     // work with the response
     success: function( response ) { 
        
      
             var temp = response.list[0].main.temp;
             
             if(temp<25 ){
              $('.message').html("it's feels cold, get a jacket");
             }else if(temp<35){
              $('.message').html("it's feels normal"); 
             }else if(temp<50){
              $('.message').html("it's feels hot, switch on your AC");
             }

        $('.city').html(response.list[0].name);
        $('.country').html('( </span><span>'+response.list[0].sys.country+'</span><span> )');
        $('.temp').html('<span>'+response.list[0].main.temp+'</span><span class="t">* C</span>');
       
         
     }
 });
});



 Step 5 : Adding the video background based on time of user's machine.  

We have used BigVideo.js to show video background, We have three videos, one for morning to afternoon, one for evening, and one for night. We will show them based on user's machine time (time on his laptop/deskto/device). Below is the code...


  var date = new Date();
    var hour = date.getHours();
             var min = date.getMinutes();

             //console.log("hour: "+hour+" minute: "+min);

             if(hour<5){
                   $(function() {
          var BV = new $.BigVideo();
          BV.init();
          BV.show(['night.mp4'],{ambient:true});
                   });
               }else if(hour<16){
                 $(function() {
          var BV = new $.BigVideo();
          BV.init();
          BV.show(['daylight.mp4'],{ambient:true});
                   });
               }else if(hour<19){
                 $(function() {
          var BV = new $.BigVideo();
          BV.init();
          BV.show(['evening.mp4'],{ambient:true});
                   });
               }else{
                    $(function() {
          var BV = new $.BigVideo();
          BV.init();
          BV.show(['night.mp4'],{ambient:true});
                   });
 }

Step 6 : combining all the three parts into a single javascript file


var date = new Date();
    var hour = date.getHours();
             var min = date.getMinutes();

             //console.log("hour: "+hour+" minute: "+min);

             if(hour<5){
                   $(function() {
          var BV = new $.BigVideo();
          BV.init();
          BV.show(['night.mp4'],{ambient:true});
                   });
               }else if(hour<16){
                 $(function() {
          var BV = new $.BigVideo();
          BV.init();
          BV.show(['daylight.mp4'],{ambient:true});
                   });
               }else if(hour<19){
                 $(function() {
          var BV = new $.BigVideo();
          BV.init();
          BV.show(['evening.mp4'],{ambient:true});
                   });
               }else{
                    $(function() {
          var BV = new $.BigVideo();
          BV.init();
          BV.show(['night.mp4'],{ambient:true});
                   });
 }

$('.submit').click(function(){
 
 var city = $('.city_names').val();
 //console.log(city);
 $.ajax({
     url: "http://api.openweathermap.org/data/2.5/find",
  
     // name of the callback parameter
     jsonp: "callback",
  
     // tell jQuery we're expecting JSONP
     dataType: "jsonp",
  
     //what we want
     data: {
         q: city,
         units:"metric",
         mode: "json"
     },
  
     // work with the response
     success: function( response ) { 
        
      
             var temp = response.list[0].main.temp;
             
             if(temp<25 ){
              $('.message').html("it's feels cold, get a jacket");
             }else if(temp<35){
              $('.message').html("it's feels normal"); 
             }else if(temp<50){
              $('.message').html("it's feels hot, switch on your AC");
             }

        $('.city').html(response.list[0].name);
        $('.country').html('( </span><span>'+response.list[0].sys.country+'</span><span> )');
        $('.temp').html('<span>'+response.list[0].main.temp+'</span><span class="t">* C</span>');
       
         
     }
 });
});

$(document).ready(function(){
 $( ".city_names" ).autocomplete({
  source: function( request, response ) {
   $.ajax({
    url: "http://api.openweathermap.org/data/2.5/find",
    dataType: "jsonp",
    data: {
     q: request.term,
     mode: "json"
    },
    success: function( data ) {
     // Fix for IE 8 as forEach function not supported yet below IE 9
     if (typeof Array.prototype.forEach != 'function') {
         Array.prototype.forEach = function(callback){
           for (var i = 0; i < this.length; i++){
             callback.apply(this, [this[i], i, this]);
           }
         };
     }

     var parsed = data.list;
     var newArray = new Array(parsed.length);
     var i = 0;
       parsed.forEach(function (entry) {
                     var newObject = {
                         label: entry.name+" "+entry.sys.country
                     };
                     newArray[i] = newObject;
                     i++;
                 });

       response(newArray);
    },
    error: function (message) {
                 response([]);
             }
   });
  },
  minLength: 2,
  open: function() {
   $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
  },
  close: function() {
   $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
  }
 });
 
});


That's all, you might get  5 second glitch on video background, which can be tweaked but I will leave it for now, we have successfully created a weather app using only html,css and jQuery. If you want to support mobile devices, you can include a check for mobile devices using main.js javascript file and replace video with a static background using css.

Share this tutorial if you find it useful and do comment if any questions/suggestions.

Download Source 



Introduction 

In this tutorial we are going to look at a typical login and registration example using the ever popular jquery ui tabs in place with J2EE. We will be using MVC model for the tutorial, this is not based on any MVC framework so we will create our own forced MVC model using different packages, servlets and class files. MySql database will serve as a back end for registering and authenticating users.

jquery-tabs-login-registration-demo

You can download the source code using the link below as a war file and import it directly to Eclipse. You will only need the database and a table ready to use which can be built using the script provided below.

Download Source

Project Setup

I will be using Elcipse for J2EE with MySql database and Apache Tomcat 7. This example will require one additional jar called mysql-connector for jdbc. Below is a screenshot of completed project on Eclipse.

project-structure

Creating the Users table

We need a table to store users for our site. We will be creating a table called users with 6 fields. Refer below query to create the table.


   CREATE TABLE users(
    id INT AUTO_INCREMENT,
    fullname VARCHAR (50),
    email VARCHAR (50),
    password VARCHAR (50),
    gender VARCHAR (50),
    birthdate VARCHAR (50),
    PRIMARY KEY ( id )
    ) 

We do not need any data to be populated as we will user registration page for the same.


Creating the login and registration form using jQuery UI tabs

We will require a JSP instead of plain html as we need to show few errors based on username/password authentication. This page will be created in WebContent folder and our web.xml file will use this as welcome page for website. I have not used any front end and back end validation as it will make the tutorial very large.  
If you require one you can use JavaScript/jQuery validation plugin and regular Expressions on the Java Classes to do the validations.
Just copy and paste this code in a file named index.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login and registartion example in J2EE</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="style.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
$(function() {
  $( "#tabs" ).tabs();
});
</script>
</head>
<body>
 <div class="wrapper">
 <div class="header">
  <h1>Tabbed Login and Registration example with jQuery UI in J2EE using MySql database</h1>
 </div>
 
 <div class="container">
  <div class="instruction">
<div id="tabs">
  <ul>
    <li><a href="#login">Login</a></li>
    <li><a href="#register">Register</a></li>
  </ul>
  <div id="login">
   <% 
   if("Invalid username or password".equalsIgnoreCase((String)session.getAttribute("error"))){ %>
    <h6> Invalid user name or password. Please try again.</h6>
   <%} %>
    <form method="post" action="LoginController">
     <label for="email">Email:</label>
     <input type="text" name="email" id="email" class="email" placeholder="Your email address"/>
     <label for="password">Password:</label>
     <input type="password" name="password" id="password" class="password" placeholder="Your password"/>
     <input type="submit" value="Login">
    </form>
  </div>
  <div id="register">
   <form method="post" action="RegistrationController">
    <label for="fullname">Full Name:</label><br/>
     <input type="text" name="fullname" id="fullname" class="fullname" placeholder="Your full name"/>
     <br/>
     <label for="email">Email:</label><br/>
     <input type="text" name="email" id="email" class="email" placeholder="Your email address"/>
     <br/>
     <label for="password">Password:</label><br/>
     <input type="password" name="password" id="password" class="password" placeholder="Your password"/>
     <br/>
     <label for="gender">Gender:</label><br/>
     <select name="gender" id="gender" class="gender">
      <option value="Male">Male</option>
      <option value="Male">Female</option>
     </select>
     <br/>
     <label for="birthdate">Birth Date:</label><br/>
     <input type="text" name="birthdate" id="birthdate" class="birthdate" placeholder="Your birth date"/>
     <br/>
     <input type="submit" value="Register">
   </form>
  </div>
</div>
  </div>
 </div>
 
 <div class="footer">
  &copy; 2014 <a href="http://techyari.in">TechYari</a> All rights reserved. 
 </div>
 </div>
</body>
</html>

Styling the Login & Registration page

Create a file called style.css and add following styles to it.


body{
 background-color: #e6e6e6;
 font-family: Helvetica;
 font-size: 17px;
 color: #666;
 margin: 0px;
 padding: 0px;
}
.wrapper{ 
  width:1024px;
     margin: 0 auto;
     background:white;
     }
     
.header{padding:10px;background-color:#4D82CA;color:white}     

h1{
 text-align:center;
 font-size:20px;
 margin:0px;
}

.container{
 min-height:400px;
 border-top: 1px solid gray;
 padding: 50px;
 }
.center{margin-left:43%}

.footer{ text-align:center;border-top: 1px solid gray;padding:10px;background-color:#4D82CA;color:white }

.footer a {color:lavender;text-decoration:none;}


Creating the Packages, Servlets and Java Classes

As we intend to organize this example as an MVC application we will create three packages insider our src folder
  1. in.techyari.example.dao
  2. in.techyari.example.controller
  3. in.techyari.example.model
  • dao package will contain classes related to Database Connection and Data Access Objects for our Model Class.
  • controller package will contain the servlets for Login and Registration form
  • Model will contain our User model class having 6 attributes.
Create a class named Database inside in.techyari.example.dao use below code for reference, modify the database name, username and password according to your database. 

package in.techyari.example.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Database {
 
 
 public Connection getConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{
  
  Connection connection =  null;
  
  // Store the database URL in a string
  String url = "jdbc:mysql://localhost:3306/tutorials"; 
  
  Class.forName("com.mysql.jdbc.Driver").newInstance();
  
  // set the url, username and password for the databse 
  connection = DriverManager.getConnection(url,"root","");   
  return connection;
  
 }
}

Now we will create our Model class User which will go inside in.techyari.example.model, here we are going to provide two constructors, first the default one and second with 5 arguments to create a User object when someone registers on our site. We will also override toString method so that we can print some useful info for our class in console during development and debugging.


package in.techyari.example.model;

public class User {
 
 private int id;
 private String fullname;
 private String email;
 private String password;
 private String gender;
 private String birthdate;
 
 public User(){
  
 }
 
 public User(String fullname, String email, String password,String gender, String birthdate) {
  this.fullname = fullname;
  this.email = email;
  this.password = password;
  this.gender = gender;
  this.birthdate = birthdate;
 }
 
 
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getFullname() {
  return fullname;
 }
 public void setFullname(String fullname) {
  this.fullname = fullname;
 }
 public String getEmail() {
  return email;
 }
 public void setEmail(String email) {
  this.email = email;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public String getGender() {
  return gender;
 }
 public void setGender(String gender) {
  this.gender = gender;
 }
 public String getBirthdate() {
  return birthdate;
 }
 public void setBirthdate(String birthdate) {
  this.birthdate = birthdate;
 }

 @Override
 public String toString() {
  return "User [id=" + id + ", fullname=" + fullname + ", email=" + email
    + ", gender=" + gender + ", birthdate=" + birthdate + "]";
 }
 
 
 
}

Creating the UserDAO class to insert and validate users. We will first create a UserDAO interface and then we will implement this interface in UserDAOImpl class. both will reside in in.techyari.example.dao package.

Below is the code for UserDAO Interface



package in.techyari.example.dao;

import in.techyari.example.model.User;

public interface UserDAO {
 
 public User getUserByEmail(String email,String password);
 public int createOrUpdateUser(User u);
 
}

Now the UserDAOImpl class which will provide the actual implementation for methods in UserDAO

package in.techyari.example.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import in.techyari.example.model.User;

public class UserDAOImpl implements UserDAO{
 
 Database db = new Database();
 

 @Override
 public User getUserByEmail(String email, String password) {
  User user = new User();
  try {
   Connection connection = db.getConnection();
   PreparedStatement ps = connection.prepareStatement("SELECT * FROM users WHERE email LIKE ? AND password LIKE ?");
   ps.setString(1, email);
   ps.setString(2, password);
   ResultSet rs = ps.executeQuery();
   while(rs.next()){
    user.setId(rs.getInt("id"));
    user.setFullname(rs.getString("fullname"));
    user.setEmail(rs.getString("email"));
    user.setGender(rs.getString("gender"));
    user.setBirthdate(rs.getString("birthdate"));
   }
   
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } 
  return user;
 }

 @Override
 public int createOrUpdateUser(User u) {
  int result = 0;
  try {
   Connection connection = db.getConnection();
   PreparedStatement ps = connection.prepareStatement("INSERT INTO users (fullname,email,password,gender,birthdate) VALUES (?,?,?,?,?)");
   ps.setString(1, u.getFullname());
   ps.setString(2, u.getEmail());
   ps.setString(3, u.getPassword());
   ps.setString(4, u.getGender());
   ps.setString(5, u.getBirthdate());
   result = ps.executeUpdate();
   
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return result; 
  
 }

}

So by far we have created our model and database access objects with a database class to provide the jdbc connectivity between our java and mysql. Now we will create our controllers, we have two major actions in this application :

  • Login
  • Registration
Creating the Registration Controller : create a servlet named RegistrationController and place inside in.techyari.example.controller package. This servlet uses annotations to provide us servlet configuration for the path RegistrationController which is being used as action by "registration form" in index.jsp page. So upon hitting the submit button you will call this controller which will further take care of registering the user on our database.


package in.techyari.example.controller;

import in.techyari.example.dao.UserDAOImpl;
import in.techyari.example.model.User;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class RegistrationController
 */
@WebServlet("/RegistrationController")
public class RegistrationController extends HttpServlet {
 private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegistrationController() {
        super();
        // TODO Auto-generated constructor stub
    }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  
  String fullname = request.getParameter("fullname");
  String email = request.getParameter("email");
  String password= request.getParameter("password");
  String gender = request.getParameter("gender");
  String birthdate = request.getParameter("birthdate");
  
  User user = new User(fullname,email,password,gender,birthdate);
  
  UserDAOImpl userDAOImpl = new UserDAOImpl();
  
  int result = userDAOImpl.createOrUpdateUser(user);
  
  if(result == 0){
   
   System.out.println("User could not be registered");
  }else{
   
   System.out.println(user.getFullname()+" You have been registered successfully");
   response.sendRedirect("success.html");
  }
  
 }

}

You might have noticed that registration controller redirects to a success page when a user is successfully registered. Below is the code for success.html (I am using html page here as I don't need to perform any logical/dynamic operations)


<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login and registartion example in J2EE</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="style.css">

</head>
<body>
 <div class="wrapper">
 <div class="header">
  <h1>Tabbed Login and Registration example with jQuery validation in J2EE using MySql database</h1>
 </div>
 
 <div class="container">
  <div class="instruction">
   <h3> You have been successfully registered.<a href="index.jsp">Click here to back to login page</a></h3>
  </div>
 </div>
 
 <div class="footer">
  &copy; 2014 <a href="http://techyari.in">TechYari</a> All rights reserved. 
 </div>
 </div>
</body>
</html>

Ok so we now have registration in place, time to login, use the same convention and create a servlet named LoginController in same package. Below is the code for LoginController


package in.techyari.example.controller;

import in.techyari.example.dao.UserDAOImpl;
import in.techyari.example.model.User;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class LoginController
 */
@WebServlet("/LoginController")
public class LoginController extends HttpServlet {
 private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginController() {
        super();
        // TODO Auto-generated constructor stub
    }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
 
  String error;
  String email = request.getParameter("email");
  String password= request.getParameter("password");
  HttpSession session = request.getSession();
  UserDAOImpl userDAOImpl = new UserDAOImpl();
    
  User user = userDAOImpl.getUserByEmail(email,password);
  
  
  if(user.getFullname() == null){
   error = "Invalid username or password";
   System.out.println("Could not log you in please check your email & password");
   session.setAttribute("error", error);
   response.sendRedirect("index.jsp");
  }else{
   session.setAttribute("user",user);
   System.out.println(session.getAttribute("user"));
   error = "none";
   response.sendRedirect("welcome.jsp");
  }
 }

 @Override
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  // TODO Auto-generated method stub
  if("logout".equalsIgnoreCase(request.getParameter("query"))){
   
      HttpSession session = request.getSession();
      session.removeAttribute("user");
      session.invalidate();
      response.sendRedirect("index.jsp");
   }
 }

}

We have everything in place now, we just need the user to redirect to welcome.jsp page based on conditions calculated by LoginController. So create a welcome.jsp page in WebContent folder and you are done. Refer below for the code.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"
  import = "in.techyari.example.model.User"   
    
 %>
<!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">
<title>Login and registartion example in J2EE</title>
</head>
<body>
 <%
   User user = (User)session.getAttribute("user");
   if(user!=null){ %>
  
      <h3>Welcome <% out.print(user.getFullname()); %></h3>
      <a href="LoginController?query=logout">Logout</a>
      
      <% }else{ %> 
       <h3>Your don't have permission to access this page</h3>
      <% } %>
 
 
</body>
</html>

Download Source

Now deploy this app to Tomcat and you have a web app ready with registration and login all placed at work. The idea behind this tutorial was to give exposure to MVC design pattern and using it with real world. This is not a perfect piece of code as it does not use encryption for password, client side & server side validation and few other required pieces like form auto fill on registration error. I will be creating a separate tutorial for them as they themselves are huge topics and placing them here would make this tutorial very lenthy.

Kindly share this tutorial if you find it useful. Share your concerns/queries using the comment box below.

In this tutorial I am going to integrate jQuery autocomplete plugin into J2EE application having MySql database. Our input field will receive a JSON response via ajax call to the servlet, which will be displayed as a drop down list when a user types, we will achieve this using jQuery autocomplete plugin. 


Final Application


jquery-autocomplete-demo

Requirements

  • MySql Database ( I use WAMP server as it comes bundled with PhpMyAdmin for MySQL database)
  • Eclipse IDE for J2EE ( it's my preference)
  • JDK 1.7
  • Apache Tomcat 7 (As we will be using annotation based configuration for our servlets)
  • gson 2.2.1 library for JSON conversion
  • mysql connector jar for jdbc connection

Project Structure

Below is a how your project should look after completion. To begin open your Eclipse IDE and create a new Dynamic Web Project ( don't forget to use web module version 3 to support annotations ). 

jquery-autocomplete-project-structure

Database and table setup

In order to move forward launch your favorite tool and create a dummy database with a single table called user with two columns (id,name) and populate the table with some dummy data. 

Creating the home page with autocomplete 

Our home page will feature a text box which is going to be populated by values retrieved from database using autocomplete plugin.This file requires 4 external files to work as expected ( jquery, jquery ui, jquery ui css, style.css and search.js )


<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>jQuery Autocomplete example with J2EE and MySql database</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="style.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script src="search.js"></script>
</head>
<body>
 <div class="wrapper">
 <div class="header">
  <h1>jQuery Autocomplete example with J2EE, JSON and MySql database</h1>
 </div>
 
 <div class="container">
  <div class="instruction">
   <h5>Search for Ajay, Eva or type any character between a to i.</h5>
   <div class="search-container">
    <div class="ui-widget">
     <input type="text" id="search" name="search" class="search" placeholder="search here"/>
    </div>   
   </div>
  </div>
 </div>
 
 <div class="footer">
  &copy; 2014 <a href="http://techyari.in">TechYari</a> All rights reserved. 
 </div>
 </div>
</body>
</html>





Styling the page with css

In order to style our home page we will use css, copy and paste the code given below :

<style type="text/css">
body{
 background-color: #e6e6e6;
 font-family: Helvetica;
 font-size: 17px;
 color: #666;
 margin: 0px;
 padding: 0px;
}
.wrapper{ 
  width:1024px;
     margin: 0 auto;
     background:white;
     }
     
.header{padding:10px;background-color:#4D82CA;color:white}     

h1{
 text-align:center;
 font-size:20px;
 margin:0px;
}

.container{
 min-height:400px;
 border-top: 1px solid gray;
 padding: 50px;
 }
.center{margin-left:43%}

.footer{ text-align:center;border-top: 1px solid gray;padding:10px;background-color:#4D82CA;color:white }

.footer a {color:lavender;text-decoration:none;}
</style>


Getting user data from database using ajax and applying autocomplete

Search.js is being used here to create ajax request to the server/servlet/controller and apply the response to the input box using jQuery autocomplete plugin.


<script type="text/javascript">
  $(function() {
    $( "#search" ).autocomplete({
     source: function (request, response) {
            $.ajax({
                url: "SearchController",
                dataType: 'json',
                data: request,
                success: function (data) {
                 if (typeof Array.prototype.forEach != 'function') {
         Array.prototype.forEach = function(callback){
           for (var i = 0; i < this.length; i++){
             callback.apply(this, [this[i], i, this]);
           }
         };
     }

     var values = data;
     var newArray = new Array(values.length);
     var i = 0;
      values.forEach(function (entry) {
                     var newObject = {
                         label: entry.name
                     };
                     newArray[i] = newObject;
                     i++;
                 });

       response(newArray);
                }   
            }); 
        },  
        minLength: 1
    });
  });
</script>


Creating the controller to handle ajax calls

When a user types a character in text box ,jQuery will fire an ajax request using autocomplete plugin to the controller,  our controller will call the user data access object which in turn creates the necessary connection and returns the user data back as an array list to the controller. After getting the data we convert it to json format and return it back to the success function of our ajax call. Create an servlet named SearcController, use below code for reference.  


package in.techyari.tutorial.controller;

import in.techyari.tutorial.dao.UserDAO;
import in.techyari.tutorial.model.User;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

/**
 * Servlet implementation class SearchController
 */
@WebServlet("/SearchController")
public class SearchController extends HttpServlet {
 private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public SearchController() {
  
    }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
  String text = request.getParameter("term");
  System.out.println("Hello from Get Method: " +text);
  UserDAO userDAO = new UserDAO();
  try {
   ArrayList<User> users  = userDAO.getUsers(text);
   for(User user: users){
    System.out.println(user.getName());
   }
   
   String searchResult = new Gson().toJson(users);
   
   PrintWriter writer = response.getWriter();
   writer.write(searchResult);
  
  }catch(Exception e){
   e.printStackTrace();
  }
  
 }

 

}


Connecting to database using JDBC

We want to connect to MySql database using jdbc. Create a file called Database.java and replace the url, username and password values with corresponding values of your database.


package in.techyari.tutorial.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Database {
 
 public Connection getConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{
  
  Connection connection =  null;
  
  // Store the database URL in a string
  String url = "jdbc:mysql://localhost:3306/searchtutorial"; 
  
  Class.forName("com.mysql.jdbc.Driver").newInstance();
  
  // set the url, username and password for the databse 
  connection = DriverManager.getConnection(url,"root","");   
  return connection;
  
 }
}



Craeting User model class

We are following a forced MVC pattern in this tutorial so we need a model for our user class. Use below code and create a class named User.java


package in.techyari.tutorial.model;

public class User {
 
 private String id;
 private String name;
 
 
 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
 
}


Creating methods to get User data from database

Finally we need a data access object class called UserDAO.java which will interact with mysql database and return the data for autocomplete query made by ajax request. We have used sql like query here to fetch all the matching records for input characters.


package in.techyari.tutorial.dao;

import in.techyari.tutorial.model.User;
import in.techyari.tutorial.dao.Database;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.sql.PreparedStatement;


public class UserDAO {
 
 public ArrayList getUsers(String s) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{
  
  ArrayList userList = new ArrayList();
  Database db = new Database();
  Connection connection = db.getConnection();
  
  try{
   PreparedStatement ps = connection.prepareStatement("SELECT * FROM user WHERE name like ?");
   ps.setString(1, "%" +s+"%");
   ResultSet rs = ps.executeQuery();
   
   while(rs.next()){
    User user = new User();
    user.setId(rs.getString("id"));
    user.setName(rs.getString("name"));
    userList.add(user);
   }
  }catch(Exception e){
   e.printStackTrace();
  }
  return userList;
 }
}

<.pre>

This is it. We have successfully integrated jQuery autocomplete with J2EE application.

You can download the EAR file which contains the source code from the download link give below:

 Download Source

Like and share this tutorial if you find it useful, kindly use the comment box if you have any queries or suggestions.

Introduction

WordPress plugins are the easiest way to add functionality to your blog. Below is a list of few wonderful plugins that can make your site come to life.


BackUpWordPress

As it’s name suggests it keeps backup of your site database and code automatically. Yo can set your preferred duration, email address to get notified on each backup, and also download limits for each backup. By default it saves last 10 backups on the server. It can be very handy when it comes to automated backups.

Limit Login Attempts

Site Security is one of the most critical factors once you site gets popular. This wordpress plugin helps in limiting login attempts by way of cookies and IP adress blocking. It can make your site more secure and foolproof by making bruteforce attacks more difficult.

Akismet

 Akismet is the most popular spam filter when it comes to wordpress. It can take care of all the spam while you prepare your next post. It uses a web service to filter spam on your website so you don’t have to worry filtering comments and trackbacks anymore.


WP to Twitter

Twitter is one of the most popular social networking platform. This plugin helps to automatically tweet each post with tiny url service integration of your choice. You can also edit how prefix and suffix for each post. It makes very easy to let your followers know of every new activity on your website.


Yet Another Related Posts Plugin

When blogs become to heavy it’s very difficult to find a post that you might be interested in. Yet another related post plugin is a simple and unique plugin which checks you database for similar posts, it uses a  unique algorithm to show related posts so that a visitor never misses a post he might be interested in. You can also switch between thumbnails and links when showing the block for related post.


Google XML Sitemaps

Google XML Sitemaps helps to generate special sitemap for your blog. This plugin makes it pretty easier to generate sitemap the way you want and thus helps in better indexing of the website in search engines.


Contact Form

Name

Email *

Message *

Labels

Follow TechYari on

Translate

About TechYari

Tech Yari is a Technical Blog featuring articles on Web Development, Web Design, Search Engine Optimization, Social Media Marketting and Programming.