Professional Documents
Culture Documents
INSTITUTE OF TECHNOLOGY
SCHOOL OF COMPUTING
DEPARTMENT OF
INFORMATION TECHNOLOGY
Group ASSIGNMENT
ADVANCED PROGRAMING
LAB DOCUMENTATION ASSIGNMENT
Name ID NO
1. Alehgn Manaye…………………………………. TER/1302/10
2. Almaz Atanaw ………………………………….. TER/1305/10
3. Amare Malede ………………………………….. TER/1306/10
4. Yabisira kibretu …………………………………. TER/1298/10
5. Afomia Alemeye ……………………………………TER/1301/10
SECTION A
Chapter one
1. Graphical user interface and
data base connectivety
Lab exercise documentation
num1 = Float.parseFloat(jTextField1.getText());
num2 = Float.parseFloat(jTextField2.getText());
result = num1+num2;
jTextField3.setText(String.valueOf(result));
//clear button
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
}
GUI Calculator
The operators +,-,*,/,% shoud be set at operator textfield and
1,2,3,4,5,6,7,8,9,0 and . should be set at Num1 or Num2 textfield.Num1
textfield should be filled first and then the operator textfield and finally
the Num2 textfield.
• //code for each button
• private void btn1ActionPerformed(java.awt.event.ActionEvent
evt)
• {
• String str=null;
• if(txtop.getText().equals(""))
• { str = txtnum1.getText() + btn1.getText();
• txtnum1.setText(str);
• } else
• { str= txtnum2.getText() + btn1.getText();
• txtnum2.setText(str);
• }
• }
• private void btn2ActionPerformed(java.awt.event.ActionEvent
evt)
• {
• String str=null;
• if(txtop.getText().equals(""))
• { str = txtnum1.getText() + btn2.getText();
• txtnum1.setText(str);
• } else
• { str= txtnum2.getText() + btn2.getText();
• txtnum2.setText(str);
• }
• }
• private void btn3ActionPerformed(java.awt.event.ActionEvent
evt)
• {
• String str=null;
• if(txtop.getText().equals(""))
• { str = txtnum1.getText() + btn3.getText();
• txtnum1.setText(str);
• } else
• { str= txtnum2.getText() + btn3.getText();
• txtnum2.setText(str);
• }
• }
• private void btn4ActionPerformed(java.awt.event.ActionEvent
evt)
• {
• String str=null;
• if(txtop.getText().equals(""))
• { str = txtnum1.getText() + btn4.getText();
• txtnum1.setText(str);
• } else
• { str= txtnum2.getText() + btn4.getText();
• txtnum2.setText(str);
• }
• }
• private void btn5ActionPerformed(java.awt.event.ActionEvent
evt)
• {
• String str=null;
• if(txtop.getText().equals(""))
• { str = txtnum1.getText() + btn5.getText();
• txtnum1.setText(str);
• } else
• { str= txtnum2.getText() + btn5.getText();
• txtnum2.setText(str);
• }
• } private void btn7ActionPerformed(java.awt.event.ActionEvent
evt)
• {
• String str=null;
• if(txtop.getText().equals(""))
• { str = txtnum1.getText() + btn7.getText();
• txtnum1.setText(str);
• } else
• { str= txtnum2.getText() + btn7.getText();
• txtnum2.setText(str);
• }
• } private void btn8ActionPerformed(java.awt.event.ActionEvent
evt)
• {
• String str=null;
• if(txtop.getText().equals(""))
• { str = txtnum1.getText() + btn8.getText();
• txtnum1.setText(str);
• } else
• { str= txtnum2.getText() + btn8.getText();
• txtnum2.setText(str);
• }
• }
•
• private void btn9ActionPerformed(java.awt.event.ActionEvent
evt)
• {
• String str=null;
• if(txtop.getText().equals(""))
• { str = txtnum1.getText() + btn9.getText();
• txtnum1.setText(str);
• } else
• { str= txtnum2.getText() + btn9.getText();
• txtnum2.setText(str);
• }
• } private void btn0ActionPerformed(java.awt.event.ActionEvent
evt)
• {
• String str=null;
• if(txtop.getText().equals(""))
• { str = txtnum1.getText() + btn0.getText();
• txtnum1.setText(str);
• } else
• { str= txtnum2.getText() + btn0.getText();
• txtnum2.setText(str);
• }
• }
• private void
btndotActionPerformed(java.awt.event.ActionEvent evt)
• {
• String str;
• if(txtop.getText().equals(""))
• {
• str = txtnum1.getText() + btndot.getText();
• txtnum1.setText(str);
• btndot.setEnabled(false);
• }
• else
• {
• str = txtnum2.getText() + btndot.getText();
• txtnum2.setText(str);
• btndot.setEnabled(false);
• }
•
• }
• private void btnaddActionPerformed(java.awt.event.ActionEvent
evt)
• {
•
if(txtnum1.getText().equals(""))JOptionPane.showMessageDialog(
null," Enter value in the first textfield");
• else{
• txtop.setText("+");
• btndot.setEnabled(true);
• }
• }
• private void btnsubtActionPerformed(java.awt.event.ActionEvent
evt)
• {
•
if(txtnum1.getText().equals(""))JOptionPane.showMessageDialog(
null," Enter value in the first textfield");
• else{
• txtop.setText("-");
• btndot.setEnabled(true);
• }
• } private void
btnmultActionPerformed(java.awt.event.ActionEvent evt) {
•
if(txtnum1.getText().equals(""))JOptionPane.showMessageDialog(
null," Enter value in the first textfield");
• else{
• txtop.setText("*");
• btndot.setEnabled(true);
• }
• }
joption pane
import javax.swing.*;
public class UseOptionPanes {
public static void main(String[] args){
//read the users input graphically
String name=JOptionPane.showInputDialog(null,"What is your name");
//ask the user a yes/no question;
int choice=JOptionPane.showConfirmDialog(null, "Do you like cake,"+ name + "?");
//show different response based on answer
if(choice==JOptionPane.YES_OPTION){
JOptionPane.showMessageDialog(null,"Of course!,who doesn't?");
}
else{//choice==NO_OPTION or CANCEL_OPTION
JOptionPane.showMessageDialog(null, "we'll have to agree to disagree");}}}
===================================================
joptionPane withnumbers
import javax.swing.*;
public class OptionPanes2 {
public static void main(String[] arg){
String ageText=JOptionPane.showInputDialog(null,"How old are you");
int age=Integer.parseInt(ageText);
String moneyText=JOptionPane.showInputDialog(null,"How much money do you
have?");
double money=Double.parseDouble(moneyText);
JOptionPane.showMessageDialog(null,"If you double your money each year,\n"
+"you will have " +(money*32)+ "birr at age "+ (age+5)+"!"); }}
javaframe exersice
import java.awt.*; // for Dimension
import javax.swing.*; // for GUI components
public class SampleFrame {
public static void main(String[] args){
JFrame frame=new JFrame();
frame.setVisible(true);
frame.setForeground(Color.red);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(new Point(10,50));
frame.setSize(new Dimension(300,120));
frame.setTitle("A frame"); } }
buttons
=============================
importjava.awt.*;
importjavax.swing.*;
public classComponentsExample {
public static voidmain(String[] args) {
JFrame frame = newJFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(newDimension(300, 100));
frame.setTitle("A frame");
JButton button1 = newJButton();
button1.setText("I'm a button.");
button1.setBackground(Color.BLUE);
frame.add(button1);
JButton button2 = newJButton();
button2.setText("Click me!");
button2.setBackground(Color.RED);
frame.add(button2);
frame.setVisible(true); }}
==============================
borderlayout
=============================
importjava.awt.*;
importjavax.swing.*;
public classBorderLayoutExample {
public static voidmain(String[] args) {
JFrame frame = newJFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(newDimension(210, 200));
frame.setTitle("Run for the border");
frame.setLayout(newBorderLayout());
frame.add(newJButton("north"), BorderLayout.NORTH);
frame.add(newJButton("south"), BorderLayout.SOUTH);
frame.add(newJButton("west"), BorderLayout.WEST);
frame.add(newJButton("east"), BorderLayout.EAST);
frame.add(newJButton("center"), BorderLayout.CENTER);
frame.setVisible(true); } }
compositelayout
importjava.awt.*;
importjavax.swing.*;
public classTelephone {
public static voidmain(String[] args) {
JFrame frame = newJFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(newDimension(250, 200));
frame.setTitle("Telephone");
frame.setLayout(newBorderLayout());
// main phone buttons
JPanel centerPanel = newJPanel(newGridLayout(4, 3));
for(inti = 1; i <= 9; i++) {
centerPanel.add(newJButton("" + i)); }
centerPanel.add(newJButton("*"));
centerPanel.add(newJButton("0"));
centerPanel.add(newJButton("#"));
frame.add(centerPanel, BorderLayout.CENTER);
// south status panel
JPanel southPanel = newJPanel(newFlowLayout());
southPanel.add(newJLabel("Number to dial: "));
southPanel.add(newJTextField(10));
frame.add(southPanel, BorderLayout.SOUTH);
frame.setVisible(true); }}
chapter two
2. applet
If it’s drawn on the screen, then java.awt.Graphics is probably involved!
Since you may want to use many classes from the java.awt package, simply import them all by
using * as:
import java.awt.*;
Example
Importjavax.swing.JApplet;
importjava.awt.Graphics;
publicclassMyFirstAppletextendsJApplet
{
//declarevariablesher publicvoidinit()
//datainitializationgoeshere
} public void paint( Graphics g )
{
g.drawstring(“This is my first applet code”, 30,50);
// other code goes here
}
}
<HTML>
<HEAD>
<TITLE>TitleName</TITLE>
</HEAD>
<BODY>
<APPLET>
CODE = Classname.class
CODEBASE = . directory of class file
WIDTH = 50 width of window in pixels
HEIGHT = 50 height of window in pixels
</APPLET>
</BODY>
</HTML>
// The method that will be automatically called when the applet is started
public void init()
{
// It is required but does not need anything.
}
// The standard method that you have to use to paint things on screen
// This overrides the empty Applet method, you can't called it "display" for example.
import java.awt.*;
import javax.swing.JApplet;
public class DrawExample extends Applet
{
bgColor = Color.blue;
}
public void stop()
{
}
g.setColor(weirdColor);
// a circle (int x, int y, int width, int height,int startAngle, int arcAngle);
// ovals are also possible this way.
g.fillArc(120,120,60,60,0,360);
g.setColor(Color.yellow);
// Draw a line (int x1, int y1, int x2, int y2)
g.drawLine(140,140,160,160);
// reset the color to the standard color for the next time the applets paints
// an applet is repainted when a part was'nt visible anymore
// happens most often because of browser minimizing or scrolling.
g.setColor(Color.black);
}
Chapter tree
3. Servlet
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
// ExtendHttpServlet class
public class myfirstservletpage extends HttpServlet {
out.print("<a
href=\"http://www.google.co.za\">google</a>");out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
} }
Exmple2
/ Import required java libraries
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
public class Formdatausinggetmethod extends HttpServlet {
*/
throwsServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try {
out.print( "<html>");
out.print("<body bgcolor=pink");
out.print("<br>");
out.print("</form>");
String fname=null,sname=null,submit=null;
fname=request.getParameter(“first_name”);
sname=request.getParameter(“second_name”);
submit=request.getParameter(“submit”);
if(submit!=null)
out.print( "<h1 align=center> Using GET Method to Read Form Data </h1>");
out.print("<ul>");
out.print("</ul>");
out.print("</body></html>");
} finally {
out.close();
Below is Formdatacheckbox.java servlet program to handle input given by web browser for
checkbox button.
String course1=null,course2=null,course3=null,submit=null;
Course1=request.getParameter(“java”);
Course2=request.getParameter(“php”);
Course3=request.getParameter(“c++”);
submit=request.getParameter(“submit”);
if(submit!=null)
out.print("<ul>");
if(course1!=null) out.print("<li><b>”+course1+”</b></li>”);
if(course2!=null) out.print("<li><b>”+course2+”</b></li>”);
if(course3!=null) out.print("<li><b>”+course3+”</b></li>”);
out.print("</ul>");
out.print("</body></html>");
} finally {
out.close();
}
}
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
try {
if(submit!=null&&courses!=null)
{
out.print("Selected course(s) is/are:");
out.print("<ul>");
for(inti=0; i<courses.length; i++)
out.print("<li>"+(courses[i])+”</li>”);
out.print("</ul>");
}else
out.print("<p><font color=red>Please select course</font></p>");
out.print("</body></html>");
} finally {
out.close();
}
}
}
Let we have a database called stud and table dept1 (with fields did and dname)
In this program we are going to fetch the data from the database table to our java servlet pages.
Create a class named as viewdepartment.java and database called studentregistrationdb (user
name= stud and password=stud) table name department (did,dname)
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
importjava.sql.*;
public class viewdepartment extends HttpServlet {
Connection con=null; Statement stmt=null; ResultSet rs=null;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
out.print("<html>");
out.print("<head>");
out.print("<title>Servlet database connection</title>");
out.print("</head>");
out.print("<body>");
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "stud", "stud");
stmt=con.createStatement();
String sql=”select * from department”;
rs=stmt.executeQuery(sql);
while(rs.next())
{ out.print("<tr> ");
out.print("<td>"+rs.getString(“did”) + "</td><td>" +rs.getString(“dname”)+"</td>" );
out.print("</tr> ");
}
out.print ("</table>");
out.print ("</body></html>");
}catch(SQLException e){
out.print(e.getMessage());
}
}//end of processRequest
} //end of class
To make our program working we need to make one html form in which we will have two
fields, one is for the department name and the other one is for entering the department id. And
we will have the submit button, clicking on which the values will be passed to the the database
server.
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
importjava.sql.*;
public class registerdepartment extends HttpServlet {
Connection con; PreparedStatement ps; ResultSet rs;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
out.print(" <html><head>");
out.print("<title>Department Registration Form</title></head>");
out.print("<body>");
out.print("<form method=post action= registerdepartment.java >");
out.print(" Department ID: <input type=text name=did size=20 required /><br>");
out.print(" Department Name: <input type=text name=dname size=20 required /><br>");
out.print("<input type=submit name=save value=Save / ><input type=reset value=clear>");
out.print("</form>");
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "stud", "stud");
String id = request.getParameter("did");
String name = request.getParameter("dname");
String save = request.getParameter("save");
if(save!=null){
ps = con.prepareStatement("insert into department values(?,?)");
ps.setString(1,id);
pt.setString(2,name);
int i = ps.executeUpdate();
if(i>0)
out.print("Record has been inserted");
else
out.printl("Failed to insert the data");
}
out.println("</body></html>");
publicclassregisterdepartmentextendsHttpServlet{ Connectioncon;PreparedStatem
entps;ResultSetrs;
protectedvoidprocessRequest(HttpServletRequestrequest,HttpServletResponseresp
onse)
throwsServletException,IOException{ response.setContentType("text/html");
PrintWriterout=response.getWriter(); try{ out.print(""); out.print(""); out.print("
"); out.print(""); out.print("DepartmentID:
"); out.print("DepartmentName:
"); out.print(""); out.print("
"); DriverManager.registerDriver(neworacle.jdbc.driver.OracleDriver());
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","stud","
stud"); Stringid=request.getParameter("did");
Stringname=request.getParameter("dname");
Stringsave=request.getParameter("save"); if(save!=null)
{ ps=con.prepareStatement("insertintodepartmentvalues(?,?)");16
ps.setString(1,id); pt.setString(2,name); inti=ps.executeUpdate(); if(i>0)
out.print("Recordhasbeeninserted"); else out.printl("Failedtoinsertthedata"); }
out.println("
"); }catch(SQLExceptione){ out.println(e.getMessage()); } }//endofprocessRequestmethod }//endofclass
Chapter 4
4. Jsp
<html><head>
<title>JSP Page</title>
<body bgcolor=”pink”>
Hello World! <br/>
<h1>Welcome to JSP programming
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</h1>
<%
int x=3,y=8,z=x+y;
%>
<p>
The sum of <%=x%> and <%=y%> is <%=z%>
Today's date: <%= (new java.util.Date()) %>
</p>
</body>
</html>
import java.io.*;
1 import javax.servlet.*;
2 import javax.servlet.http.*;
3
4 public class ...Servlet extends HttpServlet {
5
6 // Runs when the servlet is loaded onto the server.
7 public void init() {
8 ......
9 }
10
11 // Runs on a thread whenever there is HTTP GET request
12 // Take 2 arguments, corresponding to HTTP request and response
13 public void doGet(HttpServletRequest request, HttpServletResponse
14 response)
15 throws IOException, ServletException {
16
17 // Set the MIME type for the response message
18 response.setContentType("text/html");
19 // Write to network
20 PrintWriter out = response.getWriter();
21
22 // Your servlet's logic here
23 out.println("<html>");
24 out.println( ...... );
25 out.println("</html>");
26 }
27
28 // Runs as a thread whenever there is HTTP POST request
29 public void doPost(HttpServletRequest request, HttpServletResponse
30 response)
31 throws IOException, ServletException {
32 // do the same thing as HTTP GET request
33 doGet(request, response);
34 }
35
36 // Runs when the servlet is unloaded from the server.
37 public void destroy() {
38 ......
39 }
40
41 // Other instance variables and methods
}
Java servlet produces HTML
<html>
<head>
<title>Reading HTML Request Parameters</title>
</head>
<body>
<h3>Choose course(s):</h3>
<form method="get">
<input type="checkbox" name="course" value="OOP">OOP
<input type="checkbox" name="course" value="C++">C++
<input type="checkbox" name="course" value="PHP">PHP
<input type="submit" value="select">
</form>
<%
String[] arr = request.getParameterValues("course");
if (arr != null) {
%>
<h3>You have selected cours(s):</h3>
<ul>
<%
for (int i = 0; i < arr.length; ++i) {
%>
<li><%= arr[i] %></li>
<%
}
%>
</ul>
<a href="<%= request.getRequestURI() %>">BACK</a> //refresh or reload page
<%
}
%>
</body>
</html>
Browse the JSP pa
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "studentdb",
"studentdb");
stmt=con.createStatement();
rs = stmt.executeQuery(sql);
if(!rs.next()) {%>
<h1> No user registered </h1>
<% rd=request.getRequestDispatcher("Login.jsp");
rd.include(request, response);
}else{ // else---1
rs = stmt.executeQuery(sql);
while(rs.next()){
if (uname.equals(rs.getString(“User_Name”))&&
upass.equals(rs.getString(“Password”))&&
rs.getString(“Status”).equals(“Active”)
{
if(rs.getString(User_Type).equals(“Admin”) ){
rd=request.getRequestDispatcher("Adminpage.jsp");
rd.forward(request, response);
}
else if(rs.getString(User_Type).equals (“coursemanager”)){
rd=request.getRequestDispatcher(“CourseManagerpage.jsp");
rd.forward(request, response);
}
else if(rs.getString(User_Type).equals (“resultmanager”)){
rd=request.getRequestDispatcher(“ResultManagerpage.jsp");
rd.forward(request, response);
}else{
%>
<h1> Try to enter correct user name or password </h1>
<% rd=request.getRequestDispatcher("Login.jsp");
rd.include(request, response);
}
} // if---3
}//while
}Catch(SQLException e){
out.print(e.getMessage());
}
} //if ---2
}// else---1
%>
</body></html>
<body>
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
"studentregistrationdb", " studentregistrationdb ");
stmt=con.createStatement();
rs = stmt.executeQuery(sql);
%>
<hr>
</tr>
<%
}
%>
</table>
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
"studentregistrationdb", " studentregistrationdb ");
String id = request.getParameter("deptid");
String name = request.getParameter("deptname");
int i = pst.executeUpdate();
if(i!=0){
%>
<h1>Record has been inserted </h1>
<%
}
else{
%>
<h1>failed to insert the data</h1>
<% }
pst.close();
con.close();
}catch(SQLException e){}
%>
</body></html>