SlideShare a Scribd company logo
1 of 18
Iram Ramrajkar                          T.Y.B.Sc.I.T.                             Advance Java


                                         SWING
GENERAL TEMPLATE TO CREATE SWING BASED APPLICATION:

import javax.swing.*;
import java.awt.*;
//import package for event

class MyFrame extends JFrame implements TypeListener
{
  GUIComponent cmp;

 MyFrame(String title)
  {
   super(title);
   setSize(200,200);

   Container cp=this.getContentPane();
   cp.setLayout(new FlowLayout());

    //instantiate cmp.

   cp.add(hello);

   cmp.addTypeListener(this); //register cmp for event
  }

 public void methodName(TypeEvent te)
  {
    //logic for event processing
  }

 public static void main(String args[])
  {
   MyFrame mf = new MyFrame ("My first frame");
   mf.setVisible(true);
  }
}


JList:

To create a JList:
                     String arr[]={“item1”,”item2” ,”item3” ,”item4” ,”item5”};
                     JList lst = new JList(arr);

To obtain the selected item value/index in the list:
  To obtain the value of the item selected:

                                        Page 1 of 18
Iram Ramrajkar                       T.Y.B.Sc.I.T.                    Advance Java


     String s = lst.getSelectedValue().toString();
  To obtain the index of the item selected:
     int ind = lst.getSelectedIndex();

For handling list events:
                           Make the class implement the ListSelectionListener
(present in javax.swing.event package), and override the valueChangedMethod.

   public void valueChagned(ListSelectionEvent lse)
      { perform "logic" }



JTable:

   To create a JTable:
    String [][]data = {
                 {“data of row 1”},
                 {“data of row 2”},
                 {“data of row 3”}
              };
    String []header = {column headers};
    JTable jt = new JTable(data,header);



JTree

  To create a tree:
  //create root node
      MutableTreeNode root = new DefaultMutableTreeNode(“data”);

  //Create all the branches
     MutableTreeNode bnc1 = new DefaultMutableTreeNode(“data”);
      ...
      ...
      ...

  //create the nodes of the branches
      bnc1.add(new DefaultMutableTreeNode(“data”), position);
      ...
      ...
      ...

  //Add the branches to the root
     root.add(bnc1,position);
     ...
     ...



                                     Page 2 of 18
Iram Ramrajkar                         T.Y.B.Sc.I.T.                         Advance Java



  //Add the root in the tree model
      DefaultTreeModel tm = new DefaultTreeModel(root);

  //Add the tree model to the tree.
     JTree t = new JTree(tm);

 To obtain the selected path of a tree:
   String s= t.getSelectionPath().toString();

 For handling tree events:
                           Make the class implement the TreeSelectionListener
(present in javax.swing.event package), and override the valueChangedMethod.

   public void valueChagned(TreeSelectionEvent tse)
      { perform "logic" }



JSplitPane

 To create a split pane:
   JSplitPane sp = new JSpiltPane(orientation, repaint, comp1,comp2)

        Where orientation can be:
          JSplitPane.HORIZONTAL_SPLIT
          JSplitPane.VERTICAL_SPLIT
        Repaint is either true or false stating if the component should be re-paint if the
spilt pane is re-sized.
        Comp1 and comp2 are the two components to be added in the splitpane.



JTabbedPane:

 To create a tabbed pane:
    JTabbedPane tp = new JTabbedPane();

  Adding tabs to it:
    tp.add(“tab title”,comp)



JButton:

To create a button:
   JButton jb = new JButton("label");

To handle button events:
                     Make the class implement the ActionListener (present in

                                       Page 3 of 18
Iram Ramrajkar                        T.Y.B.Sc.I.T.                   Advance Java


java.awt.event package), and override the actionPerformed Method.

   public void actionPerformed(ActionEvent tse)
      { perform "logic" }



JTextField:

To create a text box:
   JTextField tf = new JTextField(int size);



                                     SERVLET
GENERAL TEMPLATE FOR AN HTML FILE:

<html>
 <body>
   <form action="MyServlet" method="get">
      ADD ALL THE GUI COMPONENTS
   </form>
 </body>
</html>



VARIOUS HTML GUI COMPONENT TAGS:

For a text box:
       <input type="text" name="boxName" />

For a button:
       <input type="submit" value="buttonLabel" />

For a combo box:
       <select name="boxName">
              <option value="optName1"> Text </option>
              <option value="optName2"> Text </option>
              <option value="optName3"> Text </option>
       </select>

For a radio button:
       <input type="radio" name="buttonName1" value="val1" > text </input>
       <input type="radio" name="buttonName1" value="val2" > text </input>
       <input type="radio" name="buttonName1" value="val3" > text </input>



                                     Page 4 of 18
Iram Ramrajkar                             T.Y.B.Sc.I.T.           Advance Java



GENRAL TEMPLATE FOR GENRIC SERVLET:

import javax.servlet.*;
import java.io.*;

public class MyServlet extends GenericServlet
 {
   public void init(ServletConfig sc)
     { }

    public void service(ServletRequest req, ServletResponse res)
                 throws ServletException, IOException
      {
        res.setContentType(“type”)

         String data=req.getParameter(“compName”)

         PrintWriter pw=res.getWriter();

         PERFORM LOGIC

         pw.println(answer to logic);

         pw.close();
     }

    public void destroy( )
      { }
}


GENRAL TEMPLATE FOR HTTP SERVLET

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

    public void doGet(HttpServletRequest request,
                 HttpServletResponse response)
               throws ServletException, IOException
        //change from doGet to doPost
       //if transfer mechanism is HTTP POST.
    {
      response.setContentType("text/html");

         String data=request.getParameter("obj");


                                           Page 5 of 18
Iram Ramrajkar                         T.Y.B.Sc.I.T.   Advance Java


        PrintWriter pw=response.getWriter();

        PERFORM LOGIC
        pw.print(answer to logic);

        pw.close();
    }
}



                         JAVA SERVER PAGES – JSP
GENRAL TEMPLATE FOR HTML PAGE:

<html>
 <body>
   <form action="fileName.jsp" method="get">
      ADD ALL THE GUI COMPONENTS
   </form>
 </body>
</html>



GENRAL TEMPLATE for JSP TAGS:

for printing values/output use expression tag:
<%=exp %>

for decaling variables and methods:
<%! declare %>

for writing small java code:
<% code %>

for importing packages:
<% @page import="package name" %>




                                       Page 6 of 18
Iram Ramrajkar                           T.Y.B.Sc.I.T.                Advance Java


               JAVA DATABASE CONNECTIVITY – JDBC
GENRAL TEMPLATE FOR JDBC BASED PROGRAM

import java.sql.*;

class Demo
{
  public static void main(String args[])
    {
      try
        {
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

         Connection con = DriverManager.getConnection("jdbc:odbc:dsn");

         CREATE STATEMENT OBJECT

         EXECUTE AND PROCESS SQL QUERY

         PRINT ANSWER

          con.close();
           }
         catch(Exception e)
         { System.out.println("Error: "+e); }
     }
 }


Static SQL Statements:

Statement stmt = con.createStatement();

for executing DDL (insert/delete/update queries)
    int ans=stmt.executeUpdate("sql query");

for executing DQL (select queries)
    ResultSet rs = stmt.executeQuery("sql query");
    while(rs.next)
       { print "rs.getDataType("column name")"; }



Dynamic SQL Statements:

PreparedStatement ps = con.prepareStatement("query with missing elements
replaced by ? ");

                                         Page 7 of 18
Iram Ramrajkar                       T.Y.B.Sc.I.T.   Advance Java



for executing DDL (insert/delete/update queries)
    int ans=sps.executeUpdate( );

for executing DQL (select queries)
    ResultSet rs = ps.executeQuery( );
    while(rs.next)
       { print "rs.getDataType("column name")"; }




                                    Page 8 of 18
Iram Ramrajkar                           T.Y.B.Sc.I.T.        Advance Java




SQL QUERIES:

INSERT:
     insert into tableName values ( val1,val2, val3, .....)

DELETE:
     delete from tableName where condition

UPDATE:
    update tableName
          set columnName = value ,
          columnName = value ,
          ...
    where condition

SELECT:
     select columnName, columnName, . . .
     from tableName
     where condition



                            JAVA SERVER FACES – JSF
GENERAL TEMPLATE FOR CREATING A JSF MANAGED BEAN:

import javax.faces.bean.*;

@ManagedBean
@SessionScoped
public class MyBean {
  //declare variables

    //assign getters and setters to variables.

    public String logic()
    {
      //perform logic

        if(answer to logic is correct)
        {return "success";}
        else
        {return "fail";}
    }
}



                                         Page 9 of 18
Iram Ramrajkar                     T.Y.B.Sc.I.T.                   Advance Java



GENERAL TEMPLATE FOR CREATING A FACELET / JSF PAGE

<html xmlns="http://www.w3.org/1999/xhtml"
   xmlns:h="http://java.sun.com/jsf/html">
  <h:body>
    <h:form>
       ADD ALL THE COMPONENTS

       <h:commandButton value="Login" action="#{myBean.logic}"/>
     </h:form>
  </h:body>
</html>


JSF FACELET GUI TAGS:

Adding a button component
      <h:commandButton value="label" action="#{courseBean.methodName}"/>

Adding a text field component
      <h:inputText id="name" value="#{myBean.attribute}"/>

Adding a password filed component
      <h:inputText id="name" value="#{myBean.attribute}"/>



GENERAL TEMPLATE FOR CREATING NAIVGATION RULES IN JSF
CONFIGURATION FILE (faces-config.xml)

<faces-config version="2.0"
  xmlns="http://java.sun.com/xml/ns/javaee">

 <navigation-rule>
  <from-view-id>/index.xhtml</from-view-id>
  <navigation-case>
     <from-action>#{myBean.logic}</from-action>
        <from-outcome>success</from-outcome>
        <to-view-id>page1.xhtml</to-view-id>
  </navigation-case>

   <navigation-case>
     <from-action>#{myBean.logic}</from-action>
        <from-outcome>fail</from-outcome>
        <to-view-id>page2.xhtml</to-view-id>
   </navigation-case>
 </navigation-rule>
</faces-config>


                                  Page 10 of 18
Iram Ramrajkar                           T.Y.B.Sc.I.T.              Advance Java




                     ENTERPRISE JAVA BEAN – EJB
GENERAL TEMPLATE FOR CREATING AN ENTERPRISE BEAN

package myPack;

import javax.ejb.Stateless;

@Stateless
public class MyBean {
 public returnType method(parameters)
    {
      PERFORM LOGIC AND RETURN ANSWER
     }
   }
 }


GENERAL TEMPLATE FOR CREATING A SERVLET THAT CALLS A BEAN:

import myPack.*;
import javax.ejb.*;
import java.io.*;
import javax.servlet.*
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

  @EJB
  MyBean bean;

  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException
    {
      response.setContentType("text/html");

       PrintWriter out = response.getWriter();

    try {
dataType var = bean.method(parameters);

out.println("Answer: "+var);
        }

       } catch(Exception e) { out.println(e); }
  }
   }

                                        Page 11 of 18
Iram Ramrajkar                        T.Y.B.Sc.I.T.                 Advance Java




GENERAL TEMPLATE FOR CREATING AN HTML FILE

<html>
 <body>
   <form action="MyServlet" method="get">
      ADD ALL THE GUI COMPONENTS
   </form>
 </body>
</html>



                                  HIBERNATE
GENERAL TEMPLATE FOR CREATING A POJO FOR HIBERNATE:

package myPack;
import java.io.*;

public class MyPojo implements Serializable
 {
   //declare variables

  //provide getters and setters for varaibles.
 }



GENERAL TEMPLATE FOR CREATING A HIBERNATE CONFIGURATION FILE:
(hibernate.cfg.xml)

<hibernate-configuration>
 <session-factory>
  <property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <property
name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/myDB</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.connection.password">1234</property>
  <mapping resource="myPack/MyMapping.hbm.xml"/>
 </session-factory>
     </hibernate-configuration>




                                     Page 12 of 18
Iram Ramrajkar                         T.Y.B.Sc.I.T.                  Advance Java




GENERAL TEMPLATE FOR CREATING A HIBERNATE MAPPING FILE:
(MyMapping.hbm.xml)

<hibernate-mapping>
      <class name="myPack.MyPojo" table="student" catalog="myDB">
         <id name="pk property name" type="data type">
              <column name="col name"/>
              <generator class="identity"/>
         </id>

          <property name="property name" type="data type">
              <column name="col anme" />
          </property>
       </class>
    </hibernate-mapping>



GENERAL TEMPLATE FOR CREATING A JSP PAGE THAT WILL ADD
RECORDS INTO DATABASE USING HIBERNATE:

<%@ page import="org.hibernate.*, org.hibernate.cfg.*, myPack.*;"%>

<% SessionFactory sf;
Session s;
Transaction t=null;

sf = new Configuration().configure().buildSessionFactory();

s=sf.openSession();

try
{
t=s.beginTransaction();
MyPojo st=new MyPojo();
USE SETTERS TO SET VALUES OF VARIABLES
s.save(st);

t.commit();
out.println("Record Added!");

}
catch(RuntimeException e)
    { t.rollback(); out.println(e);}
%>




                                       Page 13 of 18
Iram Ramrajkar                          T.Y.B.Sc.I.T.                   Advance Java




GENERAL TEMPLATE FOR CREATING A JSP PAGE THAT WILL RETRIVE
RECORDS FROM THE DATABASE USING HIBERNATE

<%@ page import="org.hibernate.*, org.hibernate.cfg.*, myPack.*, java.util.*;" %>

<% SessionFactory sf;
Session s;

sf=new Configuration().configure().buildSessionFactory();
s=sf.openSession();

Transaction t=null;
List <MyPojo> l;

try
  {
    t=s.beginTransaction();

  l = s.createQuery("from MyPojo").list();

  Iterator ite=l.iterator();

   while(ite.hasNext())
        {
         MyPojo obj=(MyPojo) ite.next();
            //print values using getters of varaibles
         }
   s.close();
  }
catch(RuntimeException e)
  { out.println(e); } %>




                                       Page 14 of 18
Iram Ramrajkar                         T.Y.B.Sc.I.T.        Advance Java


                                        STRUT
GENERAL TEMPLATE FOR CREATING A STRUTS ACTION CLASS

package myPack;

import com.opensymphony.xwork2.*;

public class MyAction extends ActionSupport
{
 //declare varaibles

//assign getters and setters

    @Override
    public String execute()
    {
      //perform logic
      if(answer to logic is correct)
          return "success";
      else
          return "failure";
    }
}


GENERAL TEMPLATE FOR CREATING A STRUTS CONFIGURATION FILE
(struts.xml)

<struts>
<package name="/" extends="struts-default">
 <action name="MyAction" class="myPack.MyAction">
   <result name="success">/page1.jsp</result>
   <result name="failure">/page2.jsp</result>
 </action>
</package>
</struts>


GENERAL TEMPLATE FOR CREATING A JSP PAGE THAT USES STRUTS
TAGLIB AND CALLS A STRUTS ACTION CLASS

<%@taglib prefix="s" uri="/struts-tags" %>
<html>
  <body>
    <s:form method="get" action="myPack/MyAction.action">
       ADD COMPONENTS
    </s:form>

                                       Page 15 of 18
Iram Ramrajkar                       T.Y.B.Sc.I.T.            Advance Java


  </body>
</html>



GENERAL TAG TEMPLATE FOR STRUTS TAGLIB IN JSP PAGE TO BUILD GUI
COMPONENTS:

To display value of some property in action class:
      <s:property value="property name" "/>

To display a textbox:
      <s:textfield name="property name"/>

To display a button:
       <s:submit value="label" />



                               WEB SERVICES
GENERAL TEMPLATE FOR CREATING A WEB SERVICE PROVIDER

package myPack;

import javax.jws.*;
import javax.ejb.*;

@WebService( )
@Stateless()
public class MyService {

    @WebMethod( )
    public returnType methodName(@WebParam( ) parameters) {
      //logic
    }
}


GENERAL TEMPLATE FOR CREATING A WEB SERVICE CONSUMER

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.ws.*;
import myPack.*;

public class MyServlet extends HttpServlet {
  @WebServiceRef(wsdlLocation = "WEB-
                                    Page 16 of 18
Iram Ramrajkar                        T.Y.B.Sc.I.T.                  Advance Java


INF/wsdl/localhost_8080/MyApp/MyService.wsdl")
  private MyService_Service service;

   public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
       {
        //obatin parameters from the user

        response.setContentType("text/html");

        PrintWriter pw = response.getWriter();

        dataType ans=methodName(parameters);
        pw.println(ans);

        pw.close();
    }

    private returnType methodName(parameters) {
       MyService port = service.getMyServicePort();
       return port.methodName(parameters);
    }
}


                                   JAVA MAIL
GENERAL TEMPLATE FOR CREATING A SERVLET THAT SENDS MAIL USING
JAVA MAIL API

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;


public class processMail extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse
response)
       throws ServletException, IOException {
     String from=request.getParameter("t1");
     String emailFrom=request.getParameter("t2");
     String emailFromPwd=request.getParameter("t3");
     String emailTo=request.getParameter("t4");

                                     Page 17 of 18
Iram Ramrajkar                             T.Y.B.Sc.I.T.                 Advance Java


          String sub=request.getParameter("t5");
          String msg=request.getParameter("t6");

          PrintWriter pw=response.getWriter();

          try
          {
             String host="smtp.gmail.com";
             String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

              Properties prop=System.getProperties();
              prop.put("mail.host",host);
              prop.put("mail.transport.protocol","smtp");
              prop.put("mail.smtp.auth","true");
              prop.put("mail.smtp.port",465);
              prop.put("mail.smtp.socketFactory.fallback","false");
              prop.put("mail.smtp.socketFactory.class",SSL_FACTORY);

              Session s = Session.getDefaultInstance(prop, null);

              Message m = new MimeMessage (s);
              m.setFrom(new InternetAddress(emailFrom));
              m.addRecipient(Message.RecipientType.TO,new InternetAddress(emailTo));
              m.setSubject(sub);
              m.setContent(msg,"text/html");

              Transport t = s.getTransport("smtp");
              t.connect(host, emailFrom, emailFromPwd);
              t.sendMessage(m,m.getAllRecipients());
              pw.println("Message sent successfully :) ");
              t.close();
          }

          catch(Exception e)
          { pw.println(e); }
      }
  }


GENERAL TEMPLATE FOR AN HTML FILE:

<html>
 <body>
   <form action="MyServlet" method="get">
      ADD ALL THE GUI COMPONENTS
   </form>
 </body>
</html>



                                          Page 18 of 18

More Related Content

What's hot

Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in PythonSujith Kumar
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in javaNilesh Dalvi
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: MethodsSvetlin Nakov
 
Data Structure Project File
Data Structure Project FileData Structure Project File
Data Structure Project FileDeyvessh kumar
 
Introduction to Array ppt
Introduction to Array pptIntroduction to Array ppt
Introduction to Array pptsandhya yadav
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in javaHitesh Kumar
 
Data types in php
Data types in phpData types in php
Data types in phpilakkiya
 
Using SQL Queries to Insert, Update, Delete, and View Data.ppt
Using SQL Queries to Insert, Update, Delete, and View Data.pptUsing SQL Queries to Insert, Update, Delete, and View Data.ppt
Using SQL Queries to Insert, Update, Delete, and View Data.pptMohammedJifar1
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaMonika Mishra
 
Introduction to matplotlib
Introduction to matplotlibIntroduction to matplotlib
Introduction to matplotlibPiyush rai
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Appili Vamsi Krishna
 
Intoduction to numpy
Intoduction to numpyIntoduction to numpy
Intoduction to numpyFaraz Ahmed
 

What's hot (20)

Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Python : Dictionaries
Python : DictionariesPython : Dictionaries
Python : Dictionaries
 
Awt and swing in java
Awt and swing in javaAwt and swing in java
Awt and swing in java
 
Advanced Python : Decorators
Advanced Python : DecoratorsAdvanced Python : Decorators
Advanced Python : Decorators
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
Data Structure Project File
Data Structure Project FileData Structure Project File
Data Structure Project File
 
Introduction to Array ppt
Introduction to Array pptIntroduction to Array ppt
Introduction to Array ppt
 
PHP - Introduction to File Handling with PHP
PHP -  Introduction to  File Handling with PHPPHP -  Introduction to  File Handling with PHP
PHP - Introduction to File Handling with PHP
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
Data types in php
Data types in phpData types in php
Data types in php
 
Using SQL Queries to Insert, Update, Delete, and View Data.ppt
Using SQL Queries to Insert, Update, Delete, and View Data.pptUsing SQL Queries to Insert, Update, Delete, and View Data.ppt
Using SQL Queries to Insert, Update, Delete, and View Data.ppt
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Introduction to matplotlib
Introduction to matplotlibIntroduction to matplotlib
Introduction to matplotlib
 
Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional Arrays 1D and 2D , and multi dimensional
Arrays 1D and 2D , and multi dimensional
 
Java swing
Java swingJava swing
Java swing
 
3rd Semester Computer Science and Engineering (ACU) Question papers
3rd Semester Computer Science and Engineering  (ACU) Question papers3rd Semester Computer Science and Engineering  (ACU) Question papers
3rd Semester Computer Science and Engineering (ACU) Question papers
 
Intoduction to numpy
Intoduction to numpyIntoduction to numpy
Intoduction to numpy
 

Similar to Advance Java Programs skeleton

Exercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera CymbronExercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera Cymbroncymbron
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxCodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxmary772
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxCodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxmccormicknadine86
 
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsphanleson
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsleminhvuong
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingVisual Engineering
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql JOYITAKUNDU1
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Zianed Hou
 
In Java Write a GUI application to simulate writing out a check. The.pdf
In Java Write a GUI application to simulate writing out a check. The.pdfIn Java Write a GUI application to simulate writing out a check. The.pdf
In Java Write a GUI application to simulate writing out a check. The.pdfflashfashioncasualwe
 
Write a GUI application to simulate writing out a check. The value o.pdf
Write a GUI application to simulate writing out a check. The value o.pdfWrite a GUI application to simulate writing out a check. The value o.pdf
Write a GUI application to simulate writing out a check. The value o.pdffathimaoptical
 
Main class --------------------------import java.awt.FlowLayout.pdf
Main class --------------------------import java.awt.FlowLayout.pdfMain class --------------------------import java.awt.FlowLayout.pdf
Main class --------------------------import java.awt.FlowLayout.pdfanushkaent7
 
Java!!!!!Create a program that authenticates username and password.pdf
Java!!!!!Create a program that authenticates username and password.pdfJava!!!!!Create a program that authenticates username and password.pdf
Java!!!!!Create a program that authenticates username and password.pdfarvindarora20042013
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 

Similar to Advance Java Programs skeleton (20)

Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Exercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera CymbronExercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera Cymbron
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
My java file
My java fileMy java file
My java file
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxCodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docxCodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
 
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
code for quiz in my sql
code for quiz  in my sql code for quiz  in my sql
code for quiz in my sql
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
 
In Java Write a GUI application to simulate writing out a check. The.pdf
In Java Write a GUI application to simulate writing out a check. The.pdfIn Java Write a GUI application to simulate writing out a check. The.pdf
In Java Write a GUI application to simulate writing out a check. The.pdf
 
Write a GUI application to simulate writing out a check. The value o.pdf
Write a GUI application to simulate writing out a check. The value o.pdfWrite a GUI application to simulate writing out a check. The value o.pdf
Write a GUI application to simulate writing out a check. The value o.pdf
 
Xml & Java
Xml & JavaXml & Java
Xml & Java
 
Main class --------------------------import java.awt.FlowLayout.pdf
Main class --------------------------import java.awt.FlowLayout.pdfMain class --------------------------import java.awt.FlowLayout.pdf
Main class --------------------------import java.awt.FlowLayout.pdf
 
Java!!!!!Create a program that authenticates username and password.pdf
Java!!!!!Create a program that authenticates username and password.pdfJava!!!!!Create a program that authenticates username and password.pdf
Java!!!!!Create a program that authenticates username and password.pdf
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 

Recently uploaded

A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 

Recently uploaded (20)

A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 

Advance Java Programs skeleton

  • 1. Iram Ramrajkar T.Y.B.Sc.I.T. Advance Java SWING GENERAL TEMPLATE TO CREATE SWING BASED APPLICATION: import javax.swing.*; import java.awt.*; //import package for event class MyFrame extends JFrame implements TypeListener { GUIComponent cmp; MyFrame(String title) { super(title); setSize(200,200); Container cp=this.getContentPane(); cp.setLayout(new FlowLayout()); //instantiate cmp. cp.add(hello); cmp.addTypeListener(this); //register cmp for event } public void methodName(TypeEvent te) { //logic for event processing } public static void main(String args[]) { MyFrame mf = new MyFrame ("My first frame"); mf.setVisible(true); } } JList: To create a JList: String arr[]={“item1”,”item2” ,”item3” ,”item4” ,”item5”}; JList lst = new JList(arr); To obtain the selected item value/index in the list: To obtain the value of the item selected: Page 1 of 18
  • 2. Iram Ramrajkar T.Y.B.Sc.I.T. Advance Java String s = lst.getSelectedValue().toString(); To obtain the index of the item selected: int ind = lst.getSelectedIndex(); For handling list events: Make the class implement the ListSelectionListener (present in javax.swing.event package), and override the valueChangedMethod. public void valueChagned(ListSelectionEvent lse) { perform "logic" } JTable: To create a JTable: String [][]data = { {“data of row 1”}, {“data of row 2”}, {“data of row 3”} }; String []header = {column headers}; JTable jt = new JTable(data,header); JTree To create a tree: //create root node MutableTreeNode root = new DefaultMutableTreeNode(“data”); //Create all the branches MutableTreeNode bnc1 = new DefaultMutableTreeNode(“data”); ... ... ... //create the nodes of the branches bnc1.add(new DefaultMutableTreeNode(“data”), position); ... ... ... //Add the branches to the root root.add(bnc1,position); ... ... Page 2 of 18
  • 3. Iram Ramrajkar T.Y.B.Sc.I.T. Advance Java //Add the root in the tree model DefaultTreeModel tm = new DefaultTreeModel(root); //Add the tree model to the tree. JTree t = new JTree(tm); To obtain the selected path of a tree: String s= t.getSelectionPath().toString(); For handling tree events: Make the class implement the TreeSelectionListener (present in javax.swing.event package), and override the valueChangedMethod. public void valueChagned(TreeSelectionEvent tse) { perform "logic" } JSplitPane To create a split pane: JSplitPane sp = new JSpiltPane(orientation, repaint, comp1,comp2) Where orientation can be: JSplitPane.HORIZONTAL_SPLIT JSplitPane.VERTICAL_SPLIT Repaint is either true or false stating if the component should be re-paint if the spilt pane is re-sized. Comp1 and comp2 are the two components to be added in the splitpane. JTabbedPane: To create a tabbed pane: JTabbedPane tp = new JTabbedPane(); Adding tabs to it: tp.add(“tab title”,comp) JButton: To create a button: JButton jb = new JButton("label"); To handle button events: Make the class implement the ActionListener (present in Page 3 of 18
  • 4. Iram Ramrajkar T.Y.B.Sc.I.T. Advance Java java.awt.event package), and override the actionPerformed Method. public void actionPerformed(ActionEvent tse) { perform "logic" } JTextField: To create a text box: JTextField tf = new JTextField(int size); SERVLET GENERAL TEMPLATE FOR AN HTML FILE: <html> <body> <form action="MyServlet" method="get"> ADD ALL THE GUI COMPONENTS </form> </body> </html> VARIOUS HTML GUI COMPONENT TAGS: For a text box: <input type="text" name="boxName" /> For a button: <input type="submit" value="buttonLabel" /> For a combo box: <select name="boxName"> <option value="optName1"> Text </option> <option value="optName2"> Text </option> <option value="optName3"> Text </option> </select> For a radio button: <input type="radio" name="buttonName1" value="val1" > text </input> <input type="radio" name="buttonName1" value="val2" > text </input> <input type="radio" name="buttonName1" value="val3" > text </input> Page 4 of 18
  • 5. Iram Ramrajkar T.Y.B.Sc.I.T. Advance Java GENRAL TEMPLATE FOR GENRIC SERVLET: import javax.servlet.*; import java.io.*; public class MyServlet extends GenericServlet { public void init(ServletConfig sc) { } public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { res.setContentType(“type”) String data=req.getParameter(“compName”) PrintWriter pw=res.getWriter(); PERFORM LOGIC pw.println(answer to logic); pw.close(); } public void destroy( ) { } } GENRAL TEMPLATE FOR HTTP SERVLET import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException //change from doGet to doPost //if transfer mechanism is HTTP POST. { response.setContentType("text/html"); String data=request.getParameter("obj"); Page 5 of 18
  • 6. Iram Ramrajkar T.Y.B.Sc.I.T. Advance Java PrintWriter pw=response.getWriter(); PERFORM LOGIC pw.print(answer to logic); pw.close(); } } JAVA SERVER PAGES – JSP GENRAL TEMPLATE FOR HTML PAGE: <html> <body> <form action="fileName.jsp" method="get"> ADD ALL THE GUI COMPONENTS </form> </body> </html> GENRAL TEMPLATE for JSP TAGS: for printing values/output use expression tag: <%=exp %> for decaling variables and methods: <%! declare %> for writing small java code: <% code %> for importing packages: <% @page import="package name" %> Page 6 of 18
  • 7. Iram Ramrajkar T.Y.B.Sc.I.T. Advance Java JAVA DATABASE CONNECTIVITY – JDBC GENRAL TEMPLATE FOR JDBC BASED PROGRAM import java.sql.*; class Demo { public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:dsn"); CREATE STATEMENT OBJECT EXECUTE AND PROCESS SQL QUERY PRINT ANSWER con.close(); } catch(Exception e) { System.out.println("Error: "+e); } } } Static SQL Statements: Statement stmt = con.createStatement(); for executing DDL (insert/delete/update queries) int ans=stmt.executeUpdate("sql query"); for executing DQL (select queries) ResultSet rs = stmt.executeQuery("sql query"); while(rs.next) { print "rs.getDataType("column name")"; } Dynamic SQL Statements: PreparedStatement ps = con.prepareStatement("query with missing elements replaced by ? "); Page 7 of 18
  • 8. Iram Ramrajkar T.Y.B.Sc.I.T. Advance Java for executing DDL (insert/delete/update queries) int ans=sps.executeUpdate( ); for executing DQL (select queries) ResultSet rs = ps.executeQuery( ); while(rs.next) { print "rs.getDataType("column name")"; } Page 8 of 18
  • 9. Iram Ramrajkar T.Y.B.Sc.I.T. Advance Java SQL QUERIES: INSERT: insert into tableName values ( val1,val2, val3, .....) DELETE: delete from tableName where condition UPDATE: update tableName set columnName = value , columnName = value , ... where condition SELECT: select columnName, columnName, . . . from tableName where condition JAVA SERVER FACES – JSF GENERAL TEMPLATE FOR CREATING A JSF MANAGED BEAN: import javax.faces.bean.*; @ManagedBean @SessionScoped public class MyBean { //declare variables //assign getters and setters to variables. public String logic() { //perform logic if(answer to logic is correct) {return "success";} else {return "fail";} } } Page 9 of 18
  • 10. Iram Ramrajkar T.Y.B.Sc.I.T. Advance Java GENERAL TEMPLATE FOR CREATING A FACELET / JSF PAGE <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"> <h:body> <h:form> ADD ALL THE COMPONENTS <h:commandButton value="Login" action="#{myBean.logic}"/> </h:form> </h:body> </html> JSF FACELET GUI TAGS: Adding a button component <h:commandButton value="label" action="#{courseBean.methodName}"/> Adding a text field component <h:inputText id="name" value="#{myBean.attribute}"/> Adding a password filed component <h:inputText id="name" value="#{myBean.attribute}"/> GENERAL TEMPLATE FOR CREATING NAIVGATION RULES IN JSF CONFIGURATION FILE (faces-config.xml) <faces-config version="2.0" xmlns="http://java.sun.com/xml/ns/javaee"> <navigation-rule> <from-view-id>/index.xhtml</from-view-id> <navigation-case> <from-action>#{myBean.logic}</from-action> <from-outcome>success</from-outcome> <to-view-id>page1.xhtml</to-view-id> </navigation-case> <navigation-case> <from-action>#{myBean.logic}</from-action> <from-outcome>fail</from-outcome> <to-view-id>page2.xhtml</to-view-id> </navigation-case> </navigation-rule> </faces-config> Page 10 of 18
  • 11. Iram Ramrajkar T.Y.B.Sc.I.T. Advance Java ENTERPRISE JAVA BEAN – EJB GENERAL TEMPLATE FOR CREATING AN ENTERPRISE BEAN package myPack; import javax.ejb.Stateless; @Stateless public class MyBean { public returnType method(parameters) { PERFORM LOGIC AND RETURN ANSWER } } } GENERAL TEMPLATE FOR CREATING A SERVLET THAT CALLS A BEAN: import myPack.*; import javax.ejb.*; import java.io.*; import javax.servlet.* import javax.servlet.http.*; public class MyServlet extends HttpServlet { @EJB MyBean bean; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); try { dataType var = bean.method(parameters); out.println("Answer: "+var); } } catch(Exception e) { out.println(e); } } } Page 11 of 18
  • 12. Iram Ramrajkar T.Y.B.Sc.I.T. Advance Java GENERAL TEMPLATE FOR CREATING AN HTML FILE <html> <body> <form action="MyServlet" method="get"> ADD ALL THE GUI COMPONENTS </form> </body> </html> HIBERNATE GENERAL TEMPLATE FOR CREATING A POJO FOR HIBERNATE: package myPack; import java.io.*; public class MyPojo implements Serializable { //declare variables //provide getters and setters for varaibles. } GENERAL TEMPLATE FOR CREATING A HIBERNATE CONFIGURATION FILE: (hibernate.cfg.xml) <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myDB</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">1234</property> <mapping resource="myPack/MyMapping.hbm.xml"/> </session-factory> </hibernate-configuration> Page 12 of 18
  • 13. Iram Ramrajkar T.Y.B.Sc.I.T. Advance Java GENERAL TEMPLATE FOR CREATING A HIBERNATE MAPPING FILE: (MyMapping.hbm.xml) <hibernate-mapping> <class name="myPack.MyPojo" table="student" catalog="myDB"> <id name="pk property name" type="data type"> <column name="col name"/> <generator class="identity"/> </id> <property name="property name" type="data type"> <column name="col anme" /> </property> </class> </hibernate-mapping> GENERAL TEMPLATE FOR CREATING A JSP PAGE THAT WILL ADD RECORDS INTO DATABASE USING HIBERNATE: <%@ page import="org.hibernate.*, org.hibernate.cfg.*, myPack.*;"%> <% SessionFactory sf; Session s; Transaction t=null; sf = new Configuration().configure().buildSessionFactory(); s=sf.openSession(); try { t=s.beginTransaction(); MyPojo st=new MyPojo(); USE SETTERS TO SET VALUES OF VARIABLES s.save(st); t.commit(); out.println("Record Added!"); } catch(RuntimeException e) { t.rollback(); out.println(e);} %> Page 13 of 18
  • 14. Iram Ramrajkar T.Y.B.Sc.I.T. Advance Java GENERAL TEMPLATE FOR CREATING A JSP PAGE THAT WILL RETRIVE RECORDS FROM THE DATABASE USING HIBERNATE <%@ page import="org.hibernate.*, org.hibernate.cfg.*, myPack.*, java.util.*;" %> <% SessionFactory sf; Session s; sf=new Configuration().configure().buildSessionFactory(); s=sf.openSession(); Transaction t=null; List <MyPojo> l; try { t=s.beginTransaction(); l = s.createQuery("from MyPojo").list(); Iterator ite=l.iterator(); while(ite.hasNext()) { MyPojo obj=(MyPojo) ite.next(); //print values using getters of varaibles } s.close(); } catch(RuntimeException e) { out.println(e); } %> Page 14 of 18
  • 15. Iram Ramrajkar T.Y.B.Sc.I.T. Advance Java STRUT GENERAL TEMPLATE FOR CREATING A STRUTS ACTION CLASS package myPack; import com.opensymphony.xwork2.*; public class MyAction extends ActionSupport { //declare varaibles //assign getters and setters @Override public String execute() { //perform logic if(answer to logic is correct) return "success"; else return "failure"; } } GENERAL TEMPLATE FOR CREATING A STRUTS CONFIGURATION FILE (struts.xml) <struts> <package name="/" extends="struts-default"> <action name="MyAction" class="myPack.MyAction"> <result name="success">/page1.jsp</result> <result name="failure">/page2.jsp</result> </action> </package> </struts> GENERAL TEMPLATE FOR CREATING A JSP PAGE THAT USES STRUTS TAGLIB AND CALLS A STRUTS ACTION CLASS <%@taglib prefix="s" uri="/struts-tags" %> <html> <body> <s:form method="get" action="myPack/MyAction.action"> ADD COMPONENTS </s:form> Page 15 of 18
  • 16. Iram Ramrajkar T.Y.B.Sc.I.T. Advance Java </body> </html> GENERAL TAG TEMPLATE FOR STRUTS TAGLIB IN JSP PAGE TO BUILD GUI COMPONENTS: To display value of some property in action class: <s:property value="property name" "/> To display a textbox: <s:textfield name="property name"/> To display a button: <s:submit value="label" /> WEB SERVICES GENERAL TEMPLATE FOR CREATING A WEB SERVICE PROVIDER package myPack; import javax.jws.*; import javax.ejb.*; @WebService( ) @Stateless() public class MyService { @WebMethod( ) public returnType methodName(@WebParam( ) parameters) { //logic } } GENERAL TEMPLATE FOR CREATING A WEB SERVICE CONSUMER import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import javax.xml.ws.*; import myPack.*; public class MyServlet extends HttpServlet { @WebServiceRef(wsdlLocation = "WEB- Page 16 of 18
  • 17. Iram Ramrajkar T.Y.B.Sc.I.T. Advance Java INF/wsdl/localhost_8080/MyApp/MyService.wsdl") private MyService_Service service; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //obatin parameters from the user response.setContentType("text/html"); PrintWriter pw = response.getWriter(); dataType ans=methodName(parameters); pw.println(ans); pw.close(); } private returnType methodName(parameters) { MyService port = service.getMyServicePort(); return port.methodName(parameters); } } JAVA MAIL GENERAL TEMPLATE FOR CREATING A SERVLET THAT SENDS MAIL USING JAVA MAIL API import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class processMail extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String from=request.getParameter("t1"); String emailFrom=request.getParameter("t2"); String emailFromPwd=request.getParameter("t3"); String emailTo=request.getParameter("t4"); Page 17 of 18
  • 18. Iram Ramrajkar T.Y.B.Sc.I.T. Advance Java String sub=request.getParameter("t5"); String msg=request.getParameter("t6"); PrintWriter pw=response.getWriter(); try { String host="smtp.gmail.com"; String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; Properties prop=System.getProperties(); prop.put("mail.host",host); prop.put("mail.transport.protocol","smtp"); prop.put("mail.smtp.auth","true"); prop.put("mail.smtp.port",465); prop.put("mail.smtp.socketFactory.fallback","false"); prop.put("mail.smtp.socketFactory.class",SSL_FACTORY); Session s = Session.getDefaultInstance(prop, null); Message m = new MimeMessage (s); m.setFrom(new InternetAddress(emailFrom)); m.addRecipient(Message.RecipientType.TO,new InternetAddress(emailTo)); m.setSubject(sub); m.setContent(msg,"text/html"); Transport t = s.getTransport("smtp"); t.connect(host, emailFrom, emailFromPwd); t.sendMessage(m,m.getAllRecipients()); pw.println("Message sent successfully :) "); t.close(); } catch(Exception e) { pw.println(e); } } } GENERAL TEMPLATE FOR AN HTML FILE: <html> <body> <form action="MyServlet" method="get"> ADD ALL THE GUI COMPONENTS </form> </body> </html> Page 18 of 18