Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses
Showing posts with label JavaBeans Components. Show all posts
Showing posts with label JavaBeans Components. Show all posts

How to use aliases when referring to a bean in configuration file of Spring Framework ?.

A simple example to demonstrate, how to use Aliases when referring to a bean configuration file in Spring Framework

1. Create a Dog class

package com.hubberspot.spring;


public class Dog {

 private String tail;
 private String coat;
 private String breed;

 public String getTail() {
  return tail;
 }

 public void setTail(String tail) {
  this.tail = tail;
 }

 public String getCoat() {
  return coat;
 }

 public void setCoat(String coat) {
  this.coat = coat;
 }

 public String getBreed() {
  return breed;
 }

 public void setBreed(String breed) {
  this.breed = breed;
 }

 public void move() {
  System.out.println("A Dog of breed "+ getBreed() +", " +
    "having "+ getCoat() +"\nand "+ getTail() + " " +
    "tail moves slowly ...");
 }


}




2. Create a Spring configuration file say spring.xml and place it in classpath i.e src folder of your Eclipse



1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" 
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

 <!-- In order to create an object of bean we define its properties in bean 
  tag. The 'id' attribute value can be thought of as a reference to 'class' 
  attribute value -->

 <bean id="dog" class="com.hubberspot.spring.Dog">


  <!-- setting the property of dog from the spring configuration file, the 
   property tag uses the setter method to set the properties to its respective 
   field -->

  <property name="tail" value="straight"></property>
  <property name="coat" value="stripes on white fur"></property>
  <property name="breed" value="German Shepherd"></property>

 </bean>

 <!-- here name is mapped with the id of the bean and alias is the new name 
  designers provide as per requirement -->
 <alias name="dog" alias="dog-alias" />


</beans>



3. Create a test class and run to see the output below :

package com.hubberspot.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class WildLifeApplication {

 public static void main(String[] args) {

  // ApplicationContext is a Spring interface which 
  // provides with the configuration for an application. 
  // It provides us with all the methods that BeanFactory 
  // provides. It loads the file resources in a older 
  // and generic manner. It helps us to publish events to the
  // listener registered to it. It also provides quick support
  // for internationalization. It provides us with the object 
  // requested, it reads the configuration file and provides
  // us with the necessary object required.
  // We are using concrete implementation of ApplicationContext
  // here called as ClassPathXmlApplicationContext because this 
  // bean factory reads the xml file placed in the classpath of 
  // our application. We provide ClassPathXmlApplicationContext
  // with a configuration file called as spring.xml placed
  // at classpath of our application. 
  ApplicationContext context = 
    new ClassPathXmlApplicationContext(("spring.xml"));

  // In order to get a object instantiated for a particular bean 
  // we call getBean() method of ClassPathXmlApplicationContext
  // passing it the id for which the object is to be needed. 
  // Here getBean() returns an Object. We need to cast it back 
  // to the Dog object. Without implementing new keyword we 
  // have injected object of Dog just by reading an xml 
  // configuration file.
  Dog dog = (Dog)context.getBean("dog");

  // Calling our functionality
  dog.move();
  
  // getting the same bean of dog by calling the alias of dog
  // alias help us by providing different name to a single
  // bean as per our design needs.
  // check for changes done in spring.xml file
  dog = (Dog)context.getBean("dog-alias");

  // Calling our functionality
  dog.move();

 }

}





Output of the program :



How to use model / Java / Pojo classes with JSP and Servlets ?.


Program to demonstrate how to use model / Java / Pojo classes with JSP and Servlets

Model Class in Java :


package com.hubberspot.model;

public class Customer {

 private String firstName; 
 private String lastName; 
 private String emailAddress;

 public Customer() {  
  firstName = "";
  lastName = "";
  emailAddress = "";
 }
 
 public Customer(String firstName , String lastName , String emailAddress) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.emailAddress = emailAddress;
 }

 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
 public String getEmailAddress() {
  return emailAddress;
 }
 public void setEmailAddress(String emailAddress) {
  this.emailAddress = emailAddress;
 }

}




Service Class in Java :

package com.hubberspot.utility;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import com.hubberspot.model.Customer;

public class CustomerService {

    public static void write(Customer customer, String filePath) {
 try {

  File file = new File(filePath);
  FileWriter writer = new FileWriter(file);
  PrintWriter out = new PrintWriter(writer);
   
  String firstName = customer.getFirstName();
  String lastName = customer.getLastName();
  String emailAddress = customer.getEmailAddress();
   
  out.println("First Name : "+ firstName+"" );
  out.println("Last Name : "+ lastName+"" );
  out.println("Email Address : "+ emailAddress+"" );
out.close(); 
 } catch (IOException e) {   
  e.printStackTrace();
 }
   }
}




subscribe.html



1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.

<!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>Email Subscription</title>
</head>
<body>
 <h1>Join Hubberspot's Email list</h1>
 <p>
  In order to join our email list, enter you name and email address
  below </br> and Click Submit button.
 </p>

 <form action="email_entry.jsp" method="get">
  <table cellspacing="5" border="0">
   <tr>
    <td align="right">First Name : </td>
    <td><input type="text" name="firstName"></td>
   </tr>
   <tr>
    <td align="right">Last Name : </td>
    <td><input type="text" name="lastName"></td>
   </tr>
   <tr>
    <td align="right">Email Address : </td>
    <td><input type="text" name="emailAddress"></td>
   </tr>
   
   <tr>
    <td></td>
    <td align="left"></br><input type="submit" value="Submit"></td>
   </tr>

  </table>
 </form>
</body>
</html>


email_entry.jsp



1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.

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

 <%
  // Get the form requests 
  String firstName = request.getParameter("firstName");
  String lastName = request.getParameter("lastName");
  String emailAddress = request.getParameter("emailAddress");
  
  // Get the complete real path for subscription.txt
  ServletContext context = request.getServletContext();
  String filePath = context.getRealPath("/subscription.txt");
    
  // Using DataModel in a JSP
  Customer customer = new Customer(firstName, lastName, emailAddress);
  
  // Using the CustomerService class to write info to file
  CustomerService.write(customer, filePath);
 %>

 <h1>Thanks for joining Hubberspot's Email list</h1>
 <p>Kindly have a look what you have entered :</p>

 <table cellspacing="0" cellpadding="5" border="1">
  <tr>
   <td align="right">First Name :</td>
   <td><%=customer.getFirstName()%></td>
  </tr>

  <tr>
   <td align="right">Last Name :</td>
   <td><%=customer.getLastName()%></td>
  </tr>

  <tr>
   <td align="right">Email Address :</td>
   <td><%=customer.getEmailAddress()%></td>
  </tr>
 </table>

 <p>
  To provide correct information, click 'back' on browser window </br>or
  click on Back button below :
 </p>
 
 <form action="subscribe.html" method="post">
 <input type="submit" value="Back">
 </form>

</body>
</html>


How to run the application :
  1. Deploy the application on the server.
  2. Run and request for subscribe.html.
  3. After filling the necessary data , submit the data to email_entry.jsp.
  4. email_entry.jsp displays the information in it .
  5. A file subscrition.txt gets created and data is written to it by CustomerService class.



Output of the program : 

1. subscribe.html


























 2. email_entry.jsp




 3. subscription.txt

 

How to work with Inner beans using configuration file in a Spring Framework ?.




A simple example to demonstrate, how to work with Inner beans to provide object dependency injection to a bean using Configuration file in Spring Framework

1. Create a Coat class

package com.hubberspot.spring;

public class Coat {

 private String color;
 private String type;

 public String getColor() {
  return color;
 }

 public void setColor(String color) {
  this.color = color;
 }

 public String getType() {
  return type;
 }

 public void setType(String type) {
  this.type = type;
 } 

}




2. Create a Tail class

package com.hubberspot.spring;

public class Tail {

 private int length;
 private String color;

 public int getLength() {
  return length;
 }

 public void setLength(int length) {
  this.length = length;
 }

 public String getColor() {
  return color;
 }

 public void setColor(String color) {
  this.color = color;
 } 
}




3. Create a Dog class

package com.hubberspot.spring;


public class Dog {

 private Tail tail;
 private Coat coat;


 public Tail getTail() {
  return tail;
 }

 public void setTail(Tail tail) {
  this.tail = tail;
 }

 public Coat getCoat() {
  return coat;
 }

 public void setCoat(Coat coat) {
  this.coat = coat;
 }


 public void move() {

  System.out.println("A Dog having "+ getCoat().getColor() +
   " color coat \nand "+ getTail().getLength() + " cms" +
   " tail moves slowly ...");

 }

}




4. Create a Spring configuration file placed in the classpath of Spring project


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" 
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

 <!-- In order to create an object of bean we define its properties in bean 
  tag. The 'id' attribute value can be thought of as a reference to 'class' 
  attribute value -->

 <bean id="dog" class="com.hubberspot.spring.Dog">

  <!-- dog has a property called as tail and coat which are objects of class 
   Tail and Coat. In order to have Object injection i.e Tail and Coat to class 
   Dog we use ref attribute of property tag which points to the id of bean that 
   we want to inject -->

  <!-- Here Dog class has Tail and Coat objects but there is some slight 
   difference in their working. Class Coat is a normal been referenced by Dog 
   by its id, whereas Tail Class is an Inner class to Dog. It is visible to 
   Dog by its own definition. No id attribute is given for the classes which 
   are Inner class. -->

  <property name="tail">
   <bean class="com.hubberspot.spring.Tail">

    <property name="length" value="30"></property>
    <property name="color" value="white"></property>

   </bean>
  </property>
  <property name="coat" ref="coat"></property>

 </bean>

 <bean id="coat" class="com.hubberspot.spring.Coat">

  <property name="type" value="stripes"></property>
  <property name="color" value="white"></property>

 </bean>



</beans>


5. Create a Test class and Run it to see the output below -

package com.hubberspot.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class WildLifeApplication {

 public static void main(String[] args) {

  // ApplicationContext is a Spring interface which 
  // provides with the configuration for an application. 
  // It provides us with all the methods that BeanFactory 
  // provides. It loads the file resources in a older 
  // and generic manner. It helps us to publish events to the
  // listener registered to it. It also provides quick support
  // for internationalization. It provides us with the object 
  // requested, it reads the configuration file and provides
  // us with the necessary object required.
  // We are using concrete implementation of ApplicationContext
  // here called as ClassPathXmlApplicationContext because this 
  // bean factory reads the xml file placed in the classpath of 
  // our application. We provide ClassPathXmlApplicationContext
  // with a configuration file called as spring.xml placed
  // at classpath of our application. 
  ApplicationContext context = 
    new ClassPathXmlApplicationContext(("spring.xml"));

  // In order to get a object instantiated for a particular bean 
  // we call getBean() method of ClassPathXmlApplicationContext
  // passing it the id for which the object is to be needed. 
  // Here getBean() returns an Object. We need to cast it back 
  // to the Dog object. Without implementing new keyword we 
  // have injected object of Dog just by reading an xml 
  // configuration file.
  Dog dog = (Dog)context.getBean("dog");

  // Calling our functionality
  dog.move();

 }

}





6. How it exactly works see below diagram - 





























Output of the program - 


 





How to create a simple JavaBean component ?.

JavaBeans are the powerful reusable components created for reducing redundant code . The JavaBean has few rules associated with it . The JavaBean creation process is easy and simple . The process of creating a JavaBean is demonstrated below .

The Bean creating process :

In order to create a bean , we have to define a java class . The class must have a no-argument constructor , should have a accessor and mutator methods and should be serializable by implementing an interface called "Serializable" . Accessor methods are also called as getters and Mutators methods are called as setters. The property of the JavaBean should be accessed , modified by these setters and getters.

Let us look into an simple example :

package com.hubberspot.javabeans.example;

import java.io.*;

public class SimpleJavaBean implements Serializable
{
  protected int value;
  
  public SimpleJavaBean()
  {
    value = 0;
  }

  public void setValue(int newValue)
  {
    value = newValue;
  }

  public int getValue()
  {
    return value;
  }
}  

In the above example, the bean has one property called value. The accessor method is getValue() and the mutator method is setValue().

Compiling the Bean

The bean class should be compiled as a regular java file using javac compiler.
 
© 2021 Learn Java by Examples Template by Hubberspot