Saturday, June 18, 2011

Implementing Bean with scriptlet in JSP





Example for implementing bean with scriptlet <% code %> in a JSP page:
     We can use all of the JSP coding while using Java Beans in a JSP page. There are three main kinds of JSP scripting elements in JSP.
<%= expression %> is called Expression to evaluate value in output
<%  somecode  %> is called Scriptlet that are inserted into serlet's "service" method
<%! declaration %> is called JSP Declaration for declaring objects of components.


JSP Scriptlets
     If you want to do some coding of multiple lines or of single lines rather than inserting a single expression then you can use JSP scriptlets in the following way :
<% Java Code %>


      For example if you have to use "if-else" in your JSP page you can use it like this:
<%
   if(condition) {
  some statements..
  }
   else{
   some statements..
  }
%>


In this way, JSP scriptlet lets you do java coding in a JSP page wherever you want. Following example will describe you to use JSP Scriptlet in a JSP page using Java Beans. In our example we have made a bean file which is making the database connection in its constructor and after getting connection according to getter and setter method it will insert values into database by insert() method of this bean. For inserting data into bean file we are using MySQL database and connecting to the database "messagepaging" and table is "message" and structure of this database table is given as below:


CREATE TABLE `message` (
`id` int(11) NOT NULL auto_increment,
`message` varchar(256) default NULL,
PRIMARY KEY (`id`)
)
  •  Bean file code for this example bean is given as below:
bean.java
package myexample;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
public class bean

  private int msgid;
  private String message;
  private Connection connection=null;
  private ResultSet rs = null;
  private Statement st = null;
  String connectionURL = "jdbc:mysql://192.168.10.59/messagepaging";


  public bean()
  {
 try {
  // Load the database driver
  Class.forName("com.mysql.jdbc.Driver");
  // Get a Connection to the database
  connection = DriverManager.getConnection(connectionURL, "root", "root");
 }
       catch(Exception e){
       System.out.println("Exception is ;"+e);
 }
  } 
  public void setmsgid(int msgid){
   this.msgid = msgid;
    }
  public int getmsgid(){
  return (this.msgid);
  }
   public void setmessage(String message){
  this.message = message;
   }
   public String getmessage(){
  return (this.message);
   }
   public void insert(){
      try{
  String sql = "insert into message(id,message)
   values('"+msgid+"','"+message+"')";
  Statement s = connection.createStatement();
  s.executeUpdate (sql);
  s.close ();
  }
      catch(Exception e){
      System.out.println("Exception is ;"+e);
  }
     } 
}
  • This "bean.java" file has two properties "msgid" and "message" which are having their setter and getter to set and get properties values and these properties are being set in the JSP file using following code:


<jsp:useBean id="sample" class="myexample.bean" scope="page">
   <jsp:setProperty name="sample" property="*"/>
</jsp:useBean>


  • And by using scrpitlet in JSP we are calling insert method when the form will be submit.
<% sample.insert();%>
 where "sample" is the id assigned for "bean.java" in myexample package.
  •  Full JSP code for "jspBean.jsp" is given as:


<%@ page language="Java" import="java.sql.*" %>
<html>
<head><title>Using Scriptlet to use Bean</title></head>
<body bgcolor="#ffccff">
<h1>Using JSP Scriptlet to use Bean</h1>
<form name="form1" method="POST">
  <table border="0" width="35%">
   <tr>
  <td width="10%"><b>ID</b></td>
  <td width="90%"><input type="text" name ="msgid"></td>
  </tr>
  <tr>
  <td width="10%"><b>Message</b></td>
  <td width="90%"><input type="text" name ="message"> </td>
   </tr>
  <tr>
  <td width="100%" colspan="2" align="center"><p align="left">
   <input type = "submit" value="Submit">
   </td>
  </tr>
   </table>
<jsp:useBean id="sample" class="myexample.bean" scope="page">
  <jsp:setProperty name="sample" property="*"/>
</jsp:useBean>
<!--Bean method called using JSP scriptlet -->
<% sample.insert();%>
</form>
</body>
</html>



Just the basic of Java Applet

Java Applet


-Introduction
Applet is java program that can be embedded into HTML pages. Java applets runs on the java enables web browsers such as mozila and internet explorer. Applet is designed to run remotely on the client browser, so there are some restrictions on it. Applet can't access system resources on the local computer. Applets are used to make the web site more dynamic and entertaining.


-Advantages of Applet:
•Applets are cross platform and can run on Windows, Mac OS and Linux platform
•Applets can work all the version of Java Plugin
•Applets runs in a sandbox, so the user does not need to trust the code, so it can work without security approval
•Applets are supported by most web browsers
•Applets are cached in most web browsers, so will be quick to load when returning to a web page
•User can also have full access to the machine if user allows


-Disadvantages of Java Applet:
•Java plug-in is required to run applet
•Java applet requires JVM so first time it takes significant startup time
•If applet is not already cached in the machine, it will be downloaded from internet and will take time
•Its difficult to desing and build good user interface in applets compared to HTML technology


-What Is Java Plug-in?
Java Plug-in extends the functionality of a web browser, allowing applets or Java Beans to be run under Sun's Jave 2 runtime environment (JRE) rather than the Java runtime  environment that comes with the web browser. Java Plug-in is part of Sun's JRE and is installed with it when the JRE is installed on a computer. It works with both Netscape and  Internet Explorer.
This functionality can be achieved in two different ways:
1.By using the conventional APPLET tag in a web page.
2.By replacing the APPLET tag with the OBJECT tag for Internet Explorer; by replacing the APPLET tag with the EMBED tag for Netscape 4. Note, however, that the OBJECT and EMBED tags must conform to a special format as described in the next chapter, Using OBJECT, EMBED and APPLET Tags in Java Plug-in.


-Applet versus Application:
      Applets as previously described, are the small programs while applications are larger programs. Applets don't have the main method while in an application execution starts with the main method.Applets are designed just for handling the client site problems. while the java applications are designed to work with the client as well as server. Applets are created by extending the java.applet.To create an applet just create a class that extends the java.applet.Applet class and inherit all the features available in the parent class.
import java.awt.*;
import java.applet.*;
class Myclass extends Applet {
public void init() {
/* All the variables, methods and images initialize here will be called only once because this method is called only   once when the applet is first initializes */
}
public void start() {
/* The components needed to be initialize more than once in your applet are written here or if the reader switches back and forth in the applets. This method can be called more than once.*/
}
public void stop() {
/* This method is the counterpart to start(). The code, used to stop the execution is written here*/
}
public void destroy() {
/* This method contains the code that result in to release the resources to the applet before it is finished. This method is called only once. */
}
public void paint(Graphics g) {
/* Write the code in this method to draw, write, or color things on the applet pane are */
}
}


In the above applet you have seen that there are five methods. In which two ( init() and destroy ) are called only once while remaining three (start() , stop() , and paint() ) can be called any number of times as per the requirements. The major difference between the two (applet and application) is that java applications are designed to work under the homogenous and more secure areas. On contrary to that, java applets are designed to run the heterogeneous and probably unsecured environment. Internet has imposed several restrictions on it.
Applets are not capable of reading and writing the user's file system. This means that the applet neither can access nor place anything locally. To illustrate this lets take an example.. Many Window based C applications uses the .INF file as the initialization file to store the information about the application and any user preferences in 16-bit Windows or the Registry in 32-bit Windows. While in case of current applet it is not possible. One more thing to point here is that applets are unable to use the native methods, run any program on the user system or load shared libraries. The major security concern here is  that the local shared libraries and the native methods may results in the loophole in the java security model.
Applets are not capable of  communicating the server than one from which they are originating. There are the cases in which an encryption key is used for the verification purpose for a particular applet to a server. But accessing a remote server is not possible.
The conclusion is that the java applets provides a wide variety of formats for program execution and a very tight security model on the open environment as on the Internet.


-The Life cycle of An Applet:
Applet runs in the browser and its lifecycle method are called by JVM when it is loaded and destroyed. Here are the lifecycle methods of an Applet:
init(): This method is called to initialized an applet
start(): This method is called after the initialization of the applet.
stop(): This method can be called multiple times in the life cycle of an Applet.
destroy(): This method is called only once in the life cycle of the applet when applet is destroyed.


init () method: The life cycle of an applet is begin  on that time when the applet is first loaded into the browser and called the init() method. The init() method is called only one time in the life cycle on an applet. The init() method is basically called to read the PARAM tag in the html file. The init () method retrieve the passed parameter through the PARAM tag of html file using get Parameter() method All the initialization such as initialization of variables and the objects like image, sound file are loaded in the init () method .After the initialization of the init() method user can interact  with the Applet and mostly applet contains the init() method.
Start () method: The start method of an applet is called after the initialization method init(). This method may be called multiples time when the Applet needs to be started or restarted. For Example if the user wants to return to the Applet, in this situation the start Method() of an Applet will be called by the web browser and the user will be back on the applet. In the start method user can interact within the applet.
Stop () method:  The stop() method can be called multiple times in the life cycle of applet like the start () method. Or should be called at least one time. There is only miner difference between the start() method and stop () method. For example the stop() method is called by the web browser on that time When the user leaves one applet to go another applet and the start() method is called on that time when the user wants to go back into the first program or Applet.
destroy() method: The destroy() method is called  only one time in the life cycle of Applet like init() method. This method is called only on that time when the browser needs to Shut down.
HTML provides a tag that enables the developer  to "embed" the applet within the page. This tag is known as the APPLET tag.

Going through the basics of xml



XML


- Extensible Markup Language (XML) is a data storage toolkit, a configurable vehicle for any kind of information, an evolving and open standard embraced by everyone from bankers to webmasters. On one level, XML is a protocol for containing and managing information.


-  XML is not itself a markup language: it's a set of rules for building markup languages.So what exactly is a markup language? Markup is information added to a document that enhances its meaning in certain ways, in that it identifies the parts and how they relate to each other.


- XML was designed to transport and store data.


What is XML?
- XML stands for EXtensible Markup Language
- XML is a markup language much like HTML
- XML was designed to carry data, not to display data
- XML tags are not predefined. You must define your own tags
- XML is designed to be self-descriptive


Example:
<message>
  <exclamation>Hello, world!</exclamation>
  <paragraph>XML is <emphasis>fun</emphasis> and
    <emphasis>easy</emphasis> to use.
    <graphic fileref="smiley_face.pict"/></paragraph>
</message>
This snippet includes the following markup symbols, or tags: 
• The tags <message> and </message> mark the start and end points of the whole XML fragment.
• The tags <exclamation> and </exclamation> surround the text Hello, world!.
• The tags <paragraph> and </paragraph> surround a larger region of text and tags.
• Some <emphasis> and </emphasis> tags label individual words.
• A <graphic fileref="smiley_face.pict"/> tag marks a place in the text to insert a picture.


- In XML, a document is even more general: it's the basic unit of XML information, composed of elements and other markup in an orderly package.


- One of the most promising applications of XML is as a format for application-to-application data exchange.- There are two ways for creating a language based on XML. The first is called freeform XML. In this mode,there are some minimal rules about how to form and use tags, but any tag names can be used and they can appear in any order. This is sort of like making up your own words but observing rules of punctuation. When a document satisfies the minimal rules of XML, it is said to be well-formed, and qualifies as good XML.  


- XML provides a way to describe your language in no uncertain terms. This is called document modeling, because it involves creating a specification that lays out the rules for how a document can look. In effect, it is a model against which you can compare a particular document (referred to as a document instance) to see if it truly represents your language, so you can test your document to make sure it matches your language specification. We call this test validation. If your document is found to be valid, you know it's free from mistakes such as incorrect tag spelling, improper ordering, and missing data. 


- The most common way to model documents is with a document type definition (DTD). This is a set of rules or declarations that specify which tags can be used and what they can contain. At the top of your document is a reference to the DTD, declaring your desire to have the document validated.


- The most fundamental XML processor reads XML documents and converts them into an internal representation for other programs or subroutines to use. This is called a parser, and it is an important component of every XML processing program. The parser turns a stream of characters from files into meaningful chunks of information called tokens. The tokens are either interpreted as events to drive a program, or are built into a temporary structure in memory (a tree representation) that a program can act on. 


- There are three steps for parsing an XML document. The parser reads in the XML from files on a computer (1). It translates the stream of characters into bite-sized tokens (2). Optionally, the tokens can be used to assemble in memory an abstract representation of the document, an object tree (3).


• XML Separates Data from HTML
                    If you need to display dynamic data in your HTML document, it will take a lot of work to edit the HTML each time the data changes. With XML, data can be stored in separate XML files. This way you can concentrate on using HTML for layout and display, and be sure that changes in the underlying data will not require any changes to the HTML. With a few lines of JavaScript code, you can read an external XML file and update the data content of your web page.
• XML Simplifies Data Sharing
                    In the real world, computer systems and databases contain data in incompatible formats.
• XML data is stored in plain text format.
            This provides a software- and hardware-independent way of storing data.This makes it much easier to create data that can be shared by different applications.
• XML Simplifies Data Transport
                   One of the most time-consuming challenges for developers is to exchange data between incompatible systems over the Internet. Exchanging data as XML greatly reduces this complexity, since the data can be read by different incompatible applications.
• XML Simplifies Platform Changes
                   Upgrading to new systems (hardware or software platforms), is always time consuming. Large amounts of data must be converted and incompatible data is often lost. XML data is stored in text format. This makes it easier to expand or upgrade to new operating systems, new applications, or new browsers, without losing data.
• XML Makes Your Data More Available
Different applications can access your data, not only in HTML pages, but also from XML data sources. With XML, your data can be available to all kinds of "reading machines" (Handheld computers, voice machines, news feeds, etc), and make it more available for blind people, or people with other disabilities.


XML Syntax Rules
- All XML Elements Must Have a Closing Tag
- XML Tags are Case Sensitive
- XML Elements Must be Properly Nested
- XML Documents Must Have a Root Element
- XML Attribute Values Must be Quoted
- White-space is Preserved in XML
- Entity References
       There are 5 predefined entity references in XML:
                 &lt; < less than
                 &gt; > greater than
                 &amp; & ampersand
                 &apos; ' Apostrophe
                 &quot; " quotation mark


-What is an XML Element?
An XML element is everything from (including) the element's start tag to (including) the element's end tag.
An element can contain:
• other elements
• text
• attributes
• or a mix of all of the above...
<bookstore>
  <book category="CHILDREN">
    <title>Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="WEB">
    <title>Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>
In the example above, <bookstore> and <book> have element contents, because they contain other elements. <book> also has an attribute (category="CHILDREN"). <title>, <author>, <year>, and <price> have text content because they contain text.


-XML elements must follow these naming rules:
• Names can contain letters, numbers, and other characters
• Names cannot start with a number or punctuation character
• Names cannot start with the letters xml (or XML, or Xml, etc)
• Names cannot contain spaces


History of XML
    SGML was designed to be a flexible and all-encompassing coding scheme. Like XML, it is basically a toolkit for developing specialized markup languages. But SGML is much bigger than XML, with a looser syntax and lots of soteric parameters. It's so flexible that software built to process it is complex and expensive, and its usefulness is limited to large organizations that can afford both the software and the cost of maintaining complicated SGML. 
    The public revolution in generic coding came about in the early 1990s, when Hypertext Markup Language (HTML) was developed by Tim Berners-Lee and Anders Berglund. Berners-Lee and Berglund created an SGML document type for hypertext documents that was compact and efficient. It was easy to write software for this markup language, and even easier to encode documents. HTML escaped from the lab and went on to take over the world. However, HTML was in some ways a step backward. To achieve the simplicity necessary to be truly useful, some principles of generic coding had to be sacrificed. For example, one document type was used for all purposes,forcing people to overload tags rather than define specific-purpose tags. Second, many of the tags are purely presentational. The simplistic structure made it hard to tell where one section began and another ended. Many HTML-encoded documents today are so reliant on pure formatting that they can't be easily repurposed. To return to the ideals of generic coding, some people tried to adapt SGML for the Web—or rather, to adapt the Web to SGML. This proved too difficult. SGML was too big to squeeze into a little web browser. A smaller language that still retained the generality of SGML was required, and thus was born the Extensible Markup Language (XML).


XML Attributes
  In HTML, attributes provide additional information about elements:
   <img src="computer.gif">
   <a href="demo.asp">
-Attributes often provide information that is not a part of the data. In the example below, the file type is irrelevant to the data, but can be important to the software that wants to manipulate the element:
<file type="gif">computer.gif</file>
-Attribute values must always be quoted. Either single or double quotes can be used. For a person's sex, the person element can be written like this:
<person sex="female"> or like this  <person sex='female'>
-Some of the problems with using attributes are:
• attributes cannot contain multiple values (elements can)
• attributes cannot contain tree structures (elements can)
• attributes are not easily expandable (for future changes)
-Attributes are difficult to read and maintain. Use elements for data. Use attributes for information that is not relevant to the data.


XML Validation
XML with correct syntax is "Well Formed" XML. XML validated against a DTD is "Valid" XML.
-Well Formed XML Documents
    A "Well Formed" XML document has correct XML syntax.
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
-Valid XML Documents
   A "Valid" XML document is a "Well Formed" XML document, which also conforms to the rules of a Document Type Definition (DTD). The purpose of a DTD is to define the structure of an XML document. It defines the structure with a list of legal elements. The below will be the DTD for the example shown above:
<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
-PCDATA is Parsed Character Data, which is the text that will be parsed by the parser. The text will be examined by the parser for entities and markups. Tags inside the text will be treated as markups and entities will be expanded. Parsed Character Data should not contain any & , <  or  > symbols , these should be represented by the &amp; , &lt; , &gt;  entities.
-CDATA is text that will not be parsed by a parser.

Wednesday, June 8, 2011

DESIGN PATTERNS

In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations. Object-oriented design patterns typically show relationships and interactionsbetweenclasses or objects, without specifying the final application classes or objects that are involved. Algorithms are not thought of as design patterns, since they solvecomputationalproblems rather than design problems.

Design patterns can speed up the development process by providing tested, proven development paradigms. Effective software design requires considering issues that may not become visible until later in the implementation. Reusing design patterns helps to prevent subtle issues that can cause major problems and improves code readability for coders and architects familiar with the patterns.

History

Patterns originated as an architectural conceptby Christopher Alexander. In 1987, Kent Beckand Ward Cunningham began experimenting with the idea of applying patterns toprogramming and presented their results at theOOPSLA conference that year. In the following years, Beck, Cunningham and others followed up on this work.

Design patterns gained popularity in computer science after the book Design Patterns: Elements of Reusable Object-Oriented Softwarewas published in 1994 (Gamma et al). That same year, the first Pattern Languages of Programs conference was held and the following year, the Portland Pattern Repositorywas set up for documentation of design patterns. The scope of the term remained a matter of dispute into the next decade.

Uses

Design patterns can speed up the development process by providing tested, proven development paradigms. Effective software design requires considering issues that may not become visible until later in the implementation. Reusing design patterns helps to prevent subtle issues that can cause major problems and improves code readability for coders and architects familiar with the patterns.

Often, people only understand how to apply certain software design techniques to certain problems. These techniques are difficult to apply to a broader range of problems. Design patterns provide general solutions, documented in a format that doesn't require specifics tied to a particular problem.

Design patterns are composed of several sections (see Documentation). Of particular interest are the Structure, Participants, and Collaboration sections. These sections describe a design motif: a prototypical micro-architecture that developers copy and adapt to their particular designs to solve the recurrent problem described by the design pattern. (A micro-architecture is a set of program constituents (e.g., classes, methods...) and their relationships.) Developers use the design pattern by introducing in their designs this prototypical micro-architecture, which means that micro-architectures in their designs will have structure and organization similar to the chosen design motif.In addition, patterns allow developers to communicate using well-known, well understood names for software interactions. Common design patterns can be improved over time, making them more robust than ad-hoc designs.

Classification

Design patterns can be classified in terms of the underlying problem they solve. Examples of problem-based pattern classifications include:

Fundamental patterns

Creational patterns

Structural patterns

Behavioral patterns

Concurrency patterns

Architectural patterns

Documentation

The documentation for a design pattern should contain enough information about the problem that the pattern addresses, the context in which it is used, and the suggested solution.

A commonly used format is the one used by theGang of Four. It contains the following sections:

Pattern Name and Classification: Every pattern should have a descriptive and unique name that helps in identifying and referring to it. Additionally, the pattern should be classified according to a classification such as the one described earlier. This classification helps in identifying the use of the pattern.

Intent: This section should describe the goal behind the pattern and the reason for using it. It resembles the problem part of the pattern.

Also Known As: A pattern could have more than one name. These names should be documented in this section.

Motivation(Forces): This section provides a scenario consisting of a problem and a context in which this pattern can be used. By relating the problem and the context, this section shows when this pattern is used.

Applicability: This section includes situations in which this pattern is usable. It represents the context part of the pattern.

Structure: A graphical representation of the pattern. Class diagrams andInteraction diagrams can be used for this purpose.

Participants: A listing of the classes and objects used in this pattern and their roles in the design.

Collaboration: Describes how classes and objects used in the pattern interact with each other.

Consequences: This section describes the results, side effects, and trade offs caused by using this pattern.

Implementation: This section describes the implementation of the pattern, and represents the solution part of the pattern. It provides the techniques used in implementing this pattern, and suggests ways for this implementation.

Sample Code: An illustration of how this pattern can be used in a programming language

Known Uses: This section includes examples of real usages of this pattern.

Related Patterns: This section includes other patterns that have some relation with this pattern, so that they can be used along with this pattern, or instead of this pattern. It also includes the differences this pattern has with similar patterns.

MVC - MVP : Difference between these design patterns?

In traditional UI development - developer used to create a  View  using window or usercontrol or page and then write all logical code ...