SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

Pattern recognition UNIT 5
Pattern recognition UNIT 5Pattern recognition UNIT 5
Pattern recognition UNIT 5SURBHI SAROHA
 
Probabilistic Reasoning
Probabilistic Reasoning Probabilistic Reasoning
Probabilistic Reasoning Sushant Gautam
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECSreedhar Chowdam
 
Predicting students performance in final examination
Predicting students performance in final examinationPredicting students performance in final examination
Predicting students performance in final examinationRashid Ansari
 
Machine Learning Course | Edureka
Machine Learning Course | EdurekaMachine Learning Course | Edureka
Machine Learning Course | EdurekaEdureka!
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manualsameer farooq
 
Deep learning for medical imaging
Deep learning for medical imagingDeep learning for medical imaging
Deep learning for medical imaginggeetachauhan
 
Machine Learning
Machine LearningMachine Learning
Machine LearningVivek Garg
 
Machine Learning in Cyber Security
Machine Learning in Cyber SecurityMachine Learning in Cyber Security
Machine Learning in Cyber SecurityRishi Kant
 
AI Vs ML Vs DL PowerPoint Presentation Slide Templates Complete Deck
AI Vs ML Vs DL PowerPoint Presentation Slide Templates Complete DeckAI Vs ML Vs DL PowerPoint Presentation Slide Templates Complete Deck
AI Vs ML Vs DL PowerPoint Presentation Slide Templates Complete DeckSlideTeam
 
Skin lesion detection from dermoscopic images using Convolutional Neural Netw...
Skin lesion detection from dermoscopic images using Convolutional Neural Netw...Skin lesion detection from dermoscopic images using Convolutional Neural Netw...
Skin lesion detection from dermoscopic images using Convolutional Neural Netw...Adrià Romero López
 
Knowledge representation in AI
Knowledge representation in AIKnowledge representation in AI
Knowledge representation in AIVishal Singh
 
Module 4: Model Selection and Evaluation
Module 4: Model Selection and EvaluationModule 4: Model Selection and Evaluation
Module 4: Model Selection and EvaluationSara Hooker
 
Java Data Types
Java Data TypesJava Data Types
Java Data TypesSpotle.ai
 
Lecture 2 Basic Concepts in Machine Learning for Language Technology
Lecture 2 Basic Concepts in Machine Learning for Language TechnologyLecture 2 Basic Concepts in Machine Learning for Language Technology
Lecture 2 Basic Concepts in Machine Learning for Language TechnologyMarina Santini
 

La actualidad más candente (20)

Pattern recognition UNIT 5
Pattern recognition UNIT 5Pattern recognition UNIT 5
Pattern recognition UNIT 5
 
Deep learning and Healthcare
Deep learning and HealthcareDeep learning and Healthcare
Deep learning and Healthcare
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
 
Predicate logic
 Predicate logic Predicate logic
Predicate logic
 
Probabilistic Reasoning
Probabilistic Reasoning Probabilistic Reasoning
Probabilistic Reasoning
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPREC
 
Predicting students performance in final examination
Predicting students performance in final examinationPredicting students performance in final examination
Predicting students performance in final examination
 
Machine Learning Course | Edureka
Machine Learning Course | EdurekaMachine Learning Course | Edureka
Machine Learning Course | Edureka
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
 
Deep learning for medical imaging
Deep learning for medical imagingDeep learning for medical imaging
Deep learning for medical imaging
 
Machine Learning
Machine LearningMachine Learning
Machine Learning
 
Machine Learning in Cyber Security
Machine Learning in Cyber SecurityMachine Learning in Cyber Security
Machine Learning in Cyber Security
 
Sementic nets
Sementic netsSementic nets
Sementic nets
 
AI Vs ML Vs DL PowerPoint Presentation Slide Templates Complete Deck
AI Vs ML Vs DL PowerPoint Presentation Slide Templates Complete DeckAI Vs ML Vs DL PowerPoint Presentation Slide Templates Complete Deck
AI Vs ML Vs DL PowerPoint Presentation Slide Templates Complete Deck
 
Skin lesion detection from dermoscopic images using Convolutional Neural Netw...
Skin lesion detection from dermoscopic images using Convolutional Neural Netw...Skin lesion detection from dermoscopic images using Convolutional Neural Netw...
Skin lesion detection from dermoscopic images using Convolutional Neural Netw...
 
Knowledge representation in AI
Knowledge representation in AIKnowledge representation in AI
Knowledge representation in AI
 
Genetic algorithm
Genetic algorithmGenetic algorithm
Genetic algorithm
 
Module 4: Model Selection and Evaluation
Module 4: Model Selection and EvaluationModule 4: Model Selection and Evaluation
Module 4: Model Selection and Evaluation
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Lecture 2 Basic Concepts in Machine Learning for Language Technology
Lecture 2 Basic Concepts in Machine Learning for Language TechnologyLecture 2 Basic Concepts in Machine Learning for Language Technology
Lecture 2 Basic Concepts in Machine Learning for Language Technology
 

Similar a 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 a 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
 

Último

Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinojohnmickonozaleda
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 

Último (20)

Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipino
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 

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