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