SlideShare a Scribd company logo
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 (20)

PPT
JavaScript: Events Handling
Yuriy Bezgachnyuk
 
PPTX
learnhtmlbyvipuladissanayake-170516061515 (1).pptx
ManuAbraham17
 
PPTX
For Loops and Nesting in Python
primeteacher32
 
PPT
Java naming conventions
Lovely Professional University
 
PPTX
Introduction to python
Ayshwarya Baburam
 
PDF
JavaScript - Chapter 14 - Form Handling
WebStackAcademy
 
PPT
Java script -23jan2015
Sasidhar Kothuru
 
PPTX
Installing JDK and first java program
sunmitraeducation
 
PPT
Adv. python regular expression by Rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
PDF
Javascript
Vibhor Grover
 
PPT
Introduction to c#
OpenSource Technologies Pvt. Ltd.
 
PPTX
Html 5-tables-forms-frames (1)
club23
 
DOCX
Php forms and validations by naveen kumar veligeti
Naveen Kumar Veligeti
 
PPT
Java RMI
Sunil OS
 
DOC
Ad java prac sol set
Iram Ramrajkar
 
PPTX
C language unit-1
Malikireddy Bramhananda Reddy
 
PPTX
Exception handling in JAVA
Kunal Singh
 
PPTX
Data Types, Variables, and Operators
Marwa Ali Eissa
 
JavaScript: Events Handling
Yuriy Bezgachnyuk
 
learnhtmlbyvipuladissanayake-170516061515 (1).pptx
ManuAbraham17
 
For Loops and Nesting in Python
primeteacher32
 
Java naming conventions
Lovely Professional University
 
Introduction to python
Ayshwarya Baburam
 
JavaScript - Chapter 14 - Form Handling
WebStackAcademy
 
Java script -23jan2015
Sasidhar Kothuru
 
Installing JDK and first java program
sunmitraeducation
 
Adv. python regular expression by Rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
Javascript
Vibhor Grover
 
Html 5-tables-forms-frames (1)
club23
 
Php forms and validations by naveen kumar veligeti
Naveen Kumar Veligeti
 
Java RMI
Sunil OS
 
Ad java prac sol set
Iram Ramrajkar
 
Exception handling in JAVA
Kunal Singh
 
Data Types, Variables, and Operators
Marwa Ali Eissa
 

Similar to Advance Java Programs skeleton (20)

DOCX
Exercícios Netbeans - Vera Cymbron
cymbron
 
PPTX
preparecallablepptx__2023_09_11_14_40_58pptx__2024_09_23_11_14_59.pptx
tirthasurani118866
 
PPT
比XML更好用的Java Annotation
javatwo2011
 
DOCX
My java file
Anamika Chauhan
 
DOCX
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
mary772
 
DOCX
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
mccormicknadine86
 
PDF
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
PPT
Executing Sql Commands
leminhvuong
 
PPT
Executing Sql Commands
phanleson
 
PDF
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
PPT
JDBC Tutorial
Information Technology
 
DOC
code for quiz in my sql
JOYITAKUNDU1
 
PDF
Tomcat连接池配置方法V2.1
Zianed Hou
 
PDF
In Java Write a GUI application to simulate writing out a check. The.pdf
flashfashioncasualwe
 
PDF
Write a GUI application to simulate writing out a check. The value o.pdf
fathimaoptical
 
PDF
Xml & Java
Slim Ouertani
 
PDF
Main class --------------------------import java.awt.FlowLayout.pdf
anushkaent7
 
PDF
Java!!!!!Create a program that authenticates username and password.pdf
arvindarora20042013
 
PDF
Clean coding-practices
John Ferguson Smart Limited
 
PDF
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
Exercícios Netbeans - Vera Cymbron
cymbron
 
preparecallablepptx__2023_09_11_14_40_58pptx__2024_09_23_11_14_59.pptx
tirthasurani118866
 
比XML更好用的Java Annotation
javatwo2011
 
My java file
Anamika Chauhan
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
mary772
 
CodeZipButtonDemo.javaCodeZipButtonDemo.java Demonstrate a p.docx
mccormicknadine86
 
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Executing Sql Commands
leminhvuong
 
Executing Sql Commands
phanleson
 
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
JDBC Tutorial
Information Technology
 
code for quiz in my sql
JOYITAKUNDU1
 
Tomcat连接池配置方法V2.1
Zianed Hou
 
In Java Write a GUI application to simulate writing out a check. The.pdf
flashfashioncasualwe
 
Write a GUI application to simulate writing out a check. The value o.pdf
fathimaoptical
 
Xml & Java
Slim Ouertani
 
Main class --------------------------import java.awt.FlowLayout.pdf
anushkaent7
 
Java!!!!!Create a program that authenticates username and password.pdf
arvindarora20042013
 
Clean coding-practices
John Ferguson Smart Limited
 
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
Ad

Recently uploaded (20)

PPTX
Cybersecurity: How to Protect your Digital World from Hackers
vaidikpanda4
 
PPTX
Digital Professionalism and Interpersonal Competence
rutvikgediya1
 
PPTX
DIARRHOEA & DEHYDRATION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
PDF
FULL DOCUMENT: Read the full Deloitte and Touche audit report on the National...
Kweku Zurek
 
PPTX
THE HUMAN INTEGUMENTARY SYSTEM#MLT#BCRAPC.pptx
Subham Panja
 
PPTX
Unlock the Power of Cursor AI: MuleSoft Integrations
Veera Pallapu
 
PPTX
MALABSORPTION SYNDROME: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
PDF
water conservation .pdf by Nandni Kumari XI C
Directorate of Education Delhi
 
PPTX
I INCLUDED THIS TOPIC IS INTELLIGENCE DEFINITION, MEANING, INDIVIDUAL DIFFERE...
parmarjuli1412
 
PPTX
INTESTINAL OBSTRUCTION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
PDF
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
PDF
A guide to responding to Section C essay tasks for the VCE English Language E...
jpinnuck
 
PDF
Right to Information.pdf by Sapna Maurya XI D
Directorate of Education Delhi
 
PPTX
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
PDF
Exploring-the-Investigative-World-of-Science.pdf/8th class curiosity/1st chap...
Sandeep Swamy
 
PPTX
The Future of Artificial Intelligence Opportunities and Risks Ahead
vaghelajayendra784
 
PPTX
10CLA Term 3 Week 4 Study Techniques.pptx
mansk2
 
PPTX
FAMILY HEALTH NURSING CARE - UNIT 5 - CHN 1 - GNM 1ST YEAR.pptx
Priyanshu Anand
 
PPTX
Orientation MOOCs on SWAYAM for Teachers
moocs1
 
PPTX
Rules and Regulations of Madhya Pradesh Library Part-I
SantoshKumarKori2
 
Cybersecurity: How to Protect your Digital World from Hackers
vaidikpanda4
 
Digital Professionalism and Interpersonal Competence
rutvikgediya1
 
DIARRHOEA & DEHYDRATION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
FULL DOCUMENT: Read the full Deloitte and Touche audit report on the National...
Kweku Zurek
 
THE HUMAN INTEGUMENTARY SYSTEM#MLT#BCRAPC.pptx
Subham Panja
 
Unlock the Power of Cursor AI: MuleSoft Integrations
Veera Pallapu
 
MALABSORPTION SYNDROME: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
water conservation .pdf by Nandni Kumari XI C
Directorate of Education Delhi
 
I INCLUDED THIS TOPIC IS INTELLIGENCE DEFINITION, MEANING, INDIVIDUAL DIFFERE...
parmarjuli1412
 
INTESTINAL OBSTRUCTION: NURSING MANAGEMENT.pptx
PRADEEP ABOTHU
 
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
A guide to responding to Section C essay tasks for the VCE English Language E...
jpinnuck
 
Right to Information.pdf by Sapna Maurya XI D
Directorate of Education Delhi
 
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
Exploring-the-Investigative-World-of-Science.pdf/8th class curiosity/1st chap...
Sandeep Swamy
 
The Future of Artificial Intelligence Opportunities and Risks Ahead
vaghelajayendra784
 
10CLA Term 3 Week 4 Study Techniques.pptx
mansk2
 
FAMILY HEALTH NURSING CARE - UNIT 5 - CHN 1 - GNM 1ST YEAR.pptx
Priyanshu Anand
 
Orientation MOOCs on SWAYAM for Teachers
moocs1
 
Rules and Regulations of Madhya Pradesh Library Part-I
SantoshKumarKori2
 
Ad

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