How life cycle of a thread in works in Java ?.

Introduction to life cycle of a simple thread in Java :-





Life cycle of a thread in Java has many important states. These states defines the functionality and working of Java threads. There are normally five states through which a thread can go from birth to death. The states are as follows :-

  1. New :-  Whenever we instantiate an object of class Thread, we create a new thread which goes to new state. It is the state which signifies that a new thread is created but its not ready to run. 
  2. Runnable :- After creation of thread when we call Thread's start method, it changes state of a thread from new to runnable. This transition does not make thread to run but it makes a thread eligible to run. After reaching this state thread gets a call from Java Thread Scheduler to run. Thread Scheduler selects one of the runnable thread after processor becomes available to it. 
  3. Blocked :- Generally , threads can move to blocked state due to various reasons, some of the reasons are waiting for I/O operation , waiting for any network connections etc. Usually a thread gets back to its runnable state when it finishes its operation which has blocked it. A blocked thread can't be run by thread scheduler , it has to get back to runnable state to run. 
  4. Waiting :- A thread can enter to a waiting state by calling wait method over it. It can go to runnable state whenever another thread calls notify or notifyAll method to send notification to it for getting back to runnable state. 
  5. Terminate :- A thread terminates when run method completely executes itself. Once a thread terminates it never gets back to its runnable state.

Life cycle diagram of a thread in Java :- 



 

Creating a simple Chat Client/Server Solution in Java

Program to create a simple Chat Client/Server Solution in Java

1. Implementing a Chat Server

package com.hubberspot.examples;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

   private ServerSocket server;
   private int port = 5600;

   public Server() {
      try {
	server = new ServerSocket(port);
      } catch (IOException e) {
	   e.printStackTrace();
	}
   }

   public static void main(String[] args) {
	Server server = new Server();
	server.connection();
   }

   public void connection() {
	System.out.println("Waiting for client ...");
	try
	{
           Socket socket = server.accept();
	   System.out.println("Client accepted: " + socket);

	   DataInputStream dis = new DataInputStream(
		new BufferedInputStream(socket.getInputStream()));

	   boolean done = false;
	   while (!done)
	   {  
		try
		{  
	           String line = dis.readUTF();
		   System.out.println(line);
		   done = line.equals("bye");
		}
		catch(IOException ioe)
		{  
		   done = true;
		}
           }
	 	dis.close();				
		socket.close();
	   }
	   catch(IOException ioe)
	   {  
		System.out.println(ioe); 
	   }

    }
}



2. Implementing a Chat Client

package com.hubberspot.examples;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
   public static void main(String[] args) {
      try {
	//
	// Create a connection to the server socket on the server application
	//
	
        InetAddress host = InetAddress.getLocalHost();
	Socket socket = new Socket(host.getHostName(), 5600);

	//
	// Send a message to the client application
	//
	DataOutputStream dos = new DataOutputStream(
            socket.getOutputStream());
	
        DataInputStream dis = new DataInputStream(System.in);

	String line = "";
	while (!line.equals("bye"))
	{  
	   try
	   {  
		line = dis.readLine();
	        dos.writeUTF(line);
		dos.flush();
	   }
	   catch(IOException ioe)
	   {  
		System.out.println("Sending error: " + ioe.getMessage());
				}
	   }
	   
           dis.close();
	   dos.close();
	} catch (UnknownHostException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
   }
}



Output of the program : Client Screen

















Output of the program : Server Screen 



How to redirect responses to a different JSP or Servlets ?.

Program to demonstrate how to redirect responses to a different JSP or Servlets


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

<%@ 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>

<h2>How to redirect responses to a different JSP and Servlets ?</h2>
 <p>
  In order to redirect responses to a different JSP or Servlets </br>
  see demo example below : 
 </p>

 <form action="customer_info_display.jsp" 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>


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

<%@ 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"%>

 <%
  // Get the form requests 
  String firstName = request.getParameter("firstName");
  String lastName = request.getParameter("lastName");
  String emailAddress = request.getParameter("emailAddress");
  
  Customer customer = new Customer(firstName , lastName , emailAddress);
  
 %>



 <%
 // If first name entered other than Jonty
 // you will be redirected to invalid.jsp
 if(firstName.equalsIgnoreCase("Jonty"))
 {
 
 %>

 <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>
 <%
    }
 else {
    response.sendRedirect("invalid.jsp"); 
 }
 
 %>

</body>
</html>


invalid.jsp


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.

<%@ 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>

<h2> 
<p>
Sorry User ... You have entered wrong first name !!! ... <br>
Go back and type first name as : Jonty
</p>
</h2>

</body>
</html>



attributes_demo.jsp





invalid.jsp



customer_info_display.jsp


















How to set and get an attribute to/from request object in JSP and Servlets ?

Program to demonstrate how to set and get an attribute to/from request object in JSP and Servlets ?

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

<%@ 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>

<h1>Request set and get attribute demo</h1>
 <p>
  In order to set and get attributes in a request object </br>
  see demo below with a example : 
 </p>

 <form action="customer_info_display.jsp" 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>



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.

<%@ 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"%>

 <%
  // Get the form requests 
  String firstName = request.getParameter("firstName");
  String lastName = request.getParameter("lastName");
  String emailAddress = request.getParameter("emailAddress");
  
  Customer customer = new Customer(firstName , lastName , emailAddress);
  
  // 1. To set attribute in a request object 
  request.setAttribute("Customer", customer);
 %>
 
 <%
    // 2. To get the attribute set above in a different refernce
    Customer newCustomer = (Customer) request.getAttribute("Customer");
 
 %>
 
 <p>The customer created above at 1 is populated in 2 as : </p>
 
 <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><%=newCustomer.getFirstName()%></td>
  </tr>

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

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

</body>
</html>



Output of the program :


attributes_demo.jsp



























customer_info.jsp

 




Program demonstrating Switch statement working in Java

Program to demonstrate working of Switch statements in Java



package com.hubberspot.examples;

import java.util.Scanner;

public class SwitchTest {

 
    public static void main(String[] args) {
      
     Scanner scanner = new Scanner(System.in);
      
        System.out.println("This seasons IPL Teams : ");
 System.out.println("***********************************");         
        System.out.println("1. Deccan Chargers");
        System.out.println("2. Kolkata Night Riders");
        System.out.println("3. Mumbai Indians");
        System.out.println("4. Chennai Super Kings");
        System.out.println("5. Rajasthan Royals");
        System.out.println("6. Royal Challengers Bangalore");
        System.out.println("7. Kings XI Punjab");
        System.out.println("8. Pune Warriors India");
        System.out.println("9. Delhi Daredevils");
        System.out.print("");
        System.out.println("***********************************");
        System.out.print("Please choose your favorite IPL team: ");
  
        int team = scanner.nextInt();    
  
        System.out.print("So you like: ");
         
        switch (team) {
            case 1:
                System.out.println("Deccan Chargers"); 
                break;
            case 2:
                System.out.println("Kolkata Night Riders"); 
                break;
            case 3:
                System.out.println("Mumbai Indians"); 
                break;
            case 4:
                System.out.println("Chennai Super Kings"); 
                break;
            case 5:
                System.out.println("Rajasthan Royals"); 
                break;
            case 6:
                System.out.println("Royal Challengers Bangalore"); 
                break;
            case 7:
                System.out.println("Kings XI Punjab"); 
                break;
            case 8:
                System.out.println("Pune Warriors India"); 
                break;
            case 9:
             System.out.println("Delhi Daredevils"); 
             break;                 
            default:
                System.out.println("Invalid IPL team choosen");
        }
    }
}





Output of the program :



How to use various types of JSP tags in a JSP page ?

Program to demonstrate usage of various JSP tags in a JSP page

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.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.

<%@ 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>

<h2>The five types of JSP tags are as follows : </h2>

 <table cellspacing="0" cellpadding="5" border="1">
  <tr>   
   <th>Tag Name</th>
   <th>Tag Symbol</th>
   <th>Tag Usage</th>
  </tr>

  <tr>
   <td>JSP comment</td>
   <td>&lt;%-- --%&gt;</td>
   <td>JSP engine ignores code between this tag</td>
  </tr>

  <tr>
   <td>JSP directive</td>
   <td>&lt;%@ %&gt;</td>
   <td>JSP engine uses it as metadata for entire JSP page</td>
  </tr>
  
  <tr>
   <td>JSP expression</td>
   <td>&lt;%= %&gt;</td>
   <td>JSP engine uses it for displaying string value of evaluated expression</td>
  </tr>
  
  <tr>
   <td>JSP declaration</td>
   <td>&lt;%! %&gt;</td>
   <td>JSP engine uses it as for declaring instance variables and methods</td>
  </tr>
  
  <tr>
   <td>JSP scriptlet</td>
   <td>&lt;% %&gt;</td>
   <td>JSP engine uses it to insert block of Java statements</td>
  </tr>
 </table>
 
 
 <%-- This is comment tag , generally ignored by JSP engine --%>

 <%-- Below is the directive tag , used as a meta-data for entire JSP--%>
 <%@ page import="com.hubberspot.model.Customer"%>
 <%@ page import="java.io.*"%>



 <%-- Below is the JSP declaration tag used to declare methods and instance variables --%>
 <%!
       int counter = 0;
 
    public 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+"n" );
    out.println("Last Name : "+ lastName+"n" );
    out.println("Email Address : "+ emailAddress+"n" );
    out.close();
   } catch (IOException e) {   
    e.printStackTrace();
   }
   

  }  
   %>

 <%-- Below tag is the JSP Scriptlet tag which is used for inserting block
of java statements  --%>
 <%
  // 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("/WEB-INF/subscription.txt");

  // Using DataModel in a JSP
  Customer customer = new Customer(firstName, lastName, emailAddress);

  // Using the this to write info to file
  this.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>
   <%-- 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>



Output of the program :


1. subscribe.html


























 2. email_entry.jsp






 3. subscription.txt

 

How to get real path for a file in JSP and Servlet ?.

Program to demonstrate how to get real path for a file in JSP and Servlet


package com.hubberspot.jsp.servlets.examples;

import java.io.IOException;
import java.io.PrintWriter;

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

@WebServlet("/RealPathInfoServlet")
public class RealPathInfoServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
      
   
 protected void doGet(
   HttpServletRequest request, 
   HttpServletResponse response
   ) throws ServletException, IOException {
  doPost(request, response);
 }

 protected void doPost(
   HttpServletRequest request, 
   HttpServletResponse response
   ) throws ServletException, IOException {
  
  PrintWriter out = response.getWriter();
  ServletContext context = request.getServletContext();
  String realpath = context.getRealPath("/WEB-INF/web.xml");
  out.println("<html>");
  out.println("<body>");
  out.println("<h2>");
  out.println("The Real Path for the file web.xml");
  out.println("i.e. <br> the deployment descriptor is <br>");
  out.println("<h4>"+realpath+"</h4>");
  
  out.println("</h2>");
  out.println("</html>");
  out.println("</body>");
 }

}





Output of the program :



How to convert a Xml to Java Object using JAXB API and Annotations through a Java program?.

Program to demonstrate conversion of a Xml to Java Object using JAXB API and Annotations through a Java program

Steps to convert Xml to Object :

1. Creating a POJO class :

package com.hubberspot.examples;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {
 
 private Integer id;
 private String firstName; 
 private String lastName;
 private String email;
 
 public Customer(){
  
 }

 public Integer getId() {
  return id;
 }
 @XmlAttribute
 public void setId(Integer id) {
  this.id = id;
 }

 @XmlElement
 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 @XmlElement
 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 @XmlElement
 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 } 
}




2. Create a conversion class :

package com.hubberspot.examples;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class JAXBXmlToObject {
 
   public static void main(String[] args) {
  
      try {
 JAXBContext context = JAXBContext.newInstance(Customer.class);
   
 Unmarshaller unmarshaller = context.createUnmarshaller();
   
 Customer customer = (Customer) unmarshaller.unmarshal(
    new File("Customer.xml"));
   
 System.out.println("Customer Id : " 
                     + customer.getId());
   
 System.out.println("Customer FirstName : " 
                     + customer.getFirstName());
  
 System.out.println("Customer LastName : " 
                     + customer.getLastName());
   
 System.out.println("Customer Email : " 
                     + customer.getEmail());
   
       } 
       catch (JAXBException e) {
   
      e.printStackTrace();
  
       }

  }

}



3. Input of the program - XML file as "Customer.xml"

























4. Output of the program :




How to convert a Java Object to Xml using JAXB API and Annotations through a Java program?.

Program to demonstrate conversion of a Java Object to Xml using JAXB API and Annotations through a Java program

Steps to convert Object to Xml :

1. Creating a POJO class :

package com.hubberspot.examples;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {
 
 private Integer id;
 private String firstName; 
 private String lastName;
 private String email;
 
 public Customer(){
  
 }

 public Integer getId() {
  return id;
 }
 @XmlAttribute
 public void setId(Integer id) {
  this.id = id;
 }

 @XmlElement
 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 @XmlElement
 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 @XmlElement
 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 } 
}




2. Create a conversion class :

package com.hubberspot.examples;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
 
public class JAXBObjectToXml {
  public static void main(String[] args) throws IOException {

     Customer customer = new Customer();
     customer.setId(1);
     customer.setFirstName("Jonty");
     customer.setLastName("Magicman");
     customer.setEmail("jontymagicman@hubberspot.com");
 
     try {
       JAXBContext context = JAXBContext.newInstance(Customer.class);
 
       Marshaller marshaller = context.createMarshaller();
       marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
       marshaller.marshal(customer, 
        new BufferedWriter(new FileWriter("Customer.xml")));
     } catch (JAXBException e) {
         e.printStackTrace();
       }
    }
}


3. Output of the program - XML file created as "Customer.xml"




Using Reflection API to determine whether class object is an Annotation or not

Program to demonstrate how Reflection API can be used to determine whether a class object is an Annotation or not in Java

package com.hubberspot.reflection;

@interface Specifier {

}

class Public {

}

public class AnnotationInfo {

   public static void main(String[] args) {
   // Create a Test object
      Public publicInstance = new Public();
        
      // Get the class of respective types
      Class publicClass = publicInstance.getClass();
      Class specifier = Specifier.class;

      // isAnnotation() checks whether type is an annotation or not
      if(specifier.isAnnotation()) {
 // prints the simple name of the class
        System.out.println("Given type " + specifier.getSimpleName()
   + " is an Annotation");
      } else {
 System.out.println("Given class " + specifier.getSimpleName()
   + " is not an Annotation");
      }

      if(publicClass.isAnnotation()) {
 System.out.println("Given class " + publicClass.getSimpleName()
   + " is an Annotation");
      } else {
 System.out.println("Given class " + publicClass.getSimpleName()
   + " is not an Annotation");
      }


   }

}




Output of the program : 


A Simple HTML and JSP Email Subscription List Application

A Simple HTML and JSP Email Subscription List Application

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.

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

<%@ 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>
 <%
  // Get the form requests 
  String firstName = request.getParameterundefined"firstName");
  String lastName = request.getParameterundefined"lastName");
  String emailAddress = request.getParameterundefined"emailAddress");
 %>

 <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><%=firstName%></td>
  </tr>

  <tr>
   <td align="right">Last Name :</td>
   <td><%=lastName%></td>
  </tr>

  <tr>
   <td align="right">Email Address :</td>
   <td><%=emailAddress%></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>


Output of the program on browser window :

subscribe.html

























email_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