How to use Pythagoras Theorem to calculate hypotenuse of a right-angled triangle in Java ?.

Program to demonstrate how to use Pythagoras Theorem to calculate hypotenuse of a right-angled triangle in Java

 

package com.hubberspot.code;

import java.util.Scanner;


public class PythagorasTheoremCode {

 public static void main(String[] args) {

  // In order to apply Pythagoras theorem
  // we have to apply for the formula as
  // hypotenuse * hypotenuse = height * height + base * base

  // Create a Scanner object which takes System.in object
  // this makes us read values from the console
  // We will ask user to input values for the height and base
  Scanner scanner = new Scanner(System.in);

  // Prompting user to enter height ... 
  System.out.println("Enter the height of right-angled triangle : ");
  double height = 0;
  // Scanner objects nextDouble reads output from the console
  // entered by user and stores into the double variable
  height = scanner.nextDouble();  

  // Prompting user to enter base ... 
  System.out.println("Enter the base of right-angled triangle : ");
  double base = 0;
  base = scanner.nextDouble();

  System.out.println("Applying Pythagoras Theorem  ... ");

  System.out.println();

  // Math.sqrt method calculates the square root of the argument
  // passed to it
  // Math.pow method takes two arguments and 
  // returns the value of the first argument 
  // raised to the power of the second argument.

  double hypotenuse = Math.sqrt(Math.pow(height, 2) + Math.pow(base, 2));
  System.out.println("Hypotenuse of right-angled triangle : " + hypotenuse);



 }

}



Output of the program : 


 

How to use @Qualifier annotation in Spring Framework in making bean qualify to auto-wire from multiple beans ?.

Program to demonstrate how to use @Qualifier annotation in Spring Framework in making bean qualify from multiple beans

When it comes to Auto-wiring there can arise a case when there are two or more beans which qualifies to be autowired to a property. In such a scenario, Spring cannot decide that which bean it needs to autowire to. If it fails in deciding, it throws a exception as "org.springframework.beans.factory.NoSuchBeanDefinitionException". See the problem scenario code below :

1. A normal POJO class Side.java having three properties length, pointX and pointY

package com.hubberspot.spring.qualifier;

public class Side {

 private int length;
 private int pointX;
 private int pointY;


 public int getLength() {
  return length;
 }

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

 public int getPointX() {
  return pointX;
 }

 public void setPointX(int pointX) {
  this.pointX = pointX;
 }


 public int getPointY() {
  return pointY;
 }

 public void setPointY(int pointY) {
  this.pointY = pointY;
 }

}




2. A normal POJO class Triangle.java having Side as property which is auto-wired using @Autowired annotation

package com.hubberspot.spring.qualifier;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class Triangle {

 private Side side;


 public Side getSide() {
  return side;
 }

 @Autowired 
 public void setSide(Side side) {
  this.side = side;
 }

}




3. Spring Configuration XML file having bean declaration for one Triangle class and Two Side class


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"?>
<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.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <!-- In order to turn on Annotations in Spring over xml configuration we 
        need to provide a tag by name <context:annotation-config> see the tag below 
        .... -->

    <context:annotation-config />

    <bean id="triangle" class="com.hubberspot.spring.qualifier.Triangle">

    </bean>

    <bean id="side1" class="com.hubberspot.spring.qualifier.Side">
        <property name="length" value="5"></property>
        <property name="pointX" value="2"></property>
        <property name="pointY" value="3"></property>
    </bean>

    <bean id="side2" class="com.hubberspot.spring.qualifier.Side">
        <property name="length" value="7"></property>
        <property name="pointX" value="5"></property>
        <property name="pointY" value="2"></property>
    </bean>


</beans>



4. Test class for running the program

package com.hubberspot.spring.autowire;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.hubberspot.spring.qualifier.Triangle;

public class Test {

 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 Triangle object. Without implementing new keyword we 
  // have injected object of Triangle just by reading an xml 
  // configuration file.
  Triangle triangle = (Triangle)context.getBean("triangle");

  System.out.println("The length of Triangle is : " + triangle.getSide().getLength());
  System.out.println("The x co-ordinate of Triangle is : " + triangle.getSide().getPointX());
  System.out.println("The y co-ordinate of Triangle is : " + triangle.getSide().getPointY());

 }

}



Note : When we run the Test class we get an exception trace which is shown below in the image.



Exception Occured on running Test Class :





Now, where is the problem with above code ?.

The problem lies in the Spring Configuration file where there are two beans of class Side. When Spring container finds that Triangle is been Auto-wired to Side class , it checks for Spring Configuration file to fulfill dependency. Here when Spring container scans XML file finds two beans with different id say "side1" and "side2" but of same type Side. It cannot decide which is the right bean developer is looking for. In order to overcome this problem we use @Qualifier annotation, which has value attribute where we set the id for which we need the bean auto-wiring. See the Triangle modified and right code below :


Right Scenario - Providing @Qualifier Annotation in Triangle Class


package com.hubberspot.spring.qualifier;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

public class Triangle {

 private Side side;


 public Side getSide() {
  return side;
 }

 @Autowired
 @Qualifier("side1")
 public void setSide(Side side) {
  this.side = side;
 }

}




Output of the program after providing @Qualifier Annotation : 

 

How to turn on Auto Scanning of Spring Components for automatic scanning, detecting and instantiating the beans ?.

Program to demonstrate how to turn on Auto Scanning of Spring Components for automatic scanning, detecting and instantiating the beans

Spring Framework container uses Spring Configuration XML file for scanning , detecting and instantiating of beans / components. Spring Framework now provides us a way to automate this whole process of dealing with beans. Instead of dealing with beans and components manually, now we can ask Spring container to scan into a particular package and see if there are any classes with specific annotations for getting registered as a bean. By-default Auto Scanning of beans is turned off.

In order to turn on Auto Scanning we need to provide an entry in Spring Configuration file. The entry is just a tag with name "context:component-scan". As soon as we provide Spring this tag, it gets capabilities of automatically discovering and declaring beans.

This tag is very much similar to the tag "context:annotation-config". The only difference between the two is that "context:annotation-config" does not scans the beans in package.

Tag "context:component-scan" scans package and all its sub-packages for classes having specific annotations such as @Component , @Service etc to register that class as a Spring bean. This tag comes up with a attribute called as base-package, which tells the container from where it has to start scanning.

There are usually four major annotations for which the "context:component-scan" tag scans :

1. @Component - This annotation tells "context:component-scan" tag that its a class which can be treated as Spring Component.

2. @Service - This annotation tells "context:component-scan" tag that its a class which can be treated as Service.

3. @Repository - This annotation tells "context:component-scan" tag that its a class which can be treated as data repository.

4. @Controller - This annotation tells "context:component-scan" tag that its a class which can be treated as Controller for Spring Model-View-Controller.

How to provide entry for "context:component-scan" tag in Spring Configuration File ?


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.

<?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.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <!-- In order to turn on Auto Scanning in Spring we need to provide a tag 
        by name <context:component-scan> see the tag below .... -->

    <context:component-scan base-package="com.hubberspot.spring.components" />

</beans>


Above XML contains an entry for "context:component-scan" which makes Spring container detect, scan and instantiate bean automatically. By above example, the container looks in the package com.hubberspot.components and all its sub-packages for the classes having specific components declared above.

How to calculate Trigonometric functions values in Java ?

Program to demonstrate how to calculate Trigonometric functions values in Java

package com.hubberspot.code;

import java.util.Scanner;

public class TrignometricFunctionsDemo {

 public static void main(String[] args) {

  // Create a Scanner object which will read 
  // values from the console which user enters
  Scanner scanner = new Scanner(System.in);

  // Getting input from user from the console
  System.out.println("Enter value of angle in degrees ");

  // Calling nextDouble method of scanner for
  // taking a double value from user and storing
  // it in degrees variable
  double degrees = scanner.nextDouble();

  System.out.println("Lets calculate the sine, cosine and tan of angle ...");
  // In order to calculate sine , cosine and tan of angle we
  // use the Math class three static methods by name as :  
  // 1. Math.sin(a) -- Sine of a
  // 2. Math.cos(a) -- Cosine of a 
  // 3. Math.tan(a) -- Tangent of a

  double sineOfAngle = Math.sin(degrees); 
  double cosOfAngle = Math.cos(degrees); 
  double tanOfAngle = Math.tan(degrees);

  System.out.println();
  System.out.println("The Sine of " + degrees + " degrees is : "
    + sineOfAngle);
  System.out.println("The Cosine of " + degrees + " degrees is : "
    + cosOfAngle);
  System.out.println("The Tangent of " + degrees + " degrees is : "
    + tanOfAngle);

  System.out.println();
  System.out.println("Lets calculate the sec, cosec and cot of angle ...");
  // In order to calculate sec, cosec and cot of angle we
  // just inverse the value of sin , cos and tan calculated above :   
  // 4. Sec of a -- 1 / Sine of a
  // 5. Cosec of a  -- 1/ Cosine of a 
  // 6. Cot of a  -- 1 / Tangent of a

  double secOfAngle = 1 / Math.sin(degrees); 
  double cosecOfAngle = 1 / Math.cos(degrees); 
  double cotOfAngle = 1 / Math.tan(degrees);

  System.out.println("\nThe Sec of " + degrees + " degrees is : "
    + secOfAngle);
  System.out.println("The Cosec of " + degrees + " degrees is : "
    + cosecOfAngle);
  System.out.println("The Cotangent of " + degrees + " degrees is : "
    + cotOfAngle);


 }

}



Output of the program :


How to forward a request to a JSP using RequestDispatcher ?.

Program to demonstrate working of RequestDispatcher in a servlet for forwarding the request to the correct JSP


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 Fan Club</h1>
 <p>
  In order to join our fan club, enter you name and email address
  below </br> and Click Submit button.
 </p>

 <form action="CustomerInfoDispatcher" method="post">
  <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>


CustomerInfoDispatcher.java

package com.hubberspot.jsp.servlets.examples;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hubberspot.model.Customer;
import com.hubberspot.utility.CustomerService;

@WebServlet("/CustomerInfoDispatcher")
public class CustomerInfoDispatcher extends HttpServlet {



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


    protected void doPost(
  HttpServletRequest request,
  HttpServletResponse response
  ) throws ServletException, IOException {
 // Get the form requests 
 String firstName = request.getParameter("firstName");
 String lastName = request.getParameter("lastName");
 String emailAddress = request.getParameter("emailAddress");
  
 // Using DataModel in a Servlet
 Customer customer = new Customer(firstName, lastName, emailAddress);
  
 // storing the Customer object in the request object
 request.setAttribute("Customer", customer);

 String url = "/customer_info.jsp";
 // forwarding request and response object to a JSP page 
 // Using RequestDispatcher Object
 RequestDispatcher dispatcher = 
   getServletContext().getRequestDispatcher(url);
 dispatcher.forward(request, response);

   }

}




customer_info.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.

<%@ 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>Insert title here</title>
</head>
<body>

<%@ page import="com.hubberspot.model.Customer" %>

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

<% Customer customer = (Customer)request.getAttribute("Customer"); 
%>

 <table cellspacing="0" cellpadding="5" border="1">
  <tr>
   <td align="right">First Name :</td>
   <%-- Below is the JSP expression used to display string value of an expression --%>
   <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>


Customer.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;
 }
}




Output of the program :


subscribe.html




























customer_info.jsp



How to turn on Annotations in Spring Configuration file ?

A simple snippet showing how to turn on Annotations in Spring Configuration file

Annotations came into picture with JDK 1.5 to make life of a developer easier. Annotations are meta-data which provides additional information about something. It is applied to various variables , methods , classes , constructors and other declarations. Spring provides annotations as an alternative way over xml based configuration.

Annotations are turned off by-default by Spring Framework. In order to turn it on we have to provide a entry in Spring Configuration file. Using tag context:annotation-config from Spring's context namespace makes it turn on. Annotation makes development easier and faster. It also takes addition of information closer to source code. Annotation injection is done prior to xml based injection by Spring Framework.


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"?>
<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.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <!-- In order to turn on Annotations in Spring over xml configuration we 
        need to provide a tag by name <context:annotation-config /> see the tag below 
        .... -->

    <context:annotation-config />

    <bean id="employee" class="com.hubberspot.spring.autowire.Employee"
        
        
        <property name="name" value="Jonty" />
        <property name="age" value="28" />
        <property name="address" ref="address"></property>
    </bean>

    <bean id="address" class="com.hubberspot.spring.autowire.Address">

        <property name="street" value="Town Hall Street" />
        <property name="city" value="Pune" />
        <property name="state" value="Maharashtra"></property>
    </bean>

</beans>


After the annotations in Spring file is turned on, Spring automatically wires many components such as properties , constructors and various stuff to a value.

How to convert degrees into radians and radians into degress using Math class in Java ?.

Program to demonstrate how to convert degrees into radians and radians into degress using Math class in Java

package com.hubberspot.code;

import java.util.Scanner;


public class RadiansDegreesConversion {

 public static void main(String[] args) {

  // Create a Scanner object which will read 
  // values from the console which user enters
  Scanner scanner = new Scanner(System.in);

  // Getting input from user from the console
  System.out.println("Enter value of angle in degrees ");

  // Calling nextDouble method of scanner for
  // taking a double value from user and storing
  // it in degrees variable
  double degrees = scanner.nextDouble();

  System.out.println("Calculating conversion of degrees to radians ... ");

  // In order to calculate conversion of degrees to radians 
  // we use Math class toRadians() static method which takes
  // in a degree and returns back the converted value to radians
  double result = Math.toRadians(degrees);

  // printing the result on the console
  System.out.println("Conversion of " + degrees + " degrees to radians : "
    + result); 


  System.out.println();

  // Getting input from user from the console
  System.out.println("Enter value of angle in radians ");

  // Calling nextDouble method of scanner for
  // taking a double value from user and storing
  // it in radians variable
  double radians = scanner.nextDouble();

  System.out.println("Calculating conversion of radians to degrees ... ");

  // In order to calculate conversion of radians to degrees 
  // we use Math class toDegrees() static method which takes
  // in a radian and returns back the converted value to degrees
  result = Math.toDegrees(radians);

  // printing the result on the console
  System.out.println("Conversion of " + radians + " radians to degrees : "
    + result); 



 }

}



Output of the program :



How to calculate Square root and Cube root of a number in Java using Math class ?.

Program to demonstrate how to calculate Square root and Cube root of a number in Java using Math class




Click here to download complete source code 
 
package com.hubberspot.code;

import java.util.Scanner;

public class SquareAndCubeRootdemo {

 public static void main(String[] args) {

  // Create a Scanner object which will read 
  // values from the console which user enters
  Scanner scanner = new Scanner(System.in);

  // Getting input from user from the console
  System.out.println("Enter value of number for which you want Square root ");

  // Calling nextDouble method of scanner for
  // taking a double value from user and storing
  // it in number variable
  double number = scanner.nextDouble();

  System.out.println();


  System.out.println("Calculating Square root of a number ... ");

  // In order to calculate Square root of a number 
  // we use Math class Math.sqrt() static method which takes in a 
  // number and returns back the square root of that number
  double result = Math.sqrt(number);

  // printing the result on the console
  System.out.println("Square root of " + number + " is : " + result); 

  System.out.println();

  // Getting input from user from the console
  System.out.println("Enter value of number for which you want Cube root ");

  // Calling nextDouble method of scanner for
  // taking a double value from user and storing
  // it in number variable
  number = scanner.nextDouble();

  System.out.println();


  System.out.println("Calculating Cube root of a number ... ");

  // In order to calculate Cube root of a number 
  // we use Math class Math.cbrt() static method which takes in a 
  // number and returns back the square root of that number
  result = Math.cbrt(number);

  // printing the result on the console
  System.out.println("Cube root of " + number + " is : " + result); 



 }

}


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 use InitializingBean and DisposableBean interface for initializing and destroying a bean in Spring Framework ?.

Program to demonstrate how to use InitializingBean and DisposableBean interface for initializing and destroying a bean in Spring Framework

Step 1 - Create a POJO class here its Employee.java having getters, setters, constructor and implementing two interfaces InitializingBean and DisposableBean, along with its unimplemented methods as afterPropertiesSet() and destroy()

package com.hubberspot.spring.InitDestroy;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

// Create a POJO class Employee which implements
// two interfaces by name InitializingBean and DisposableBean
// these interfaces has two methods as : afterPropertiesSet() and 
// destroy(). 
public class Employee implements InitializingBean, DisposableBean{

 private String name;
 private int age;

 public Employee() {

 }

 public String getName() {
  return name;
 }

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

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 // This method is called to provide some initialization to 
 // bean by Spring Framework container
 @Override
 public void afterPropertiesSet() throws Exception {  
  System.out.println("Initializing the Employee bean ...");  
 }

 // This method is called to destroy a bean  
 // by Spring Framework container
 @Override
 public void destroy() throws Exception {
  System.out.println("Destroying the Employee bean ...");
 }

}



Step 2 - Create a Spring Configuration file having beans


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.

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


 <bean id="employee" class="com.hubberspot.spring.InitDestroy.Employee">

  <property name="name" value="Jonty" />
  <property name="age" value="28" />

 </bean>
</beans>


Step 3 - Create a test class here its Test.java having AbstractApplicationContext class for providing registerShutdownHook method to execute destroy method.

package com.hubberspot.spring.InitDestroy;

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

public class Test {

 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. 
  AbstractApplicationContext context = 
    new ClassPathXmlApplicationContext(("spring.xml"));

  // Using AbstractApplicationContext registerShutdownHook()
  // method to demonstrate destroy() method being called
  context.registerShutdownHook();

  // 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 Employee object. Without implementing new keyword we 
  // have injected object of Employee just by reading an xml 
  // configuration file.
  Employee employee = (Employee)context.getBean("employee");

  System.out.println("The name of Employee is : " + employee.getName());
  System.out.println("The age of Employee is : " + employee.getAge());

 }

}



Output of the program :



How to display request parameters in a JSP coming in a request ?.

Program to demonstrate how to display request parameters in a JSP coming in a request

request.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.
63.
64.
65.
66.
67.
68.

<%@ 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>User Information</title>
</head>
<body>

    <form action="entry.jsp" method="get">
        <table cellspacing="0" cellpadding="5" border="1">
            <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 align="right">Gender :</td>
                <td><input type="checkbox" name="male" value="Male" checked>Male</td>

            </tr>
            <tr>
                <td align="right"></td>
                <td><input type="checkbox" name="female" value="Female">Female</td>
            </tr>

            <tr>
                <td align="right">Favorite Hobbies :</td>
                <td><input type="radio" name="hobby" value="TV">TV</td>
            </tr>

            <tr>
                <td align="right"></td>
                <td><input type="radio" name="hobby" value="MOVIES">MOVIES</td>
            </tr>

            </tr>

            <tr>
                <td align="right">Select a country ...</td>
                <td><select name="country" multiple>
                        <option value="USA" selected>United States
                        <option value="CANADA">Canada
                        <option value="INDIA">India
                </select></td>
            </tr>

            <tr>
                <td></td>
                <td align="left"></br> <input type="submit" value="Submit"></td>
            </tr>

        </table>
    </form>

</body>
</html>


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.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.

<%@ 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>User Information</title>
</head>
<body>

    <h2>
        Hello Friends !!! ....<br> Below are the important methods of
        request<br> object for the coming parameters ...
    </h2>

    <hr>

    <h2>1. request.getParameter(String param)</h2>
    <h3>
        String firstName = request.getParameter("firstname"); : <br>
        returns the value of html/jsp element submitted in the form <br>
        having name attribute as firstname
    </h3>
    <%
        String firstName = request.getParameter("firstName");
    %>
    <h5>
        First Name :
        <%=firstName%>
    </h5>
    </h3>
    <hr>
    <h2>2. request.getParameterValues(String param)</h2>
    <h3>
        String[ ] countries = request.getParameterValues("country"); : <br>
        returns an array of string values of html/jsp element submitted in the
        form <br> having name attribute as country
    </h3>
    <%
        String[] countries = request.getParameterValues("country");
        for(int i = 0; i < countries.length; i++) {
    %>
    <h5>
        Country :
        <%=i + 1%>
        <%=countries[i]%></h5>

    <%
        }
    %>

    <hr>
    <h2>3. request.getParameterNames()</h2>
    <h3>
        Enumeration countries = request.getParameterNames()); : <br>
        returns an Enumeration of parameter names of html/jsp element
        submitted <br>in the form having name attribute as country
    </h3>
    <%
        java.util.Enumeration params = request.getParameterNames());
        while(params.hasMoreElements())) {
            String paramName = (String) params.nextElement();
            String paramValue = request.getParameter(paramName);
    %>

    <h5><%=paramName%>
        has a value
        <%=paramValue%></h5>

    <%
        }
    %>
    <hr>

</body>
</html>

Output on the browser window :


request.jsp






























entry.jsp


Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot