You are on page 1of 35

DEBREMARKOS UNIVERSITY

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

>>>Data validations for txt1 and txt2 textfield


//import javax.swing.JOptionPane; at the top of the class
//Letter validation,Right click on txt1,then point to Events then point to Key
finally select KeyPessed
private void txt1KeyPressed(java.awt.event.KeyEvent evt) {
if( (evt.getKeyChar() >= 'a' && evt.getKeyChar() <= 'z')||(evt.getKeyChar() >= 'A'
&& evt.getKeyChar() <= 'Z'))
txt1.setEditable(true);
else {
txt1.setEditable(false);
JOptionPane.showMessageDialog(null," please enter only letter");
txt1.setEditable(true);
}
}
//Code for clear button
private void btnclearActionPerformed(java.awt.event.ActionEvent evt)
{
txt1.setText(“ ”);
txt2.setText(“ “);
txt3.setText(“ “);
txt4.setText(“ “);
}
Second Example
Addition of two numbers
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt){

// First we define float variables.

float num1, num2, result;

// We have to parse the text to a type float.

num1 = Float.parseFloat(jTextField1.getText());

num2 = Float.parseFloat(jTextField2.getText());

// Now we can perform the addition.

result = num1+num2;

// We will now pass the value of result to jTextField3.

// At the same time, we are going to

// change the value of result from a float to a string.

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>

// required when you create an applet


import javax.swing.JApplet;

// required to paint on screen


import java.awt.Graphics;

// the start of an applet - HelloWorld will be the executable class


// Extends applet means that you will build the code on the standard Applet class
public class HelloWorld extends Applet
{

// The method that will be automatically called when the applet is started
public void init()
{
// It is required but does not need anything.
}

// This method gets called when the applet is terminated


// That's when the user goes to another page or exits the browser.
public void stop()
{
// no actions needed here now.
}

// 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.

public void paint(Graphics g)


{
//method to draw text on screen
// String first, then x and y coordinate.
g.drawString("This is my first Applet code",20,20);
g.drawString("Hellow World",20,40);

import java.awt.*;
import javax.swing.JApplet;
public class DrawExample extends Applet
{

// Specify variables that will be needed everywhere, anytime here


// The font variable
Font bigFont;

// The colors you will use


Color redColor;
Color weirdColor;
Color bgColor;

public void init()


{
// Here we will define the varibles further
// Will use Arial as type, 16 as size and bold as style
// Italic and Plain are also available
bigFont = new Font("Arial",Font.BOLD,16);

// Standard colors can be named like this


redColor = Color.red;

// lesser known colors can be made with R(ed)G(reen)B(lue).


weirdColor = new Color(60,60,122);

bgColor = Color.blue;

// this will set the backgroundcolor of the applet


setBackground(bgColor);

}
public void stop()
{
}

// now lets draw things on screen


public void paint(Graphics g)
{
// tell g to use your font
g.setFont(bigFont);
g.drawString("Shapes and Colors",80,20);

// Now we tell g to change the color


g.setColor(redColor);

// This will draw a rectangle (xco,yco,xwidth,height);


g.drawRect(100,100,100,100);

// This will fill a rectangle


g.fillRect(110,110,80,80);

// change colors again

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 {

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// TODO output your page here
out.print("<html>");
out.print("<head>");
out.print("<title>Java servlet</title>");
out.print("</head>");
out.print("<body>");

out.print("<h1> This is my first java servlet program</h1>");

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 {

/* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.

*/

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throwsServletException, IOException {

response.setContentType("text/html;charset=UTF-8");

PrintWriter out = response.getWriter();

try {

// TODO output your page here

out.print( "<html>");

out.print( "<head><title> Using GET Method to Read Form Data </title></head>");

out.print("<body bgcolor=pink");

out.print("<form action=Formdatausinggetmethod method=GET>");

out.print("First Name: <input type=text name=first_name required />");

out.print("<br>");

out.print("Second Name: <input type=text name=second_name required />");

out.print("<input type=submit name=submit value=Submit />");

out.print("<input type=Reset value=Reset />");

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("<li><b>First Name</b>: "+fname+”</li>”);

out.print("<li><b>Second Name</b>: "+sname+”</li>”);

out.print("</ul>");

out.print("</body></html>");

} finally {

out.close();

Passing Checkbox Data to Servlet Program


Checkboxes are used when more than one option is required to be selected.

Below is Formdatacheckbox.java servlet program to handle input given by web browser for
checkbox button.

// Import required java libraries


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

public class Formdatacheckbox extends HttpServlet {

/* Processes requests for both HTTP <code>GET</code> and <code>POST</code>


methods
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
throwsServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// TODO output your page here
out.print("<html>");
out.print("<head><title> Reading checkbox data</title></head>");
out.print("<body bgcolor=#f0f0f0>");

out.print("<form action=Formdatacheckbox method=POST>");


out.print("<input type=checkbox name=java value=JAVA checked=checked
/>Java<br>");
out.print("<input type=checkbox name=php value=PHP />PHP<br>");
out.print("<input type=checkbox name=C++ value=C++ />C++<br>");
out.print("<input type=submit name=submit value=’Select Subject’/>");
out.print("<input type=Reset value=Reset/>");
out.print("</form>");

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("<h1 align=center>Selected courses are:</h1>");

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();
}
}

Reading All Form Parameters:


Following is the generic example which uses getParameterValues() method of
HttpServletRequest to read all the available form parameters. This method returns an
Enumeration that contains the parameter names in an unspecified order.

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

public class checkbox extends HttpServlet {

protected void processRequest(HttpServletRequestreq, HttpServletResponse res) throws


ServletException, IOException {

res.setContentType("text/html");
PrintWriter out = res.getWriter();
try {

// TODO output your page here


out.print("<html>");
out.print("<head>");
out.print("<title>Check Box Example</title>");
out.print("</head>");
out.print("<body bgcolor=pink>");
out.print("<form method=post action=checkbox>");
out.print("<h3>Select Courses</h3>");
out.print("<p><input type=checkbox name=course value=JAVA /> Java");
out.print("<p><input type=checkbox name=course value=C++ /> C++ ");
out.print("<p><input type=checkbox name=course value=PHP /> PHP");
out.print("<p><input type=submit name=submit value=Submit /></p>");
out.print("</form> ");
String[] courses;
courses= req.getParameterValues("course");
submit= req.getParameterValues("submit");

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();
}
}
}

Retrieving Data from the table using Statement

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);

out.print("<table border= 2> ");


out.print("<tr> ");
out.print("<td>Department Id </td><td>Department Name </td> ");
out.print("</tr> ");

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

Inserting data from the HTML page to the database


Let we insert record to the table department using servlet web page form.In this program we are
going to make servlet program in which we are going to insert the values in the database table
from the html form.

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.

To accomplish our goal we first have to make a class named as registerdepartment.jave.

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>");

} catch (SQLException e){


out.println(e.getMessage());
}
} //end of processRequest method
}//end of class
Inserting data from the HTML page to the database
Toaccomplishourgoalwefirsthavetomakeaclassnamedasregisterdepartment.jave.
importjava.io.*;
importjavax.servlet.*;
importjavax.servlet. Http.*;
importjava.sql.*;

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>

The Second JSP Example


Create the second jsp web application randomnumber.jsp
1 <html>
2 <head><title>randomnumber JSP</title></head>
3 <body>
4 <%
5 double num = Math.random();
6 if (num > 0.95) {
7 %>
8 <h2>You are lucky!</h2><p>(<%= num %>)</p>
9 <%
10 } else {
11 %>
12 <h2> You can’t win ,Try more </h2><p>(<%= num %>)</p>
13 <%
14 }
15 %>
16 <a href="<%= request.getRequestURI() %>"><h3>Try Again</h3></a>
17 </body>
18 </html>
Revisit Java Servlets

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

Third JSP example - Reading HTML Request Parameters


Enter the following JSP script and save as "checkbox.jsp" in your Jspproject directory.

<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

Page Redirection Example


Assume you have Login.jsp,Adminpage.jsp,CourseManagerpage.jsp,ResultManager.jsp and
database studentdb and user table
//Login.jsp file
<%@page import =” java.sql.*”%>
<html><head><title>Jsp Page redirective</titlt></head><body>
<form method="POST" action="Login.jsp">
<p>Enter your name:<input type=text name="uname" required=” ” ></p>
<p>Enter your password: <input type="password" name="upass" required=” ” ></p>
<input type="submit" value="Submit" > <input type="reset" value="Reset" >
</form>

<% String uname = request.getParameter("un");


String upass = request.getParameter("up");
RequestDispatcher rd;
if(uname!=null && upass!=null){
try{
Connection con; Statement stmt; ResultSet rs;

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "studentdb",
"studentdb");
stmt=con.createStatement();

String sql = "select * from user ";

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>

ncluding jsp or html file and creating link on index.jsp


<html><head><title>Page include</title></head>
<%@include file="csssetting.jsp" %>
<body bgcolor="pink">
<%@include file="header.jsp" %>
<table >
<tr>
<td> <a href="checkbox.jsp"><h3>checkbox</h3></a></td>
<td > <a href="randomnumber.jsp"><h3>Randomnumber</h3></a></td>
</tr>
<tr>
<td > <a href="randomnumber.jsp"> <h3>Randomnumber</h3></a></td>
</tr>
</table>
<%@include file="footer.jsp" %>
</body>
</html>

JSP - Database connection


To start with basic concept, let us create a database called studentregistrationdb, table
department( with fields deptid,deptname) and create few records in the table.

Retrieving data from database:

<body>

<%@ page import = "java.sql.*" %>


<%
try{
Connection con; Statement stmt; ResultSet rs;

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
"studentregistrationdb", " studentregistrationdb ");
stmt=con.createStatement();

String sql = "select * from department ";

rs = stmt.executeQuery(sql);
%>
<hr>

<table border=”1” >


<tr>
<th>Department Id</th>
<th>Department Name</th>
</tr>
<%

while (rs.next()) { %>


<tr>

<td><%= rs.getString(“deptid”) %></td>


<td><%= rs.getString(“deptname”) %></td>

</tr>
<%
}
%>
</table>

<a href="<%= request.getRequestURI() %>"><h3>Back</h3></a>


<%
rs.close();
stmt.close();
con.close();
}catch(SQLException e){
out.print(e.getMessage());
}
%>
</body></html>

Inserting data to database from html form:


<html><head><title>data inserting</title></head><body>
<%@ page import = "java.sql.*" %>

<form method="post" action="Insertingdatatodatabase.jsp">


<p>Enter Dept ID: <input type="text" name="did" required=”” placeholder=”Enter department
id” pattern=”[A-Za-z0-9/]+” ></p>
<p>Enter Dept Name: <input type="text" name="dname" placeholder=”Enter department
name” required=” ” pattern=”[A-Za-z]+” </p>
<p> <input type="submit" value="Save" ></p>
<p> <input type="reset" value="Clear"></p>
</form>
<%
try{
Connection con; PreparedStatement pst;

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");

pst = con.prepareStatement("insert into dept1 values(?,?)");


pst.setString(1,id);
pst.setString(2,name);

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>

You might also like