0% found this document useful (0 votes)
14 views50 pages

Adv Java & Web programming Lab msc

The document provides several Java programming examples, including swapping numbers without a third variable, function overloading, exception handling, multithreading, and file attributes retrieval. It also demonstrates GUI elements like menus, submenus, and popup menus, as well as JDBC for database connectivity. Each example includes code snippets and expected outputs to illustrate the concepts effectively.

Uploaded by

P prasad
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
14 views50 pages

Adv Java & Web programming Lab msc

The document provides several Java programming examples, including swapping numbers without a third variable, function overloading, exception handling, multithreading, and file attributes retrieval. It also demonstrates GUI elements like menus, submenus, and popup menus, as well as JDBC for database connectivity. Each example includes code snippets and expected outputs to illustrate the concepts effectively.

Uploaded by

P prasad
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 50

Part1: Adv Java

1. Write a program to swap two numbers without using third variable

import java.util.*;
class Swap
{
public static void main(String a[])
{
System.out.println("Enter the value of x and y");
Scanner sc = new Scanner(System.in);
/*Define variables*/
int x = sc.nextInt();
int y = sc.nextInt();
System.out.println("before swapping numbers: "+x +" "+ y);
x = x + y;
y = x - y;
x = x - y;
System.out.println("After swapping: "+x +" " + y);
}
}

OUTPUT :

Enter the value of x and y


23 43
before swapping numbers: 23 43
After swapping: 43 23
2. Write a program to implement the concept of function overloading
class Adder{
static int add(int a,int b){
return a+b;
}
static int add(int a,int b,int c){
return a+b+c;
}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}

OUTPUT :

22
33

2| P a g e
3. Write a program to implement the exception handling using Java

public class JavaExceptionExample{


public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){
System.out.println(e);
}
//rest code of the program
System.out.println("rest of the code...");
}
}

OUTPUT:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

3| P a g e
4. Write a program to implement the multithreading in using java
// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
} }
// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}

4| P a g e
Output :
Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running

5| P a g e
5. Write a program to get the basic file attributes using java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.sql.Timestamp;
import java.util.Date;
public class GFG {
public static void main(String args[])
throws IOException
{
// path of the file
String path = "C:/Users/elavi/Desktop/GFG_File.txt";
// creating a object of Path class
Path file = Paths.get(path);
// creating a object of BasicFileAttributes
BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
System.out.println("creationTime Of File Is = "+ attr.creationTime());
System.out.println("lastAccessTime Of File Is = "+ attr.lastAccessTime());
System.out.println("lastModifiedTime Of File Is = "+ attr.lastModifiedTime());
System.out.println("size Of File Is = "+ attr.size());
System.out.println("isRegularFile Of File Is = "+ attr.isRegularFile());
System.out.println("isDirectory Of File Is = "+ attr.isDirectory());
System.out.println("isOther Of File Is = "+ attr.isOther());
System.out.println("isSymbolicLink Of File Is = "+ attr.isSymbolicLink());
}
}

6| P a g e
OUTPUT :
creationTime Of File Is : 2021-01-28T05:26:41.5201363Z

lastAccess Time Of File Is : 2021-01-28T05:27:41.5201363Z

lastModifiedTime Of File Is : 2021-01-28T05:26:41.500999Z

size Of File IS : 12

isRegularFile Of File Is: true

isDirectory Of File Is: false

isOther Of File Is : false

isSymbol Link Of File Is : false

7| P a g e
6. Program to demonstrate Menus, sub Menus, Popup Menus, Shortcut Keys, Check
Boxes and Separators in java

Sol 6.1- Menu.

package com.zetcode;

import java.awt.EventQueue;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class SimpleMenuEx extends JFrame {

public SimpleMenuEx() {

initUI();
}
private void initUI() {

createMenuBar();

setTitle("Simple menu");
setSize(350, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

private void createMenuBar() {


8| P a g e
var menuBar = new JMenuBar();
var exitIcon = new ImageIcon("src/resources/exit.png");

var fileMenu = new JMenu("File");


fileMenu.setMnemonic(KeyEvent.VK_F);

var eMenuItem = new JMenuItem("Exit", exitIcon);


eMenuItem.setMnemonic(KeyEvent.VK_E);
eMenuItem.setToolTipText("Exit application");
eMenuItem.addActionListener((event) -> System.exit(0));
fileMenu.add(eMenuItem);
menuBar.add(fileMenu);

setJMenuBar(menuBar);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {

var ex = new SimpleMenuEx();


ex.setVisible(true);
});
}
}
Our example will show a menu with one item. Selecting the Exit menu item we close the
application.
var menuBar = new JMenuBar();
A menubar is created with JMenuBar.

var exitIcon = new ImageIcon("src/resources/exit.png");


An Exit icon is displayed in the menu.

9| P a g e
var fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
A menu object is created with the JMenu class. The menus can be accessed via keyboard as
well. To bind a menu to a particular key, we use the setMnemonic() method. In our case, the
menu can be opened with the Alt+F shortcut.

var eMenuItem = new JMenuItem("Exit", exitIcon);


eMenuItem.setMnemonic(KeyEvent.VK_E);
A menu object consists of menu items. A menu item is created with the JMenuItem class. A
menu item has its own mnemonic. It can be activated with the Alt+F+E key combination.

eMenuItem.setToolTipText("Exit application");
This code line creates a tooltip for the menu item.

eMenuItem.addActionListener((event) -> System.exit(0));


JMenuItem is a special kind of a button component. We add an action listener to it, which
terminates the application.

fileMenu.add(eMenuItem);
menuBar.add(fileMenu);
The menu item is added to the menu object and the menu object is inserted into the menubar.

setJMenuBar(menuBar);
The setJMenuBar() method sets the menubar for the JFrame container.

10| P a g e
Output.

Sol 6.2 - SUB -Menu.


11| P a g e
package com.zetcode;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import java.awt.EventQueue;
public class SubmenuEx extends JFrame {
public SubmenuEx() {
initUI();
}

private void initUI() {

createMenuBar();

setTitle("Submenu");
setSize(360, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

private void createMenuBar() {

var menuBar = new JMenuBar();

var iconNew = new ImageIcon("src/resources/new.png");


var iconOpen = new ImageIcon("src/resources/open.png");
var iconSave = new ImageIcon("src/resources/save.png");
var iconExit = new ImageIcon("src/resources/exit.png");

var fileMenu = new JMenu("File");


var impMenu = new JMenu("Import");

var newsMenuItem = new JMenuItem("Import newsfeed list...");


var bookmarksMenuItem = new JMenuItem("Import bookmarks...");
var importMailMenuItem = new JMenuItem("Import mail...");

12| P a g e
impMenu.add(newsMenuItem);
impMenu.add(bookmarksMenuItem);
impMenu.add(importMailMenuItem);

var newMenuItem = new JMenuItem("New", iconNew);


var openMenuItem = new JMenuItem("Open", iconOpen);
var saveMenuItem = new JMenuItem("Save", iconSave);

var exitMenuItem = new JMenuItem("Exit", iconExit);


exitMenuItem.setToolTipText("Exit application");

exitMenuItem.addActionListener((event) -> System.exit(0));

fileMenu.add(newMenuItem);
fileMenu.add(openMenuItem);
fileMenu.add(saveMenuItem);
fileMenu.addSeparator();
fileMenu.add(impMenu);
fileMenu.addSeparator();
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
var ex = new SubmenuEx();
ex.setVisible(true);
});
}
}
This example creates a submenu and separates the groups of menu items with a menu
separator.
var impMenu = new JMenu("Import");
fileMenu.add(impMenu);
A submenu is just like any other normal menu. It is created the same way. We simply add a
menu to existing menu.
exitMenuItem.setToolTipText("Exit application");
A tooltip is set to the Exit menu item with the setToolTipText() method.

13| P a g e
var newMenuItem = new JMenuItem("New", iconNew);
This JMenuItem constructor creates a menu item with a label and an icon.
fileMenu.addSeparator();
A separator is a horizontal line that visually separates menu items. This way we can group
items into some logical places.
A separator is created with the addSeparator() method.

Output:

Sol 6.3 - POP- UP- Menu.

14| P a g e
package com.zetcode;

import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

public class PopupMenuEx extends JFrame {

private JPopupMenu popupMenu;

public PopupMenuEx() {

initUI();

private void initUI() {

createPopupMenu();

setTitle("JPopupMenu");

setSize(300, 250);

setLocationRelativeTo(null);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

15| P a g e
}

private void createPopupMenu() {

popupMenu = new JPopupMenu();

var maximizeMenuItem = new JMenuItem("Maximize");

maximizeMenuItem.addActionListener((e) -> {

if (getExtendedState() != JFrame.MAXIMIZED_BOTH) {

setExtendedState(JFrame.MAXIMIZED_BOTH);

maximizeMenuItem.setEnabled(false);

});

popupMenu.add(maximizeMenuItem);

var quitMenuItem = new JMenuItem("Quit");

quitMenuItem.addActionListener((e) -> System.exit(0));

popupMenu.add(quitMenuItem);

addMouseListener(new MouseAdapter() {

@Override

public void mouseReleased(MouseEvent e) {

16| P a g e
if (getExtendedState() != JFrame.MAXIMIZED_BOTH) {

maximizeMenuItem.setEnabled(true);

if (e.getButton() == MouseEvent.BUTTON3) {

popupMenu.show(e.getComponent(), e.getX(), e.getY());

});

public static void main(String[] args) {

EventQueue.invokeLater(() -> {

var ex = new PopupMenuEx();

ex.setVisible(true);

});

The example shows a popup menu with two commands. The first command maximizes the
window, the second quits the application.

popupMenu = new JPopupMenu();

JPopupMenu creates a popup menu.

17| P a g e
var maximizeMenuItem = new JMenuItem("Maximize");

maximizeMenuItem.addActionListener((e) -> {

if (getExtendedState() != JFrame.MAXIMIZED_BOTH) {

setExtendedState(JFrame.MAXIMIZED_BOTH);

maximizeMenuItem.setEnabled(false);

});

A popup menu consists of JMenuItems. This item will maximize the frame. The
getExtendedState() method determines the state of the frame. The available states are:
NORMAL, ICONIFIED, MAXIMIZED_HORIZ, MAXIMIZED_VERT, and
MAXIMIZED_BOTH. Once the frame is maximized, we disable the menu item with
setEnabled() method.

popupMenu.add(quitMenuItem);

The menu item is inserted into the popup menu with add().

addMouseListener(new MouseAdapter() {

@Override

public void mouseReleased(MouseEvent e) {

if (getExtendedState() != JFrame.MAXIMIZED_BOTH) {

maximizeMenuItem.setEnabled(true);

18| P a g e
if (e.getButton() == MouseEvent.BUTTON3) {

popupMenu.show(e.getComponent(), e.getX(), e.getY());

});

The popup menu is shown where we clicked with the mouse button. The getButton() method
returns which, if any, of the mouse buttons has changed state.

MouseEvent.BUTTON3 enables the popup menu only for the right mouse clicks. We enable
the maximize menu item once the window is not maximized.

Output:

7. Program to demonstrate JDBC in java


19| P a g e
//STEP 1. Import required packages

import java.sql.*;

public class FirstExample {

// JDBC driver name and database URL

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

static final String DB_URL = "jdbc:mysql://localhost/EMP";

// Database credentials

static final String USER = "username";

static final String PASS = "password";

public static void main(String[] args) {

Connection conn = null;

Statement stmt = null;

try{

//STEP 2: Register JDBC driver

Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection

System.out.println("Connecting to database...");

conn = DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Execute a query

System.out.println("Creating statement...");

20| P a g e
stmt = conn.createStatement();

String sql;

sql = "SELECT id, first, last, age FROM Employees";

ResultSet rs = stmt.executeQuery(sql);

//STEP 5: Extract data from result set

while(rs.next()){

//Retrieve by column name

int id = rs.getInt("id");

int age = rs.getInt("age");

String first = rs.getString("first");

String last = rs.getString("last");

//Display values

System.out.print("ID: " + id);

System.out.print(", Age: " + age);

System.out.print(", First: " + first);

System.out.println(", Last: " + last);

//STEP 6: Clean-up environment

rs.close();

stmt.close();

conn.close();

}catch(SQLException se){

//Handle errors for JDBC

21| P a g e
se.printStackTrace();

}catch(Exception e){

//Handle errors for Class.forName

e.printStackTrace();

}finally{

//finally block used to close resources

try{

if(stmt!=null)

stmt.close();

}catch(SQLException se2){

}// nothing we can do

try{

if(conn!=null)

conn.close();

}catch(SQLException se){

se.printStackTrace();

}//end finally try

}//end try

System.out.println("Goodbye!");

}//end main

}//end FirstExample

22| P a g e
Output:

Now let us compile the above example as follows −

C:\>javac FirstExample.java

C:\>

When you run FirstExample, it produces the following result −

C:\>java FirstExample

Connecting to database...

Creating statement...

ID: 100, Age: 18, First: Zara, Last: Ali

ID: 101, Age: 25, First: Mahnaz, Last: Fatma

ID: 102, Age: 30, First: Zaid, Last: Khan

ID: 103, Age: 28, First: Sumit, Last: Mittal

C:\>

8. Program to demonstrate Servlets in java

23| P a g e
8.1 Creating the index.html page

For the sake of simplicity, this page will just have a button invoke life cycle. When you will
click this button it will call LifeCycleServlet (which is mapped according to the entry in
web.xml file).

<html>
<form action="LifeCycleServlet">
<input type="submit" value="invoke life cycle servlet">
</form>
</html>

Creating the Servlet (FirstServlet)

Now, its time to create the LifeCycleServlet which


implements init(), service() and destroy() methods to demonstrate the lifecycle of a Servlet.

// importing the javax.servlet package

// importing java.io package for PrintWriter

import javax.servlet.*;

import java.io.*;

// now creating a servlet by implementing Servlet interface

public class LifeCycleServlet implements Servlet {

ServletConfig config = null;

// init method

public void init(ServletConfig sc)

config = sc;

System.out.println("in init");

// service method

24| P a g e
public void service(ServletRequest req, ServletResponse res)

throws ServletException, IOException

res.setContenttype("text/html");

PrintWriter pw = res.getWriter();

pw.println("<h2>hello from life cycle servlet</h2>");

System.out.println("in service");

// destroy method

public void destroy()

System.out.println("in destroy");

public String getServletInfo()

return "LifeCycleServlet";

public ServletConfig getServletConfig()

return config; // getServletConfig

8.2 Creating deployment descriptor (web.xml)

25| P a g e
As discussed in other posts about web.xml file we will just proceed to the creation of it in this
article.

<?xml version="1.0" encoding="UTF=8"?>

<web-app>

<servlet>

<servlet-name>LifeCycleServlet</servlet-name>

<servlet-class>LifeCycleServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>LifeCycleServlet</servlet-name>

<url-pattern>/LifeCycleServlet</url-pattern>

</servlet-mapping>

<session-config>

<session-timeout>

30

</session-config>

</web-app>

26| P a g e
Output:

9. Program to demonstrate JSP in java

27| P a g e
<html>

<head><title>JSPApp</title></head>

<body>

<form>

<fieldset style="width:20%; background-color: #ccffeb;">

<legend><b><i>JSP Application<i><b></legend>

<h3>Current Date and Time is :</h3>

<% java.util.Date d = new java.util.Date();

out.println(d.toString()); %>

</fieldset>

</form>

</body>

</html>

File Name : web.xml

<web-app>

<servlet>

<servlet-name>xyz</servlet-name>

<jsp-file>/test.jsp</jsp-file>

</servlet>

<servlet-mapping>

<servlet-name>xyz</servlet-name>

<url-pattern>/test</url-pattern>

</servlet-mapping>

</web-app>

28| P a g e
Output:

10. Programs to demonstrate Java Beans in java


29| P a g e
Main program : JavaBeans Example

Consider a student class with few properties −


package com.tutorialspoint;
public class StudentsBean implements java.io.Serializable {
private String firstName = null;
private String lastName = null;
private int age = 0;
public StudentsBean() {
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public int getAge(){
return age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(Integer age){
this.age = age;
}
}

10.1 Accessing JavaBeans

30| P a g e
The useBean action declares a JavaBean for use in a JSP. Once declared, the bean becomes a
scripting variable that can be accessed by both scripting elements and other custom tags used
in the JSP. The full syntax for the useBean tag is as follows −

<jsp:useBean id = "bean's name" scope = "bean's scope" typeSpec/>

Here values for the scope attribute can be a page, request, session or application based on your
requirement. The value of the id attribute may be any value as a long as it is a unique name
among other useBean declarations in the same JSP.

Following example shows how to use the useBean action −

<html>

<head>

<title>useBean Example</title>

</head>

<body>

<jsp:useBean id = "date" class = "java.util.Date" />

<p>The date/time is <%= date %>

</body>

</html>

OUTPUT:

The date/time is Thu Sep 30 11:18:11 GST 2010 .

10.2: Accessing JavaBeans Properties

31| P a g e
Along with <jsp:useBean...> action, you can use the <jsp:getProperty/> action to access the get
methods and the <jsp:setProperty/> action to access the set methods. Here is the full syntax −

<jsp:useBean id = "id" class = "bean's class" scope = "bean's scope">

<jsp:setProperty name = "bean's id" property = "property name"

value = "value"/>

<jsp:getProperty name = "bean's id" property = "property name"/>

...........

</jsp:useBean>

The name attribute references the id of a JavaBean previously introduced to the JSP by the
useBean action. The property attribute is the name of the get or the set methods that should be
invoked.

Following example shows how to access the data using the above syntax −

<html>

<head>

<title>get and set properties Example</title>

</head>

<body>

<jsp:useBean id = "students" class = "com.tutorialspoint.StudentsBean">

<jsp:setProperty name = "students" property = "firstName" value = "Zara"/>

<jsp:setProperty name = "students" property = "lastName" value = "Ali"/>

<jsp:setProperty name = "students" property = "age" value = "10"/>

</jsp:useBean>

<p>Student First Name:

32| P a g e
<jsp:getProperty name = "students" property = "firstName"/>

</p>

<p>Student Last Name:

<jsp:getProperty name = "students" property = "lastName"/>

</p>

<p>Student Age:

<jsp:getProperty name = "students" property = "age"/>

</p>

</body>

</html>

OUTPUT

Let us make the StudentsBean.class available in CLASSPATH. Access the above JSP. the
following result will be displayed −

Student First Name: Zara

Student Last Name: Ali

Student Age: 10

Part II: Web Tech

33| P a g e
1. Design of the Web pages using various features of HTML and DHTML in java

1.1 : JavaScript in HTML


The following example shows the current date and time with the JavaScript and HTML event
(Onclick).

In this example, we type the JavaScript code in the <head> tag.

<html>
<head>
<title>
DHTML with JavaScript
</title>
<script type="text/javascript">
function dateandtime()
{
alert(Date());
}
</script>
</head>
<body bgcolor="orange">
<font size="4" color="blue">
<center> <p>
Click here # <a href="#" onClick="dateandtime();"> Date and Time </a>
# to check the today's date and time.
</p> </center>
</font>
</body>
</html>

34| P a g e
OUTPUT:

35| P a g e
1.2: JavaScript in DHTML

<html>

<head>

<title>

getElementById.style.property example

</title>

</head>

<body>

<p id="demo"> This text changes color when click on the following different buttons. </p>

<button onclick="change_Color('green');"> Green </button>

<button onclick="change_Color('blue');"> Blue </button>

<script type="text/javascript">

function change_Color(newColor) {

var element = document.getElementById('demo').style.color = newColor;

</script>

</body>

</html>

36| P a g e
Output:

Explanation:

In the above code, we changed the color of a text by using the following syntax:

Statement: document.getElementById('demo').style.property=new_value;.

37| P a g e
2. Client server programming using servlets, ASP and JSP on the server side and java
script

on the client side in java

// To save as "<CATALINA_HOME>\webapps\helloservlet\WEB-INF\src\mypkg\
HelloServlet.java"

package mypkg;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {

@Override

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException {

// Set the response message's MIME type

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

// Allocate a output writer to write the response message into the network socket

PrintWriter out = response.getWriter();

// Write the response message, in an HTML page

try {

out.println("<!DOCTYPE html>");

out.println("<html><head>");

out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");


38| P a g e
out.println("<title>Hello, World</title></head>");

out.println("<body>");

out.println("<h1>Hello, world!</h1>"); // says Hello

// Echo client's request information

out.println("<p>Request URI: " + request.getRequestURI() + "</p>");

out.println("<p>Protocol: " + request.getProtocol() + "</p>");

out.println("<p>PathInfo: " + request.getPathInfo() + "</p>");

out.println("<p>Remote Address: " + request.getRemoteAddr() + "</p>");

// Generate a random number upon each request

out.println("<p>A Random Number: <strong>" + Math.random() + "</strong></p>");

out.println("</body>");

out.println("</html>");

} finally {

out.close(); // Always close the output writer

Compilation

// Compile the source file and place the class in the specified destination directory

d:\<CATALINA_HOME>\webapps\helloservlet\WEB-INF> javac -d classes src\mypkg\


HelloServlet.java

------------------------------------------------------------------------------------------------------------

39| P a g e
2.1 Create a configuration file called "web.xml", and save it under "webapps\
helloservlet\WEB-INF", as follows:

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app version="3.0"

xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

<!-- To save as <CATALINA_HOME>\webapps\helloservlet\WEB-INF\web.xml -->

<servlet>

<servlet-name>HelloWorldServlet</servlet-name>

<servlet-class>mypkg.HelloServlet</servlet-class>

</servlet>

<!-- Note: All <servlet> elements MUST be grouped together and

placed IN FRONT of the <servlet-mapping> elements -->

<servlet-mapping>

<servlet-name>HelloWorldServlet</servlet-name>

<url-pattern>/sayhello</url-pattern>

</servlet-mapping>

</web-app>

----------------------------------------------------------------------------

40| P a g e
The "web.xml" is called web application deployment descriptor. It provides the configuration
options for that particular web application, such as defining the the mapping between URL and
servlet class.

The above configuration defines a servlet named "HelloWroldServlet", implemented in


"mypkg.HelloServlet.class" (written earlier), and maps to URL "/sayhello", where "/" denotes
the context root of this webapp "helloservlet". In other words, the absolute URL for this servlet
is http://hostname:port/helloservlet/sayhello.Servlet_HelloServletURL.png

Take note that EACH servlet requires a pair of <servlet> and <servlet-mapping> elements to
do the mapping, via an arbitrary but unique <servlet-name>. Furthermore, all the <servlet>
elements must be grouped together and placed before the <servlet-mapping> elements (as
specified in the XML schema).

Run the program to get output:

xxx x, xxxx xx:xx:xx xx org.apache.catalina.startup.HostConfig deployDirectory

INFO: Deploying web application directory helloservlet.

Start a web browser (Firefox, IE or Chrome), and issue the following URL (as configured in
the "web.xml"). Assume that Tomcat is running in port number 8080.

http://localhost:8080/helloservlet/sayhello

We shall see the output "Hello, world!"

41| P a g e
Output:

3. Web enabling of databases in java


42| P a g e
Now let’s write a simple Java program just to test out some basic database concepts. Note that
this isn’t a server yet, it’s just a regular Java class.

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

public class Main {

public static void main(String[] args){

try {

System.out.println("Connecting to database.");

String connectionUrl = "jdbc:derby:C:/Users/kevin/Desktop/DerbyDatabase;create=true";

Connection connection = DriverManager.getConnection(connectionUrl);

Statement createPeopleTableStatement = connection.createStatement();

createPeopleTableStatement.executeUpdate("create table People(name


varchar(16), birthYear integer, favoriteColor varchar(16), primary key(name))");

System.out.println("People table created.");

catch (SQLException e) {

e.printStackTrace();

System.out.println("Done.");

}.

43| P a g e
Compile and run

Compile and run this class. Make sure derby.jar is on your classpath when you run this code!

This code does a few things:

The connectionUrl includes three things we care about:

jdbc:derby specifies the type of database we’re connecting to. In this case, we’re connecting to
a Derby database.

C:/Users/kevin/Desktop/DerbyDatabase specifies a location on your local hard drive to use as


a database.

Change this to use a directory on your own computer.

create=true tells Derby to create a database if there isn’t one already.

The Connection connection = DriverManager.getConnection(connectionUrl); line uses our


connectionUrl to connect to (and create) the Derby database.

This line requires derby.jar to be on your classpath.

The createPeopleTableStatement.executeUpdate("create table People(name varchar(16),


birthYear integer, favoriteColor varchar(16), primary key(name))");

line passes SQL into the executeUpdate() function

Output:

but this line creates a table inside our database.

3.1 Let’s add some rows to our table:

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

public class Main {

public static void main(String[] args){

44| P a g e
try {

System.out.println("Connecting to database.");

String connectionUrl =
"jdbc:derby:C:/Users/kevin/Desktop/DerbyDatabase";

Connection connection = DriverManager.getConnection(connectionUrl);

Statement insertRowStatement = connection.createStatement();

insertRowStatement.executeUpdate("insert into People (name, birthYear,


favoriteColor) values('Ada', 1823, 'Green')");

System.out.println("Added Ada to the People table.");

insertRowStatement.executeUpdate("insert into People (name, birthYear,


favoriteColor) values('Grace', 1906, 'Red')");

System.out.println("Added Grace to the People table.");

insertRowStatement.executeUpdate("insert into People (name, birthYear,


favoriteColor) values('Stanley', 2007, 'Pink')");

System.out.println("Added Stanley to the People table.");

catch (SQLException e) {

e.printStackTrace();

System.out.println("Done.");

45| P a g e
Output:

Table: People

Name Birth Year Favorite Color

Ada 1823 Green

Grace 1906 Red

Stanley 2007 Pink

3.2: For now, let’s make our program fetch results from the table: (People)

import java.sql.Connection;

import java.sql.DriverManager;
46| P a g e
import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class Main {

public static void main(String[] args){

try {

System.out.println("Connecting to database.");

String connectionUrl =
"jdbc:derby:C:/Users/kevin/Desktop/DerbyDatabase";

Connection connection = DriverManager.getConnection(connectionUrl);

Statement getRowStatement = connection.createStatement();

ResultSet resultSet = getRowStatement.executeQuery("select * from


People");

while(resultSet.next()){

String name = resultSet.getString("name");

int birthYear = resultSet.getInt("birthYear");

String favoriteColor = resultSet.getString("favoriteColor");

System.out.println(name + " was born in " + birthYear + ". Their favorite color is " +
favoriteColor + ".");

catch (SQLException e) {

e.printStackTrace();

47| P a g e
System.out.println("Done.");

} }

Output:

Table: People

Now our program uses SQL to fetch results from our database, and it loops over those results
to print the information:

Connecting to database.

Ada was born in 1823. Their favorite color is Green.


Grace was born in 1906. Their favorite color is Red.
Stanley was born in 2007. Their favorite color is Pink.

Done.

4. Multimedia effects on web pages design using Flash in java

4.1 main program :

private Animation createAnimation() {

Animation welcome =
48| P a g e
BasicTextAnimation.defaultFade(

label1,

2500,

"Welcome To",

Color.darkGray);

Animation theJGoodiesAnimation = BasicTextAnimation.defaultFade(

label1,

3000,

"The JGoodies Animation",

Color.darkGray);

Animation description =

BasicTextAnimations.defaultFade(

label1,

label2,

2000,

-100,

"An open source framework|" +

"for time-based|real-time animations|in Java.",

Color.darkGray); ... } ... }

4.2 Sub program :

Animation all =

Animations.sequential(new Animation[] {

Animations.pause(1000),
49| P a g e
welcome,

Animations.pause(1000),

theJGoodiesAnimation,

Animations.pause(1000),

description,

Animations.pause(1000),

features,

Animations.pause(1000),

featureList,

Animations.pause(1500),

});

Output:

50| P a g e

You might also like