jQuery UI Tabs (Horizontal and Vertical) Example with Java Web Application Integration

Filed Under: Java EE

jQuery UI is built on top of jQuery JavaScript Library to help web developers in creating awesome web pages with different types of effects. Today we will look into jQuery UI Tabs feature that we can use to create tabs in the view pages easily. We will use this in a simple java web application where user can register and then login. Both registration and login forms will be part of the home page, in two different tabs.

Just to get an idea, below image shows the home page of the web application after integrating all the bits and pieces.

jQuery UI Tabs

Java Web Application Setup

Below image shows the final structure of our web application. Before we proceed with the code, we need to setup our application with required JS and CSS libraries.

jQuery-UI-Tabs-Web-Application-Project

  1. Create a “Dynamic Web Project” in Eclipse, you can choose any name but if you want to use the same name as my project, use jQueryUITabsLoginExample. After project is created, convert it to maven project so that we can add required dependencies.
  2. I am using MySQL DB to store user information, below script can be used to create the Users table.
    
    CREATE TABLE `Users` (
      `email` varchar(30) NOT NULL DEFAULT '',
      `name` varchar(30) NOT NULL DEFAULT '',
      `password` varchar(30) NOT NULL DEFAULT '',
      `address` varchar(50) NOT NULL DEFAULT '',
      PRIMARY KEY (`email`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
  3. Since I am using MySQL database, we need to add MySQL Java driver to the project. Below is our final pom.xml, it’s simple and straight-forward.

    pom.xml

    
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    	<groupId>jQueryUITabsLoginExample</groupId>
    	<artifactId>jQueryUITabsLoginExample</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<packaging>war</packaging>
    
    	<dependencies>
    		<dependency>
    			<groupId>mysql</groupId>
    			<artifactId>mysql-connector-java</artifactId>
    			<version>5.0.5</version>
    		</dependency>
    	</dependencies>
    	
    	<build>
    		<sourceDirectory>src</sourceDirectory>
    		<plugins>
    			<plugin>
    				<artifactId>maven-war-plugin</artifactId>
    				<version>2.3</version>
    				<configuration>
    					<warSourceDirectory>WebContent</warSourceDirectory>
    					<failOnMissingWebXml>false</failOnMissingWebXml>
    				</configuration>
    			</plugin>
    			<plugin>
    				<artifactId>maven-compiler-plugin</artifactId>
    				<version>3.1</version>
    				<configuration>
    					<source>1.7</source>
    					<target>1.7</target>
    				</configuration>
    			</plugin>
    		</plugins>
    		<finalName>${project.artifactId}</finalName>
    	</build>
    </project>
    
  4. Download jQuery JavaScript library from http://jquery.com/download/ and put in the js directory as shown in the project image.
  5. Download jQuery UI library from http://jqueryui.com/download/, you will get a lot of JS and CSS files. You need to include only jquery-ui.js and jquery-ui.css files for the project. jQuery UI provides a lot of themes that we can use as base and then customize it according to our requirements. The layout in the project homepage is the Cupertino theme, you can choose one of the theme from the Download page.

Our project setup is ready now, we can move to our business logic part now.

Model Class

We have User class to map the database table, below is the User model class code.

User.java


package com.journaldev.servlet.model;

public class User {
	
	private String name;
	private String email;
	private String password;
	private String address;
	
	public User(){}
	
	public User(String name, String email, String password, String address){
		this.name=name;
		this.email=email;
		this.password=password;
		this.address=address;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	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 getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}

}

Database Connection Utility Class

We have a simple utility class for database connection, it’s not optimized and just for example purposes.

JDBCUtil.java


package com.journaldev.servlet.jdbc;

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

public class JDBCUtil {
	
private static Connection connection = null;

public static Connection getConnection() {
	if (connection != null)
		return connection;
	else {
		// database URL
		String dbUrl = "jdbc:mysql://localhost/TestDB";
		try 
		{
		Class.forName("com.mysql.jdbc.Driver");
		
		// set the url, username and password for the database
		connection = DriverManager.getConnection(dbUrl, "pankaj", "pankaj123");
		
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connection;
	}
	}
}

DAO Implementation Classes

UseDAO interface defines the contract for the services that will be exposed for operations on Users table.

UserDAO.java


package com.journaldev.servlet.dao;

import com.journaldev.servlet.model.User;

public interface UserDAO {

	public int createUser(User user);
	
	public User loginUser(User user);
	
}

Below is the implementation class, we could have used Hibernate or any other ORM tools for the implementation too.

UserDAOImpl.java


package com.journaldev.servlet.dao;

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

import com.journaldev.servlet.jdbc.JDBCUtil;
import com.journaldev.servlet.model.User;

public class UserDAOImpl implements UserDAO {

	private Connection dbConnection;
	private PreparedStatement pStmt;

	private String SQL_SELECT = "SELECT name, address FROM users WHERE email = ? AND password = ?";
	private String SQL_INSERT = "INSERT INTO users (name,email,password,address) VALUES (?,?,?,?)";

	public UserDAOImpl() {
		dbConnection = JDBCUtil.getConnection();
	}

	public User loginUser(User user) {
		try {
			pStmt = dbConnection.prepareStatement(SQL_SELECT);
			pStmt.setString(1, user.getEmail());
			pStmt.setString(2, user.getPassword());
			ResultSet rs = pStmt.executeQuery();
			while (rs.next()) {
				user.setName(rs.getString("name"));
				user.setAddress(rs.getString("address"));
			}
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
		return user;
	}

	public int createUser(User user) {
		int result = 0;
		try {
			pStmt = dbConnection.prepareStatement(SQL_INSERT);
			pStmt.setString(1, user.getName());
			pStmt.setString(2, user.getEmail());
			pStmt.setString(3, user.getPassword());
			pStmt.setString(4, user.getAddress());
			result = pStmt.executeUpdate();
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
		return result;
	}
}

Servlet Classes and Configuration

We have two servlet controller classes for registration and login process. There are some simple validations present to avoid common errors.

RegistrationController.java


package com.journaldev.servlet.controller;

import java.io.IOException;

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

import com.journaldev.servlet.dao.UserDAO;
import com.journaldev.servlet.dao.UserDAOImpl;
import com.journaldev.servlet.model.User;

public class RegistrationController extends HttpServlet {

	private static final long serialVersionUID = -4006561145676424435L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String name = request.getParameter("name");
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String address = request.getParameter("address");

		if ((name == null || "".equals(name))
				|| (email == null || "".equals(email))
				|| (password == null || "".equals(password))
				|| (address == null || "".equals(address))) {
			String error = "Mandatory Parameters Missing";
			request.getSession().setAttribute("errorReg", error);
			response.sendRedirect("index.jsp#register");
		} else {
			User user = new User(name, email, password, address);

			UserDAO userDAO = new UserDAOImpl();

			int result = userDAO.createUser(user);
			if (result == 1) {
				request.getSession().removeAttribute("errorReg");
				response.sendRedirect("success.jsp");
			}else{
				request.getSession().setAttribute("errorReg", "Internal Server Error, Please try again later.");
				response.sendRedirect("index.jsp#register");
			}
		}
	}
}

LoginController.java


package com.journaldev.servlet.controller;

import java.io.IOException;

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

import com.journaldev.servlet.dao.UserDAO;
import com.journaldev.servlet.dao.UserDAOImpl;
import com.journaldev.servlet.model.User;

public class LoginController extends HttpServlet {

	private static final long serialVersionUID = -4602272917509602701L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String error;
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		
		User user = new User();
		user.setEmail(email); user.setPassword(password);
		
		HttpSession session = request.getSession();
		UserDAO userDAO = new UserDAOImpl();

		User userDB = userDAO.loginUser(user);

		if (userDB.getName() == null) {
			error = "Invalid Email or password";
			session.setAttribute("error", error);
			response.sendRedirect("index.jsp");
		} else {
			session.setAttribute("user", userDB.getName());
			session.removeAttribute("error");
			response.sendRedirect("welcome.jsp");
		}
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if ("logout".equalsIgnoreCase(request.getParameter("param"))) {
			HttpSession session = request.getSession();
			if(session != null){
			session.invalidate();
			}
			response.sendRedirect("index.jsp");
		}
	}
}

It’s time to configure these servlets in web.xml file, below is the final web.xml file.

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>jQueryTabsWebAppExample</display-name>
	
	<servlet>
		<servlet-name>LoginController</servlet-name>
		<servlet-class>com.journaldev.servlet.controller.LoginController
		</servlet-class>
	</servlet>
	<servlet>
		<servlet-name>RegistrationController</servlet-name>
		<servlet-class>com.journaldev.servlet.controller.RegistrationController
		</servlet-class>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>LoginController</servlet-name>
		<url-pattern>/LoginController</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>RegistrationController</servlet-name>
		<url-pattern>/RegistrationController</url-pattern>
	</servlet-mapping>
	
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

Project CSS File

Below is our custom CSS file for view pages.

style.css


body {
	background-color: #e7e7e7;
	font-family: Helvetica;
	font-size: 14px;
	color: #666;
	margin: 0px;
	padding: 0px;
}

.wrapper {
	width: 900px;
	height: 500px;
	margin: 0 auto;
	background: white;
	margin: 0 auto;
}

.container {
	min-height: 400px;
	border-top: 1px solid gray;
	padding: 50px;
}

jQuery UI Tabs View Page

Below is the home page JSP code, where we are using jQuery UI tags.

index.jsp


<!DOCTYPE html>
<html>
<head>
<title>Login and Registration Page</title>
<link rel="stylesheet" href="css/jquery-ui.css">
<link rel="stylesheet" href="css/style.css">

<script src="js/jquery-1.11.1.js"></script>
<script src="js/jquery-ui.js"></script>

<script>
$(function() {
  $( "#tabs" ).tabs();
});
</script>

</head>

<body>
	<div class="wrapper">
		<div class="container">
			<div id="tabs">
				<ul>
					<li><a href="#login">Login</a></li>
					<li><a href="#register">Register</a></li>
				</ul>
				<div id="login">
					<% 
  	if((String)session.getAttribute("error") != null){ %>
					<h4>Invalid Email or Password. Please try again.</h4>
					<%} %>
					<form method="post" action="LoginController">
						<label for="email">Email:</label> <br /> <input type="text"
							name="email" id="email" /> <br /> <label for="password">Password:</label>
						<br /> <input type="password" name="password" id="password" /> <br />
						<br /> <input type="submit" value="Login">
					</form>
				</div>
				<div id="register">
					<% 
  	if((String)session.getAttribute("errorReg") != null){ %>
					<h4><%=session.getAttribute("errorReg") %></h4>
					<%} %>
					<form method="post" action="RegistrationController">
						<label for="name">Name:</label><br /> <input type="text"
							name="name" id="name" /> <br /> <label for="email">Email:</label><br />
						<input type="text" name="email" id="email" /> <br /> <label
							for="password">Password:</label><br /> <input type="password"
							name="password" id="password" /> <br /> <label for="address">Address:</label><br />
						<input type="text" name="address" id="address" /> <br /> <br /> <input
							type="submit" value="Register">
					</form>
				</div>
			</div>
		</div>
	</div>
</body>
</html>

jQuery JS Code for creating tags is:


$(function() {
  $( "#tabs" ).tabs();
});

Above code will convert the tabs div into different tabs. For different tabs, this div should have an unordered list of elements, for us it’s


<ul>
	<li><a href="#login">Login</a></li>
	<li><a href="#register">Register</a></li>
</ul>

Notice that every list item contains anchored URL, they should be the other div elements that will form the view of the tabs. That’s why we have two further divs – login and register. That’s it, other parts of the JSP page are simple HTML and JSP scriptlets. I know that we should not use scriptlets, but again it’s an example and I didn’t wanted to add another technology into it, if you haven’t guessed till now, I am talking about JSTL.

We have couple more simple JSP pages for registration success and login success.

success.jsp


<!DOCTYPE html>
<html>
<head>
<title>Registration Success Page</title>
<link rel="stylesheet" href="css/jquery-ui.css">
<link rel="stylesheet" href="css/style.css">

</head>
<body>
<div class="wrapper">
	<div class="container">
		<h4>
			You have been successfully registered. 
			[ <a href="index.jsp">Back to login page</a> ]
		</h4>
	</div>
</div>
</body>
</html>

welcome.jsp


<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Welcome Page</title>
<link rel="stylesheet" href="js/jquery-ui.css">
<link rel="stylesheet" href="css/style.css">
</head>

<body>
<div class="wrapper">
	<div class="container">
		<%
			String user = (String) session.getAttribute("user");
			if (user != null) {
		%>
		<h3>
			Welcome
			<%
				out.print(user);
			%>
			</h3>
			<a href="LoginController?param=logout">Logout</a>
			<%
				} else {
			%>
			<h3>Your don't have permission to access this page</h3>
			<%
				}
			%>
	</div>
</div>
</body>
</html>

jQuery UI Tabs Project Test

Our web application is ready, just build and deploy the project. Below are some of the images for different pages.

jQuery-UI-Tabs-Login-Error

jQuery-UI-Tabs-Register

jQuery-UI-Tabs-Registration-Error

jQuery UI Vertical Tabs Example

By default, jQuery UI create horizontal tabs. But we can add some extra jQuery code to create vertical tabs too. Below is another form of JSP page with vertical tabs.

index-vertical.jsp


<!DOCTYPE html>
<html>
<head>
<title>Login and Registration Page</title>
<link rel="stylesheet" href="css/jquery-ui.css">
<link rel="stylesheet" href="css/style.css">

<script src="js/jquery-1.11.1.js"></script>
<script src="js/jquery-ui.js"></script>

<script>
$(function() {
  $( "#tabs" ).tabs().addClass( "ui-tabs-vertical ui-helper-clearfix" );
  $( "#tabs li" ).removeClass( "ui-corner-top" ).addClass( "ui-corner-left" );
});
</script>

<!-- Below style for Vertical Tabs -->
<style>
  .ui-tabs-vertical { width: 45em; }
  .ui-tabs-vertical .ui-tabs-nav { padding: .1em .1em .1em .1em; float: left; width: 8em; }
  .ui-tabs-vertical .ui-tabs-nav li { clear: left; width: 100%; border-bottom-width: 1px !important; border-right-width: 0 !important; margin: 0 -1px .2em 0; }
  .ui-tabs-vertical .ui-tabs-nav li a { display:block; }
  .ui-tabs-vertical .ui-tabs-nav li.ui-tabs-active { padding-bottom: 0; padding-right: .1em; border-right-width: 1px; border-right-width: 1px; }
  .ui-tabs-vertical .ui-tabs-panel { padding: 1em; float: right; width: 30em;}
  </style>
  
</head>

<body>
<div class="wrapper">	
<div class="container">
<div id="tabs">
  <ul>
    <li><a href="#login">Login</a></li>
    <li><a href="#register">Register</a></li>
  </ul>
  <div id="login">
  	<% 
  	if((String)session.getAttribute("error") != null){ %>
  		<h4> Invalid Email or Password. Please try again.</h4>
  	<%} %>
    <form method="post" action="LoginController">
    	<label for="email">Email:</label>
    	<br/>
    	<input type="text" name="email" id="email"/>
    	<br/>
    	<label for="password">Password:</label>
    	<br/>
    	<input type="password" name="password" id="password"  />
    	<br/>
    	<br/>
    	<input type="submit" value="Login">
    </form>
  </div>
  <div id="register">
  	<% 
  	if((String)session.getAttribute("errorReg") != null){ %>
  		<h4><%=session.getAttribute("errorReg") %></h4>
  	<%} %>
  	<form method="post" action="RegistrationController">
  		<label for="name">Name:</label><br/>
    	<input type="text" name="name" id="name" />
    	<br/>
    	<label for="email">Email:</label><br/>
    	<input type="text" name="email" id="email" />
    	<br/>
    	<label for="password">Password:</label><br/>
    	<input type="password" name="password" id="password" />
    	<br/>
    	<label for="address">Address:</label><br/>
    	<input type="text" name="address" id="address" />
    	<br/>
    	<br/>
    	<input type="submit" value="Register">
  	</form>
  </div>
</div>
</div>
</div>
</body>
</html>

Below are some of the images for vertical tabs output.

jQuery-UI-Tabs-Vertical

jQuery-UI-Tabs-Vertical-Register

Summary

We have posted a lot of jQuery tutorials here, this example was meant to show how easy it is to integrate jQuery and jQuery UI into a java web application. You can download the final project from below link, don’t miss to share it with other too.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages