Web Services

Today, I came to know about Web Services. I am gonna discuss what I learnt today.

What is a web service?

Web service is a piece if code that runs on the server all the time. I will give an example of MakeMyTrip for the better understanding of concept and it’s usage. MakeMyTrip provides online travel services including flight tickets, domestic, hotel reservations, rail and bus tickets, etc. Let’s talk about flight tickets. This website shows the status of seats availability and prices of airline companies like Air India, Go Air, Jet airways etc. So, the question comes how MakeMyTrip has that information that is stored in different airline companies’ databases. Their is no possibility that MakeMyTrip has access to their databases since it is a privacy concern. So, what happens actually is, all the airline companies create web services and provide the API’s to access those web services by invoking the methods in web service class with suitable parameters.

I hope you got an idea of why there comes a need of web service. Besides this examples, there are so many examples in the world where we can see web services coming into picture; like Trivago that compares prices and features of different hotels in a place.

Behind the scene:

Now, I am gonna tell about how the communication takes place between the client  and server. From my MakeMyTrip example, you can consider MakeMyTrip as a Client and other airline companies’ web application as server or you say service provider. So, how the communication is happening-

  • At server-side, web service is created. This is nothing but a class having business methods that client may invoke.
  • After web service is created, the information about this web service is stored in WSDL(Web Services Description Language) file which is XML based. This file contains information such as methods in web service, their parameters, return type etc.
    XML is universal language that is platform and language independent. XML is used because the communicating web applications may be built in different languages and working on different platforms.
    This WSDL file is generated by WSDL generation tool.
  • Server also provides the endpoint information which is nothing but the URL of web-service denoting it’s location.
  • Now, question comes, how client comes to know about WSDL file. For that, WSDL file is registered in UDDI(Universal Description, Discovery, and Integration) registery where WSDL files are registered with unique names.
  • Now, come to client side. Client now requests UDDI which will provide requested WSDL file.
  • Client then generates Stub/proxies. This is actually generated by Stub generation tool. Stub is just a class having same methods as we had in web-service of server but having different implementation of the methods.
    One more thing, if client application is made in Java, the Stub class is also in Java; meaning in whatever language client web application is made, in the same language Stub class is generated.
  • Now, when client has to invoke any method of web service, it’s gonna create object of Stub by passing the required parameter values.
  • Stub, then stores this information(method, parameter values) in XML document. Now, a SOAP request is generated using this XML file.
  • HTTP protocol now transfers the soap request from client to server.
  • At server, their is another program Skeleton which is predefined class. Skeleton class is made using same language as server web application is made.
    Skeleton reads the SOAP request(XML) which has arrived and passes the parameter values to the actual method in web service.
  • Then, Skeleton prepares the XML document which is nothing but SOAP response containing the response from invoked method.
  • HTTP again transfers the SOAP request from server to client and handed over to Stub.
  • Response is read by Stub and given shown to client.

I mentioned about WSDL generation tool and Stub generation tool. These tools are provided by API’s such as JAX-RPC, JAX-WS, JAX-RS. These API’s are provided by Sun Microsystems if we are creating web application in Java.

I referred this video for the above explanation.

Spring DAO- Spring+Hibernate

Hello viewers ! I have today learnt how to integrate the most popular ORM framework i.e. Hibernate with Spring. I will mention the key points of how the process has to be followed.

  • Adding jar files in project
    Firstly, add all the required jar files which includes Spring core jars, Hibernate jars, Spring persist jars, Type 4 driver, DBCP jar and pool jar.
    If you are creating a simple java project(which I am discussing here), then you need to add these jars, Just do right click the project folder in package explorer -> Build Path -> Configure Build Path -> Add External jars(After that browse for required jar files) -> Apply and Close.
    But, if you are creating a Dynamic web project, then link the jars. Just copy and paste these jar files in Web content -> WEB-INF -> lib directory.
  • Create a Bean class
    Create a bean class for which you want table to be created.
  • Create mapping file
    Now, also create the mapping file(anyname.hbm.xml) where class to table mapping information is present.
  • Create class(Hibernate based DAO) with defined business methods
    It’s time to create a class where all the business methods(createSomething, deleteSomething, updateSomething, retrieveSomething etc.) are defined. Here, we’ll a use life saver 😀 API HibernateTemplate as it saves us from writing tedious code to create Configuration, SessionFactory, Session, Transaction instances and then beginTransaction, closing session..bla bla.
    In this code, we’ll use SessionFactory instance to instantiate HibernateTemplate. SessionFactory instance is injected which we’ll see later.

    package com.mitaly;
    
    import org.hibernate.SessionFactory;
    import org.springframework.orm.hibernate3.HibernateTemplate;
    
    public class TemplateDAO {
    	HibernateTemplate temp;
    
    	public void setSessionFactory(SessionFactory factory) {
    		temp = new HibernateTemplate(factory);
    	}
    	//business methods executed using HibernateTemplate's instance
    }
    
  • Create an xml file for bean configuration
    In this file, configure the bean for BasicDataSource class which contains the information about driverClassName, url of database, username, password. Remember, we have added DBCP jar and pool jar at the beginning. This BasicDataSource class is located in DBCP jar.

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    		<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    		<property name="url" value="jdbc:mysql://localhost/JavaEEPractice"/>
    		<property name="username" value="root"/>
    		<property name="password" value=""/>
    </bean>
    

    Now, create the bean for LocalSessionFactoryBean. FactoryBean creates the SessionFactory. SessionFactory can then be passed to DAO class we created earlier through dependency injection. Mapping resources and hibernate properties are specified in this bean(similar to as we write in cfg.xml file).

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    		<property name="dataSource"  ref="dataSource"/>
    
    		<property name="mappingResources">
    				<list>
    				<value>student.hbm.xml</value>
    			</list>
    		</property>
    
    		<property name="hibernateProperties">
    			<props>
    				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
    				<prop key="show_sql">true</prop>
    				<prop key="hibernate.hbm2ddl.auto">update</prop>
    			</props>
    		</property>
    </bean>
    

    Now, create the bean for DAO class, where you will simply do the setter injection of LocalSessionFactoryBean(which creates SessionFactory) to the reference of SessionFactory in DAO class.

    <bean id="templateDAO" class="com.mitaly.TemplateDAO">
    		<property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    
  • Create a class with main method
    Now, there come the last step of creating a class having main method where we would get instantiate ApplicationContext and get the bean of templateDAO class created and call the required business methods. That’s it.

AJAX and Spring DAO- Spring+JDBC

AJAX stands for Asynchronous Javascript and XML. This is the technology used to create interactive web pages where web page is updated within seconds without reloading the page. When user fills a form and submits it, the inputs get checked at server side and if any credential is wrong, user has to again fill and again submit that form. This is what a user doesn’t want. AJAX is a client-side scripting that communicates with server/database without the need for a postback or complete page refresh.

Example: Everyone must have seen cricbuzz site. The score gets updated automatically there without the need of refreshing the page. This eases the user and that is through AJAX.

I am gonna illustrate the concept through an example. What I will do is that I will create an input field. When user starts typing something, the text will be matched against the name attribute in Student table in database using LIKE clause. Then matching rows will be shown in table.

index.html-

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My web page</title>
<style>

table, th, td{
	border:1px solid black;
}
table{
	width:100%;
}
</style>

<script type="text/javascript">
 var request;
	function loadTable(){
		var nameusr = document.getElementsByName('nameusr')[0].value;
		var url = "showdata.jsp?name="+nameusr;
		if(window.XMLHttpRequest){
			request = new XMLHttpRequest();
		}else{
			request = new ActiveXObject("Microsoft.XMLHTTP");
		}

		try{
			request.onreadystatechange = getInfo;
			request.open("GET", url, true);
			request.send();
		}catch(e){
			window.alert("Some exception");
		}
	}

	function getInfo(){
		if(request.readyState == 4){
			var res = request.responseText;
			document.getElementById('table').innerHTML = res;
		}
	}

</script>
</head>
<body>
	<center>
<h4>Enter Name</h4>
<input type="text" name="nameusr" onkeyup="loadTable()"/>

		<span id="table"></span>
	</center>
</body>
</html>

showdata.jsp-

<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.DriverManager"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"     pageEncoding="UTF-8"%>
<%
	String name = request.getParameter("name");

    if(name.trim().equals("")){
    	out.print("
No record to display");
    }else{
    	try{
    		Class.forName("com.mysql.jdbc.Driver");
    		String url = "jdbc:mysql://localhost/JavaEEPractice";
    		Connection conn = DriverManager.getConnection(url,"root","");

    		String sql = "Select * from Student where name like '"+name+"%'";

    		Statement stmt = conn.createStatement();

    		ResultSet rs = stmt.executeQuery(sql);
    		if(rs.next()){
    			rs.beforeFirst();
    			out.print("
<table>");
    			out.print("
<tr>");
    			out.print("
<th>ROll</th>
<th>Name</th>
<th>Phone</th>
<th>Email</th>
<th>Age</th>
");
    			out.print("</tr>
");
    			while(rs.next()){
    				out.print("
<tr>
<td>"+rs.getInt(1)+"</td>
<td>"+rs.getString(2)+"</td>
<td>"+rs.getString(3)+"</td>
<td>"+rs.getString(4)+"</td>
<td>"+rs.getInt(5)+"</td>
</tr>
");
    			}
    			out.print("</table>
");
    		}else{
    			out.print("
No record to display");
    		}

     		conn.close();
    	}catch(Exception e){
    		out.print("Some error "+e);
    	}
    }

%>

Database table-

db1

Output-scusers1


Spring DAO(Data Access Objects):

DAO’s function is to read and write data to and from the persistent devices such as database, files, XML, spreadsheet. DAO has to serve the business problems of accessing and manipulating data. Earlier, in JDBC, we were supposed to create connection, close connection, close the result set etc. But DAO says not to care for such stuff rather focus on implementing the business logic.

Spring provides many data access frameworks such as JDBC, JPA, Hibernate, iBATIS etc. DAO provides a much simpler way to use them. As Enterprise editions keep on updating to newer technologies, so with DAO, problem of converting the code to newer technology becomes a lot easy.

One more good thing, DAO framework don’t throw technology specific exceptions. All these technology specific(Hibernate, JDBC, JPA etc.)  exceptions are subclasses of DataAccessException. So, there’s no need to handle such exceptions.


Spring+JDBC:

DAO package removes the need to do tedious JDBC coding. I am going to specify how to use JDBC module provided by spring framework-

  • Add required jar files.
  • Create a POJO/Model/Bean for which you have table in database.
  • Create an interface where you would declare all the methods(business methods).
  • Create a class that implements the above created interface. In this class, there are two important attributes- JdbcTemplate reference and DataSource reference. Let’s see what are they.JdbcTemplate is an API which allows to not write time consuming stuff like open connection, close connection, exception handling, holding the transactions etc., which we used to do in JDBC.

    Another API we have is DataSource which contains properties like driver class name, url, username, password and creates connection with database. We can use DriverManagerDataSource class or BasicDataSource(DBCP) class. The former doesn’t provide connection pooling but later does.

    We need to write the configuration for data source in XML and also inject it’s dependency to the attribute of DataSource in this class.

  • Then write the code in the main method to call the business method  according to requirement.

BeanPostProcessor and Spring AOP

Today, I got to know about methods through which we can manipulate the objects before even their initialization. BeanPostProcessor interface allows to play with the object before and after it’s initialization. Then, I got familiarized with Spring AOP(Aspect Oriented Programming) to manage the cross-cutting concerns. Let me tell you, what things I explored in them.

BeanPostProcessor:

As, I mentioned about this API that allows to manipulate the objects according to our requirement.

A real life example would be- During user login, validation is performed. So, before actual cross-checking the credentials with database, for the security purpose, data can be encrypted(before initialization). When that’s done, validate the data and decrypt it too(after initialization), so as to show to the user.

Example-

Let say, we have a POJO class, Employee.

Employee.java-

public class Employee {
	String empName;
	int empSalary;
	int empAge;
        public void initMeth() {
		System.out.println("Init called");
	}

	public void destroyMeth() {
		System.out.println("Destroy called");
	}
       public Employee() {
		System.out.println("Default constructor called");
	}
//getters setters
}

MyBeanProcessor-

Now, we create a MyBeanProcessor which implements BeanPostProcessor which has two methods we need to implement.

  • postProcessBeforeInitialization- This method is invoked before initialization method of a bean instance is invoked.
  • postProcessAfterInitialization- This method is invoked after the initialization method of a bean instance is invoked.

Both these methods take two parameters- Object type and String type. Object reference is the object of POJO class. String value is the ID of the bean we specify in the bean configuration.

package com.spring1;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyBeanProcessor implements BeanPostProcessor{

	@Override
	public Object postProcessAfterInitialization(Object obj, String str) throws BeansException {

		System.out.println("postProcessAfterInitialization");
		System.out.println("Object: "+obj);
		System.out.println("String: "+str);
		return obj;
	}

	@Override
	public Object postProcessBeforeInitialization(Object obj, String str) throws BeansException {
		System.out.println("postProcessBeforeInitialization");
		return obj;
	}

}

employee.xml-

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xmlns:context="http://www.springframework.org/schema/context"     xsi:schemaLocation="http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd     http://www.springframework.org/schema/context     http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    	<bean id="e1" class="com.spring1.Employee" init-method="initMeth" destroy-method="destroyMeth">
    		<property name="empName" value="Sheena"/>
    		<property name="empSalary" value="20000"/>
    		<property name="empAge" value="21"/>
    	</bean>

    	<bean class="com.spring1.MyBeanProcessor"/>

  </beans>

Client.java-

Write the code in main method of Client class.

public class Client {
      public static void main(String[] args) {
	   ApplicationContext context = new ClassPathXmlApplicationContext("employee.xml");
	}
}

Output-

Default constructor called
postProcessBeforeInitialization
Init called
postProcessAfterInitialization
Object: Employee [ empName=Sheena, empSalary=20000, empAge=21]
String: e1

 


Spring AOP(Aspect Oriented Programming):

In AOP, we write logic to entertain cross-cutting concerns. Cross-cutting concern is a concern that cannot be ignored at any layer(Presentation, Business, Data access layer). Example- security, transaction processing etc. The logics are written using advices. Advice is an action taken at a particular  join point(execution of a method).

We have different types of advices-

  • Before Advice: Executes before method invocation.
  • After Returning Advice: Executes after method execution has completed.
  • After Throwing Advice: Executes if method throws an exception.
  • After Advice:  Executes regardless of  whether method executed normally or resulted in exception.
  • Around Advice: Executes before and after a method.

Around advice powerful of all though it’s recommended to use less powerful advice which fulfils the requirement.

I am gonna mention real life example where it’s used.

Let say, a client sends request to server. Basically user at client is registering oneself. So, what can be done in that situation. Timestamp can be noted when user starts the registration and timestamp is again noted when user finishes the registration. In this way, the developer will get an idea that how much time it takes to register user in that web application.

To use AOP in project:

  • Firstly link all the jar files(AOP). Make sure, you must have linked the spring core jar files as AOP has requirement that it internally uses spring core.
  • Create a class where you would want to use AOP.User.java-
    public class User {
    	int uid;
    	String name;
    	int age;
    
    //constructor
    //getters setters
    
    public void registerUser(){
    		System.out.println("--registration started--");
    //Assuming 2 seconds for database operation(Register user)
    		try {
    			Thread.sleep(2000);
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		}
    		System.out.println("--registration done--");
    	}
    }
    
  • Create class that implements the required Advice. For before advice, class must implement MethodBeforeAdvice interface. For After advice, implement AfterReturningAdvice.BeforeAdvice.java-
    import java.lang.reflect.Method;
    import org.springframework.aop.MethodBeforeAdvice;
    
    public class BeforeAdvice implements MethodBeforeAdvice{
    
    	@Override
    	public void before(Method method, Object[] objArr, Object obj) throws Throwable {
    		System.out.println("--BeforeAdvice executed--");
    
    	        for(Object ob : objArr)
    				System.out.println("Object in array: "+ob);
    
    		System.out.println("Objec1: "+obj);
    		System.out.println("------------------------------");
    	}
    }
    

    AfterAdvice.java

    import java.lang.reflect.Method;
    import org.springframework.aop.AfterReturningAdvice;
    
    public class AfterAdvice implements AfterReturningAdvice{
    
    	@Override
    	public void afterReturning(Object obj1, Method method, Object[] objArr, Object obj2) throws Throwable {
    		System.out.println("--AfterAdvice executed--");
    
    		for(Object ob : objArr)
    			System.out.println("Object in array: "+ob);
    
    		System.out.println("Objec1: "+obj1);
    		System.out.println("Objec2: "+obj2);
    		System.out.println("------------------------------");
    
    	}
    }
    
  • Configure the beans in xml file. You must configure the bean for BeforeAdvice and AfterAdvice as well. Configure the bean for ProxyFactoryBean which has two properties- target and interceptorNames.user.xml-
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
        
        	<bean id="user1" class="com.springaop.User">
        		<property name="uid" value="111"/>
        		<property name="name" value="Sneha"/>
        		<property name="age" value="23" />
        	</bean>
        	
        	<bean id="bfrAdv" class="com.springaop.AfterAdvice" />
        	<bean id="aftAdv" class="com.springaop.BeforeAdvice" />
        	
        	<bean id="userProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        	  <property name="target" ref="user1" />
        	  <property name="interceptorNames">
        	  	<list>
        	  		<value>bfrAdv</value>
        	  		<value>aftAdv</value>
        	  	</list>
        	  </property>
        	</bean>
        	
        </beans>
    
  • Client.java-
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    public class Client {
               public static void main(String[] args) {
    		ApplicationContext cxt = new ClassPathXmlApplicationContext("user.xml");
    		User user = (User)cxt.getBean("userProxy");
    		user.registerUser();
    	}
    
    }
    
  • Output-
    --BeforeAdvice executed--
    Objec1: User [uid=111, name=Sneha, age=23]
    ------------------------------
    --registration started--
    --registration done--
    --AfterAdvice executed--
    Objec1: null
    Objec2: User [uid=111, name=Sneha, age=23]
    ------------------------------
    

Spring core(Part 2)

Today, I got familiarized with Dependency Injection in springs, collection injection, inheritance relation in springs and autowiring. Now, I am going to discuss what I learnt about them.

Dependency Injection-

I will take an example of two classes Person and Address to explain what is dependency injection.

Address class-

public class Address {
	String area;
	String city;
	String state;
	int zipCode;
//constructors

//getters and setters
}

Person class-

public class Person {
	String name;
	String email;
	int age;
	Address address;

	public Person() {
	     address = new Address();
	}
 //getters and setters

Person class has reference to Address class as an attribute. When Person object gets created, then only object of Address type is created as constructor of Person will be called then only. So, clearly we can see that creation of Address object is highly coupled to creation of Person object. The method for object construction of Address, you saw above lead to many problems. So, we should rather implement loosely coupled way for this. That is done by dependency injection. It can be done by two ways:

  • DI through constructors-

This says, create constructor of Person and pass reference of already created Address object to it.


public Person(Address address) {

this.address = address; }

XML for constructor based DI- Write the bean attributes for both the class in the same way. Just add the following line in Bean for Person as specified below. ‘adrs’ is the id of bean of Address.

<constructor-arg ref="adrs1" />
  • DI through setters-

This says, create a setter method in Person and pass reference of already created Address object to it.

    public void setAddress(Address address) {
this.address = address; }

XML for setter based DI- Write the bean attributes for both the class in the same way. Just add another property in Bean for Person as specified below. ‘adrs’ is the id of bean of Address.

<property name="address" ref="adrs" />

 


Injecting Collection:

Let say, we have an attribute in class which is not primitive datatype; rather it is a collection. Ok, let’s take an example of Manager class. A manager can have certificates(0 or more). So, it possesses a list of certificates.

public class Manager {

	String name;
	String email;
	int salary;

	List<String> certificates;
//getters and setters
}

In XML file, the code for bean of Manager is as under-

<bean id="mngr" class="com.spring2.Manager">
    	<property name="name" value="Sheena"/>
    	<property name="email" value="sheena@ex.com"/>
    	<property name="salary" value="50000"/>
    	<property name="certificates">
    	        		<list>
    		        <value>AWS</value>
    			<value>OCJP</value>
    			<value>CCNA</value>
    		</list>
    	</property>
    </bean>

 


Inheritance Relation in springs:

The concept is same as java class inheritance. In XML configuration, we just introduce a new attribute parent, specifying the parent bean as the value of this attribute.

I will demonstrate this by an example. Let say, there’s a class named Father having attributes as:

 public class Father {

	String fname;
	String lname;
	int wealth;
}

There’s another class Child which extends Father. Here, we have those attributes which are unique to Child.

public class Child extends Father{

	String hobby;
	int vehicles;
}

Now, coming to XML file. Define the bean configuration for both the classes. In Child bean, we can define the properties of Father class(as Child extends Father), which are fname, lname, wealth and obviously it’s own properties as well. Notice, there’s a parent attribute in Child bean whose value is same as the id of Father class.

<bean id="father" class="com.spring2.Father">
    	<property name="fname" value="Rakesh"/>
    	<property name="lname" value="Sharma"/>
    	<property name="wealth" value="100000"/>
</bean>
<bean id="child" class="com.spring2.Child" parent="father">
    	<property name="fname" value="Rohan"/>
    	<property name="hobby" value="Singing"/>
    	<property name="vehicles" value="2"/>
</bean>

Now, you can simply fetch the object in main method and display that.

public static void main(String[] args) {
		ApplicationContext cxt = new
                ClassPathXmlApplicationContext("container.xml");

		Child child = cxt.getBean("child", Child.class);
		System.out.println("Firstname: "+child.getFname());
		System.out.println("Lastname: "+child.getLname());
		System.out.println("Wealth: "+child.getWealth());
		System.out.println("Hobbies: "+child.getHobby());
		System.out.println("Vehicles: "+child.getVehicles());
	}

You will get output as:

Firstname: Rohan
Lastname: Sharma
Wealth: 100000
Hobbies: Singing
Vehicles: 2

 


AutoWiring:

Dependencies can be injected internally by autowiring. It makes the development faster since we need not define the dependency explicitly. We have two ways to do this- Autowiring through XML and @Autowired annotation. I will discuss about annotation way. If one has to see the XML way, visit this.

For this, let’s consider the Person-Address relation we saw above and inject dependency of Address in respective attribute in Person class using autowiring.

Come to Person class. Add the @Autowire annotation on the setter method, constructor or field itself. I have added this on setter method for Address.

public class Person {
	//other attributes
	Address address;
	@Autowired
	public void setAddress(Address address) {
		this.address = address;
	}
 //constructor
//other getters and setters
}

In XML file, you need to register AutowiredAnnotationBeanPostProcessor. For registering, just include ” line as shown below in XML file.

<context:annotation-config />
    	<bean id="prsn" class="com.spring2.Person">
    		<!--Define properties and values of attributes of Person except the attribute for Address type -->
    	</bean>

    	<bean id="address" class="com.spring2.Address">
    		<!-- Define the properties and values of all attributes of Address -->
    	</bean>

Now, simply add the code in main method to fetch the Person object, then you will see the Address fields are also initialized as written in bean definition.

For finding more information on Autowiring through annotation, go through the link I provided below. 🙂

http://www.mkyong.com/spring/spring-auto-wiring-beans-with-autowired-annotation/

Spring core(Part 1)

Today, sir gave an introduction to Spring framework and discussed spring core. So, what is spring?The Spring Framework is an application framework and inversion of control container for the java platform. It can be called as framework of frameworks. It provides plenty of features like predefined templates, lightweight, easy testing, fast development, loose coupling, etc.

Now, coming to the architecture of spring framework:

spring_arch

Spring framework has a modular N-layered architecture. Several modules are provided by this framework. One can always choose the desired module(needed by the application to be developed) and skip the rest.

  • Core container:

The important functionalities of IOC(Inversion of Control) and DI(Dependency Injection) are provided in this module specifically in core. Beans provides BeanFactory and Context provides ApplicationContext which we will discuss soon. Expression languages are similar to expression languages in jsp which are used for querying and manipulating objects.

  • AOP(Aspect Oriented Programming):

This helps in handling cross cutting concerns like security and caching. Basically, helping to decouple cross-cutting concerns from the objects that they affect.

  • Data Access/ Integration:

A good news, we don’t have to care much for JDBC, Hibernate, ORM, tranasction etc. They are built in already in this framework. Provision of database management modules has eased the development of applications.

  • Web Module:

Now, we need not care about MVC pattern. That too is provided by Spring framework. It comes already with MVC framework for easy development of applications.


IOC(Inversion Of Control):

This is a very important feature provided by spring framework. What it tells that you don’t need to care about object creation, it will done by the framework itself. IOC is basically provided by a container(Spring container) that is responsible for object creation, its management and destruction. Now, we will look deeper into Spring container to have better clarity of IOC.

We have two different spring containers. They are BeanFactory and ApplicationContext. BeanFactory possess mechanism capable of managing any type of object. ApplicationContext also works the same way. But there exists differences between them. Let’s look into that.

Difference between BeanFactory and ApplicationContext-

  • The first difference is that ApplicationContext is an implementation of BeanFactory. So, we can say it is superset of BeanFactory providing more implementations.
  • Second big difference, I came to know today is that BeanFactory creates the object only when requested by user explicitly but ApplicationContext creates objects specified in the configuration file even if user has not requested for the objects.

So, now we will see an example. Before that just know how to create a project using spring framework. The procedure is as-

    1. Link all the jar files for spring core. Though it depends on the requirement. I am using spring core because the example I am going to demonstrate has that requirement only. For this first create a simple java project. Right click project name in package explorer -> Build Path -> Configure Build Path -> Add External Jars(make sure, Libraries tab is selected) -> Now browse for jar files in your system. After selecting those, click Apply and Close.
    2. Now, create a Bean/POJO class. I have created Employee class. It’s time to create an XML file for configuring the objects for the POJO. Configuring means specifying the values for all the attributes of object. For this, simply create an XML file in src directory. Give a name of your choice.                        Employee.java-
      
      public class Employee {
       String empName;
       int empSalary;
       int empAge;
      
      public Employee() {
       empName = null;
       empSalary = 0;
       empAge = 0;
       System.out.println("Default constructor called");
       }
       public Employee( String empName, int empSalary, int empAge) {
       super();
      
      this.empName = empName;
       this.empSalary = empSalary;
       this.empAge = empAge;
      }
       public String getEmpName() {
       return empName;
       }
       public void setEmpName(String empName) {
       this.empName = empName;
       }
       public int getEmpSalary() {
       return empSalary;
       }
       public void setEmpSalary(int empSalary) {
       this.empSalary = empSalary;
       }
       public int getEmpAge() {
       return empAge;
       }
       public void setEmpAge(int empAge) {
       this.empAge = empAge;
       }
       @Override
       public String toString() {
       return "Employee [ empName=" + empName + ", empSalary=" +
       empSalary + ", empAge=" + empAge + "]";
       }
       }
      
      

      employee.xml-

      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xmlns:context="http://www.springframework.org/schema/context"     xsi:schemaLocation="http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd     http://www.springframework.org/schema/context     http://www.springframework.org/schema/context/spring-context-3.0.xsd">
      
          	<bean id="e1" class="com.spring1.Employee" init-method="initMeth" destroy-method="destroyMeth">
          		<property name="empName" value="Sheena"/>
          		<property name="empSalary" value="20000"/>
          		<property name="empAge" value="21"/>
          	</bean>
      
          	<bean id="e2" class="com.spring1.Employee" init-method="initMeth" destroy-method="destroyMeth">
          		<property name="empName" value="Riya"/>
          		<property name="empSalary" value="25000"/>
          		<property name="empAge" value="23"/>
          	</bean>
          </beans>
      
    3. Now, create a class having main method where we will use spring container(BeanFactory or ApplicationContext) to get the access of objects from xml file created in the previous step.
      public class Client {
      
      	public static void main(String[] args) {
      		Resource resource = new ClassPathResource("employee.xml");
      
      		BeanFactory factory = new XmlBeanFactory(resource);
      		Employee e1 = (Employee)factory.getBean("e1");
      		System.out.println("e1: "+e1);
      
      		ApplicationContext context = new ClassPathXmlApplicationContext("employee.xml");
      		Employee e2 = (Employee)context.getBean("e2");
      		System.out.println("e2: "+e2);
      	}
      
      }
      
      

      Now, see the output:

      Default constructor called
      e1: Employee [ empName=Sheena, empSalary=20000, empAge=21]
      Default constructor called
      Default constructor called
      e2: Employee [ empName=Riya, empSalary=25000, empAge=23]
      

      Observation: Default constructor is called, means object is created first for e1 when requested by BeanFactory. Similarly it has to be for e2 which is requested by ApplicationContext. But main point to be noted is that constructor is called two times before printing e2 employee. One was invoked for e1 and other for e2. Although, e1 has not been requested by ApplicationContext, still the object for e1 gets created. This is the main difference between BeanFactory and ApplicationContext.

 


Bean Lifecycle:

One interesting thing,  you can have lifecycle methods for your bean class. Means, now you can see when object gets initialized and when it is destroyed. Just define two methods in POJO class- one for init and other for destroy. Name them anything you want.

In XML file, modify the Bean by adding init-method and destroy-method. Make sure, you pass the values to these parameters as the method name(for init and destroy) you created in POJO class.

Now, whenever objects are created and destroyed, the respective method gets executed.

 


Bean Scope:

We can define scope for objects in XML file. scope parameter can be set to singleton, prototype, session, etc.

By default, it’s singleton. This means, even if we create two reference variables having same objects. Then they will be containing same address for object location. Means, single object is created in heap and both the reference variables will be pointing to that.

Scope can be prototype. Object having this scope will be created again and again for different reference variables.


IOC in Android:

Lastly, sir discussed about IOC in android. We have XML files in android where we design layout for apps. Views or viewgroups specified in XML have specific id. Whenever we call, findViewById in java code for id of particular view or viewgroup then IOC creates object for that particular view. So, everything in Android is also an object.  🙂

An Intro to Hibernate

Today, I got to know about an exciting framework, Hibernate. I am calling it exciting for many reasons and that’s why it is much in use by developers.

In JDBC, we used to set the driver class, create connection,  close connection, manage the transactions, code for batch processing and most importantly create table manually in database. Now, question comes, how Hibernate helps in that issue. Here’s the answer, below.

  • Hibernate is an ORM(Object Relational Mapping) tool that itself maps the objects in our program with tuples in the table. It creates table on its own with the help of POJO class which we create.
  • Not only this, hibernate allows to write less code for transaction management and many other queries.
  • Here, we mention the configuration information such as Driver class name, database name, username, password, url etc. in separate file (in most cases, hibernate.cfg.xml file). So, we need not to go to code for changing any parameter in future. We just have to modify the cfg.xml file.
  • A very important feature it provides is the Hibernate Query Language(HQL). HQL is database independent. So, it avoids database portability hassles.

Configuring the Hibernate:

  1. Link the jar files.
  2. Configure hibernate.cfg.xml
  3. Configure anyname.hbm.xml file
  4. Write the hibernate statements
  • Link the jar files

Create a java project. Download the jar files for hibernate. Right click project -> Build Path -> Configure Build Path. Click Add external jars. Choose all jars and click Apply an Close.

  • Configure hibernate.cfg.xml

Create an xml file by ‘hibernate.cfg.xml’ name. You can give any name but it’s better to give this name as it this file will be automatically read, otherwise we have to specify the name explicitly in the code.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost/HibernateProject</property>
        <property name="hibernate.connection.username">root</property>
        <property name="connection.password"></property>
        <property name="connection.pool_size">10</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <mapping resource="employee.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

It contains information such as driver class, url, username, password.

connection.pool_size- indicates the maximum number of pooled connections.

hibernate.dialect- Dialect class writes the query statements on our behalf. I told earlier about HQL that is database independent which operates on objects and not on table directly. So, queries for table will be written and fired by Dialect class which we specify here.

show_sql- If this property is true, then you can see the query statements fired by dialect class in console when you run the project.

hibernate.hbm2ddl.auto- If the value of this property is create, then table will be created again by deleting the previous table if present by the same name. If its value is update, then already created table will be modified.

mapping resource- Here, you will specify the hbm.xml mapping file, about which I’ll tell soon.

  • Configure anyname.hbm.xml file

Firstly you will have to create a POJO class. I created Employee class.

package com.mitaly;

public class Employee {

	int id;
	String name;
	String phone;
	int salary;
// constructor
//getters and setters
}

Now, create an xml file named ‘employee.hbm.xml‘. This file contains the mapping information. You will specify the attributes in POJO and corresponding column names.

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC   "-//Hibernate/Hibernate Mapping DTD//EN"  "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
   <class name="com.mitaly.Employee" table="Employee">
      <id name="id" column="eId">
         <generator class="increment"/>
      </id>
      <property name="name" column="eName"/>
      <property name="phone" column="ePhone"/>
      <property name="salary" column="eSalary"/>
   </class>
</hibernate-mapping>

 

  • Write the hibernate statements

Create a main class and write the following code to create an object of Employee class and store in database.

package com.mitaly;

public class Client {
	public static void main(String[] args) {

		Configuration config = null;
		SessionFactory factory = null;
		Session session = null;
		Transaction transaction = null;

		try {

			config = new Configuration();
			// this will read the hibernate.cfg.xml file
			config.configure();

			factory = config.buildSessionFactory();

			session = factory.openSession();

			transaction = session.beginTransaction();

			Employee emp = new Employee(1, "Shanaya", "90909 99993",19000);

			//for saving the data in table
			session.save(emp2);

			transaction.commit();

		}catch (Exception e) {

			transaction.rollback();
		}finally {
			session.close();
		}
	}

}

JSP(Java Server Pages)

JSP is a technology used to create dynamic web pages. It is combination of HTML and JSP tags and has more functionalities over servlet. In servlet, it was difficult to include HTML content as we have to write out.print again and again. JSP solves that problem as it combines HTML and Java code in single page.

Lifecycle:

JSP exercises necessary overhead. Let’s see how.

jsplifecyclegif

Web container translates the .jsp file into servlet code(.java). After that the servlet gets compiled and .class file is generated. Then it is loaded by classloader and instance of servlet class is created by container. This initialized servlet can request now.


Tags in JSP:

  1. Scriplet- Scriplet tag allows to write java code inside . You can simple write servlet code within these tags. One great feature is that, JSP provides the access of objects such as out, request, response, session etc. implicity i.e. we need not create objects for those, they are already created and we can refer them anytime.
  2. Declaration- Declaration tags allow to declare attributes and methods. They are to be enclosed within .
  3. Expression- The code inside expression tags is written to output stream. It is equivalent to out.print. Code needs to be written inside .

Including a file in JSP:

In JSP we can also add another file’s content. I also told you about how to include file in Servlet using request dispatcher. In JSP it’s done by:

<%@include file="anyfile.html" %>

Exception handling:

We can either write a basic try catch block for handling the exceptions or we can include an error page in the file where exception may occur. We can make any page as error page to display error to user in an appropriate manner, by setting page directive attribute isErrorPage as true.

error.jsp-

<%@ page language="java" contentType="text/html; charset=UTF-8"     pageEncoding="UTF-8"%>
<%@ page isErrorPage="true" %>
<!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=UTF-8">
<title>My web page</title>
</head>
<body>
	Some exception has occured:
	<%=exception %>
</body>
</html>
 

index.jsp-

Add the error.jsp page in index.jsp page(where error might occur).


<%@ page language="java" contentType="text/html; charset=UTF-8"     pageEncoding="UTF-8"%>
<%@ page errorPage="error.jsp" %>
<!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=UTF-8">
<title>My web page</title>
</head>
<body>
<h2>Getting value at index 20</h2>
<%! int num[] = {10,20,30}; %>
  <%     out.print("Number at index 30: "+num[20]);   %>
</body>
</html>

Output-

Screenshot from 2017-06-26 15-19-51

Filter, Init param, Context param

I am today gonna discuss about Filters, static parameters which are init-param and context-param.

Filters:

Filters are the pluggable components where preprocessing and postprocessing is done. Preprocessing is executing the code before request is sent to servlet and postprocessing means executing the code after servlet code is finished and before the container sends the response back to client. Main tasks performed at preprocessing are decryption of message sent from client, data decompression, input validation etc. At postprocessing, tasks such as encryption of response message to be sent to client, data compression etc.

Example- I have created a login form validation(checks for empty fields) using filter. Filter will check for the input fields at it’s own end first. If any one of the field is empty, it will display a message and login form is shown again else request will be redirected to associated servlet.

index.html-


<!DOCTYPE html>
<html >
<head>
<title>Flat Login Form</title>
</head>
<body>
<h2>Login to your account</h2>
<form action="Login" method="post">
      <input type="text" placeholder="Email" name="txtEmail"/>
      <input type="password" placeholder="Password" name="txtPassword"/>
      <button type="submit" value="Login">Login</button>
    </form>

</body>
</html>

 

MyFilter.java-

doFilter is the method which has an important role in Filter. This is invoked every time by container when it has to apply filter to a resource. Container provides request and response object references to filter as argument. FilterChain is used to invoke the next filter in the chain.

@WebFilter("/MyFilter")
public class MyFilter implements Filter {

    public MyFilter() {

    }
    public void init(FilterConfig fConfig) throws ServletException {
		// initialize resources
     }

     public void destroy() {
	    // free the memory occupied by resources
     }

     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

		String email = request.getParameter("txtEmail");
		String password = request.getParameter("txtPassword");

		PrintWriter out = response.getWriter();
		if(email.trim().equals("") || password.trim().equals("")) {

			RequestDispatcher dispatcher = request.getRequestDispatcher("index.html");
			dispatcher.include(request, response);

			out.print("<center>Fill required field(s) and then proceed</center>");
		}else {
			chain.doFilter(request, response);
		}
	}
}

 

ServletClass.java-

Filter is applied to this class. When the empty fields are checked by filter, then request goes to this servlet class where we would write code for cross-checking the email and password(the fields in index.xml)  from database which is done by JDBC.

@WebServlet("/Login")
public class ServletClass extends HttpServlet {
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          /* here, write the code for vaidation of email and password using JDBC */
     }
}

 

web.xml-

We need to configure web.xml. Declare the filter here and do the filter-mapping. Make sure the url-mapping pattern in filter mapping is same as url-mapping of servlet class to which we want to link our filter.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>JavaEEProject</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
    <servlet-name>Login</servlet-name>
    <servlet-class>ServletClass</servlet-class>
  </servlet>

  <filter>
    <filter-name>MyFilter</filter-name>
    <filter-class>MyFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>MyFilter</filter-name>
    <url-pattern>/Login</url-pattern>
  </filter-mapping>

</web-app>

 


Init-param:

This is static parameter stored in web.xml file. It has param-name(key) and param-value. This type of parameter is declared within the scope of a servlet of filter and has private scope to them only.

<servlet>
     <display-name>ServletClass</display-name>
     <servlet-name>ServletClass</servlet-name>
     <init-param>
         <param-name>Greetings</param-name>
         <param-value>Hello</param-value>
     </init-param>
</servlet>

 

Access the parameter value in servlet using ServletConfig object which can be used to get configuration information from web.xml file.

ServletConfig config=getServletConfig();
String greetings=config.getInitParameter("Greetings");

 


Context-param:

This is similar to init-param. The only difference is it’s global scope. It can’t  be declared locally to any servlet or filter. Data is common to whole application. This is how global parameter is declared in web.xml.

<web-app>
    <context-param>
        <param-name>driver</param-name>
        <param-value>com.mysql.jdbc.Driver</param-value>
    </context-param>
</web-app>

 

Accessing the value in servlet.

ServletConfig config=getServletConfig();
String driver=config.getInitParameter("driver");

Session Tracking

Today, I gained insight into a very important concept of session tracking in servlet. Session Tracking is a way to maintain state (data) of a user to recognize the user. It becomes very important to persist the data of user while the user is navigating between different web pages.

We have four techniques to do the same:

  1. Cookies
  2. URL Rewriting
  3. Hidden Form Fields
  4. HttpSession
  • Cookies:

Cookies are key-value pairs consisting of user’s information or other important information that are stored in cache of browser. When client makes request to the same site, cookies stored during the last session will be transferred along the request, so that the site recognizes the user as an old user and displays the content specific to the user.

Note: The value can only be of String type in cookies.

ServletClass(where cookies are created)-


@WebServlet("/Login")
public class ServletClass extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  /* Here, add the code to validate the user first and then fetch the data(email, age, salary) from database using JDBC */

		Cookie c1 = new Cookie("keyEmail", email);
		Cookie c2 = new Cookie("keyAge", String.valueOf(age));
		Cookie c3 = new Cookie("keySalary", String.valueOf(salary));
		response.addCookie(c1);
		response.addCookie(c2);
		response.addCookie(c3);

		PrintWriter out = response.getWriter();
		out.print("<a href='Home'>Go to Home</a>");
	}
}

ServletHome(where cookies are retrieved)-

@WebServlet({ "/ServletHome", "/Home" })
public class ServletHome extends HttpServlet {

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

                response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.print("<html><body>");
		out.print("
<h3>Welcome User</h3>
");

                //Getting the cookies
		Cookie[] cookieArr = request.getCookies();
		for(Cookie c: cookieArr)
			out.print(c.getName()+" : "+c.getValue());

		out.print("</body></html>");
		}
}

We have some drawbacks of using cookies-

  1. It may be the case that cookies are disabled on client’s machine.
  2. We can’t get access to  single cookie if we wish to access only one, rather we need to fetch the entire cookies array.
  • URL Rewriting:

URL Rewriting embeds the the data in the form of key-value pair in the URL itself (to whichever page we are redirecting). ‘?’ is added after file name in URL. key and value is separated by ‘=’. One parameter is separated from another by ‘&’.

If you will observe, it’s nothing but a GET request in which data is shown in URL.

ServletClass(where  URL is written)-

@WebServlet("/Login")
public class ServletClass extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  /* Here, add the code to validate the user first and then fetch the data(email, age, salary) from database using JDBC */

		PrintWriter out = response.getWriter();
		out.print("<a href='Home?txtEmail="+email+"&txtAge=" 					+ age +"&txtSalary="+salary+"'>Go to Home page</a>");
	}
}

ServletHome(where data is fetched from URL)-

@WebServlet({ "/ServletHome", "/Home" })
public class ServletHome extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              String email = request.getParameter("txtEmail");
	      int age = Integer.parseInt(request.getParameter("txtAge"));
	      int salary= Integer.parseInt(request.getParameter("txtSalary"));

              out.println("Email : "+email);
              out.println("Age : "+age);
	      out.println("Salary : "+salary);

	}
}

This method has drawbacks:

  1. Sensitive data can’t be transferred using this technique as data is visible in URL.
  2. Large amount of data has difficulty to be added in single URL.
  • Hidden Form Fields:

In this technique, we store the information in the hidden field and get it from another servlet. We keep the type of input element as ‘hidden’.

ServletClass(where  Hidden fields are created)-

@WebServlet("/Login")
public class ServletClass extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  /* Here, add the code to validate the user first and then fetch the data(email, age, salary) from database using JDBC */
              PrintWriter out = response.getWriter();
              out.print("<html><body>");
			out.print("
<form action='Home' method='post'>");
			out.print("<input type='hidden' name='txtEmail' value='"+email+"'>");
			out.print("<input type='hidden' name='txtAge' value='"+age+"'>");
			out.print("<input type='hidden' name='txtSalary' value='"+salary+"'>");
			out.print("<input type='submit' value='Go to Home Page'>");
			out.print("</form>

</body></html>");
	}
}

ServletHome(where data is fetched from Hidden fields)-

@WebServlet({ "/ServletHome", "/Home" })
public class ServletHome extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
             String email = request.getParameter("txtEmail");
	     int age = Integer.parseInt(request.getParameter("txtAge"));
              int salary = Integer.parseInt(request.getParameter("txtSalary"));

              out.println("Email : "+email);
              out.println("Age : "+age);
	      out.println("Salary : "+salary);

	}
}

It has drawaback

If we click View Page Source on that page, all the data will be revealed which we have kept hidden. So, privacy is difficult to maintain. :0

  • HttpSession:

In this technique, container creates a session ID for each user. This ID is unique to user and will be used to identify particular user.

ServletClass(where  Hidden fields are created)-

@WebServlet("/Login")
public class ServletClass extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  /* Here, add the code to validate the user first and then fetch the data(email, age, salary) from database using JDBC */
             HttpSession session = request.getSession();
	     session.setAttribute("keyEmail", email);
	     session.setAttribute("keyAge", age);
	     session.setAttribute("keySalary", salary);

             out.print("<a href='Home'>Go to Home</a>");
	}
}

ServletHome(where data is fetched from Hidden fields)-

@WebServlet({ "/ServletHome", "/Home" })
public class ServletHome extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                HttpSession session = request.getSession();
		String email = (String)session.getAttribute("keyEmail");
		int age = (int)session.getAttribute("keyAge");
		int salary = (int)session.getAttribute("keySalary");

		out.print("Email : "+email+"
");
		out.print("Age : "+age+"
");
		out.print("Salary : "+salary+"
");

	}
}