Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Java

Uploaded by

Kesavan Kesavan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Java

Uploaded by

Kesavan Kesavan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

Advance Java

Ex. No:

Date:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Page No:
Department of IT, AAGAC-VPM
Advance Java

1. CLASSES AND OBJECTS.

PROGRAM:

import java.util.Scanner;
class Box{
int width,height,depth;
Box(int w,int h,int d)
{
width=w;
height=h;
depth=d;
}
Box(int n)
{
width=height=depth=n;
}
int volume(){
return width*height*depth;
}
}
public class BoxModel {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter the Box 1 values:");
w=s.nextInt();
h=s.nextInt();
d=s.nextInt();

System.out.println("Enter the Box 2 values:");


n=s.nextInt();
Box B1=new Box(w,h,d);
Box B2=new Box(n);
vol=B1.volume();

System.out.println("The volume of box 1:"+ B1.volume());

Page No:
Department of IT, AAGAC-VPM
Advance Java

vol=B2.volume();
System.out.println("The volume of box 2:"+ B2.volume());
}
}

Page No:
Department of IT, AAGAC-VPM
Advance Java

OUTPUT:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Ex. No:

Date:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Page No:
Department of IT, AAGAC-VPM
Advance Java

2. IMPLEMENTING CLASSES.

PROGRAM:

import java.util.Scanner;
class Overloading{
int square,rect;
double circle;
void area(int a){
square=a*a;
System.out.println("Area of the square:"+ square);
}
void area(int l,int b){
rect=l*b;
System.out.println("Area of the Rectangle:"+ rect);
}
void area(double r){
double pi=3.14;
circle=pi*r*r;
System.out.println("Area of the Circle:"+ circle);
}
}
class Main{
public static void main(String[] args){
int a,l,b;
double r;
System.out.println("Implementation classes:");
Scanner s=new Scanner(System.in);
System.out.println("Enter the value of Square:");
a=s.nextInt();
System.out.println("Enter the value of Rectangle:");
l=s.nextInt();
b=s.nextInt();
System.out.println("Enter the value of Circle:");
r=s.nextDouble();
Overloading O1=new Overloading();

Page No:
Department of IT, AAGAC-VPM
Advance Java

O1.area(a);
O1.area(l,b);
O1.area(r);
}
}

Page No:
Department of IT, AAGAC-VPM
Advance Java

OUTPUT:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Ex. No:

Date:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Page No:
Department of IT, AAGAC-VPM
Advance Java

3. STRING.

PROGRAM:

import java.util.Scanner;
class StringHandling{
public static void main(String[] args){
String v1,v2,upper,lower,length,app,ins,rev,rep,substr;
int n,a,b,d,e,f,start,end;
char c;
Boolean rm,ew,sw;
System.out.println("String Handling:");
Scanner s=new Scanner(System.in);
System.out.print("Enter the First String:");
v1=s.nextLine();
System.out.print("Enter the Second String:");
v2=s.nextLine();

// Using StringBuffer
StringBuffer l1=new StringBuffer(v1);
StringBuffer l2=new StringBuffer(v2);

// To find the length of string


System.out.println("Length of first string is :" +l1.length());
System.out.println("Length of second string is :" +l2.length());

//Using charAt
System.out.println("Enter the values of CharAt:");
n=s.nextInt();
c=l1.charAt(n);
System.out.println("String CharAt is:"+ c);

//Using regionMatches
rm=v1.regionMatches(1,"form",2,4);
System.out.println(" regionMatches:" + rm);

Page No:
Department of IT, AAGAC-VPM
Advance Java

ew=v1.endsWith("World"); //endsWith and startsWith


System.out.println("The values of endsWith:" + ew);

sw=v2.startsWith("Tech");
System.out.println("The values of startsWith:" + sw);

//upper and lower


upper=v1.toUpperCase();
System.out.println("UpperCase of the String:"+ upper);

lower=v2.toLowerCase();
System.out.println("LowerCase of the String:"+ lower);

//SubString
System.out.println("Enter the value of SubString:");
a=s.nextInt();
b=s.nextInt();
substr=v2.substring(a,b);
System.out.println("Sub String:"+ substr);

// Insert and Delete


System.out.println("Enter the value for Insert:");
d=s.nextInt();
l1.insert(d,"vignesh");
System.out.println("Inserted line is :" +l1);

System.out.println("Enter the value for Delete:");


e=s.nextInt();
f=s.nextInt();
StringBuffer C = l1.delete(e,f);
System.out.println("After deletion :" +C);

app=l1.append(" ").append(l2).toString();
System.out.println("Append of the two Strings:"+ app);
}
}

Page No:
Department of IT, AAGAC-VPM
Advance Java

OUTPUT:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Ex. No:

Date:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Page No:
Department of IT, AAGAC-VPM
Advance Java

4. COLLECTION.

PROGRAM:

import java.util.*;
class Example
{
public static void main(String args[])
{

// creating an array
System.out.println(" CREATING AN ARRAY ");
Scanner sc = new Scanner(System.in);
System.out.print(" Enter the size of array : ");
int n = sc.nextInt();
int[] ar = new int[n];

int i;
System.out.print(" Enter the values for array : ");
for(i=0; i<n; i++)
{
ar[i] = sc.nextInt();
}
System.out.print(" Array elements are : ");
for(i=0; i<n; i++)
{
System.out.print(ar[i] + " " );
}

// converting array into collection


System.out.println(" \n\n CONVERTING ARRAY INTO COLLECTION ");
List<Integer> al = new ArrayList<>();
for(int val : ar)
{
al.add(val);
}

Page No:
Department of IT, AAGAC-VPM
Advance Java

System.out.println(" Converting array into collections : " +al);

// finding minimum element in arraylist


int m = Collections.min(al);
System.out.println(" Minimum element in Array List is : " +m);
System.out.println();

//creating a linked list


System.out.println(" CREATING LINKED LIST ");
LinkedList<Integer> ll = new LinkedList<>();

//adding elements in linkedlist and prints it.


ll.add(20);
ll.add(30);
ll.add(40);
ll.add(50);

System.out.println(" Elements in Linked List is : " +ll);

// finding minimum element in linked list


int m1 = Collections.min(ll);
System.out.println(" Minimum element in Linked List is : " +m1);

//comparing min element from arraylist and linked list


if( m == m1)
System.out.println(" Both minimum elements in arraylist and linkedlist were same");
else
System.out.println(" Both minimum elements in arraylist and linkedlist were not same");

System.out.println();

//converting collection to an array


System.out.println(" CONVERTING COLLECTION INTO ARRAY ");
int s = ll.size();
Integer[] ar1 = ll.toArray(new Integer[s]);

Page No:
Department of IT, AAGAC-VPM
Advance Java

System.out.println(" Converting collection into array is : " +Arrays.toString(ar1));

// finding total and average for the converted array


int tot = 0;
for(i=0; i<ar1.length; i++)
{
tot += ar1[i];
}
System.out.println(" Total of the array is : " +tot);

float avg;
avg = tot/ar1.length;
System.out.println(" Average of the array is : " +avg);
System.out.println();

// creating hashset and adding elements


System.out.println(" CREATING HASHSET AND TREESET ");
HashSet h = new HashSet();
h.add(50);
h.add(70);
h.add(90);
System.out.println(" Elements in the hash set is : " +h);

// creating treeset and adding elements


TreeSet t = new TreeSet();
t.add("Vignesh");
t.add("Vasu");
t.add("GM");
System.out.println(" Elements in the tree set is : " +t);
sc.close();

}
}

Page No:
Department of IT, AAGAC-VPM
Advance Java

OUTPUT:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Ex. No:

Date:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Page No:
Department of IT, AAGAC-VPM
Advance Java

5. DATE AND CALENDAR.

PROGRAM:

import java.util.*;
class DateCompare{
public static void main(String[] args) {

String months[]={"Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct","Nov","Dec"};
Calendar calendar = Calendar.getInstance();

System.out.print("DATE :");
System.out.print(months[calendar.get(Calendar.MONTH)]);
System.out.print(" "+calendar.get(Calendar.DATE)+" ");
System.out.println(calendar.get(Calendar.YEAR));

System.out.print("TIME:");
System.out.print(calendar.get(Calendar.HOUR)+":");
System.out.print(calendar.get(Calendar.MINUTE)+" :");
System.out.println(calendar.get(Calendar.SECOND));

//Static Time Update


calendar.set(Calendar.HOUR,12);
calendar.set(Calendar.MINUTE,30);
calendar.set(Calendar.SECOND,46);

System.out.print("UPDATED TIME IS:");


System.out.print(calendar.get(Calendar.HOUR)+":");
System.out.print(calendar.get(Calendar.MINUTE)+" :");
System.out.println(calendar.get(Calendar.SECOND));

// Create two Date objects


Date date1 = new Date();
Date date2 = new Date(date1.getTime() + 185760000);

Page No:
Department of IT, AAGAC-VPM
Advance Java

// After
boolean isAfter = date1.after(date2);
System.out.println("Date 1 is after date 2: " + isAfter);

// Before
boolean isBefore = date1.before(date2);
System.out.println("Date 1 is before date 2: " + isBefore);

// Equal
boolean isEqual = date1.equals(date2);
System.out.println("Date 1 is equal to date 2: " + isEqual);

// Compare
int compare = date1.compareTo(date2);
System.out.println("Date 1 is compareTo date 2:" + compare);

}
}

Page No:
Department of IT, AAGAC-VPM
Advance Java

OUTPUT:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Ex. No:

Date:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Page No:
Department of IT, AAGAC-VPM
Advance Java

6. PACKAGES.

PROGRAM:

package Mypack;

public class Balance {


String name;
int accountNumber;
double bal;

public Balance(String n, int a, double b) {


name = n;
accountNumber = a;
bal = b;
}

public void show() {


if (bal < 0) {
System.out.println("Warning: Balance is negative.");
}
else {
System.out.println("Your Account No is :"+ accountNumber);
System.out.println(name + ": $" + bal);
}
}

public void deposit(double amount) {


if (amount > 0) {
bal += amount;
System.out.println("Your Account No is :"+ accountNumber);
System.out.println("Deposited: $" + amount);
}
else {
System.out.println("Invalid deposit amount");
}

Page No:
Department of IT, AAGAC-VPM
Advance Java

public void withdraw(double amount) {


if (amount > 0 && amount <= bal) {
bal -= amount;
System.out.println("Your Account No is :"+ accountNumber);
System.out.println("Withdrawn: $" + amount);
}
else {
System.out.println("Invalid withdrawal amount");
}
}
}

import Mypack.*;
import java.util.Scanner;
public class BankingApp {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter your name: ");


String name = sc.nextLine();

System.out.print("Enter your Account number: ");


int accountNumber = sc.nextInt();

System.out.print("Enter initial balance: ");


double initialBalance = sc.nextDouble();

Balance account = new Balance(name, accountNumber, initialBalance);

while (true) {
System.out.println("\nDo you want to deposit or withdraw?:");

Page No:
Department of IT, AAGAC-VPM
Advance Java

System.out.println("1. Deposit");
System.out.println("2. Withdraw");
System.out.println("3. Check Balance");
System.out.println("4. Exit");

System.out.print("Choose an option: ");


int choice = sc.nextInt();

switch (choice) {
case 1:
System.out.print("Enter deposit amount: ");
double depositAmount = sc.nextDouble();
account.deposit(depositAmount);
break;
case 2:
System.out.print("Enter withdrawal amount: ");
double withdrawalAmount = sc.nextDouble();
account.withdraw(withdrawalAmount);
break;
case 3:
account.show();
break;
case 4:
System.out.println("Exiting...");
sc.close();
return;
default:
System.out.println("Invalid option. Please try again.");
}
}
}
}

Page No:
Department of IT, AAGAC-VPM
Advance Java

OUTPUT:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Ex. No:

Date:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Page No:
Department of IT, AAGAC-VPM
Advance Java

7. EXCEPTION HANDLING.

PROGRAM:

import java.util.Scanner;
class ExHandling{
public static void main(String[] args) {
int a=args.length;
Scanner s=new Scanner(System.in);
System.out.println("value of a is : "+a);
try{
if(a==0){
int b=24;
a=b/(b-b);
}

if(a==1){
int A[]={1};
A[16]=20;
}

if(a==2){
System.out.println("Enter Array size: ");
int n=s.nextInt();
int[] B=new int[n];
B[17]=15;
}
}

catch(ArithmeticException e){
System.out.println("Do not use zero as a divisor. "+e);
}

catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array size exceeds. "+e);
}

Page No:
Department of IT, AAGAC-VPM
Advance Java

catch(NegativeArraySizeException e ){
System.out.println("Array size can not be negative value. "+e);
}
finally{
System.out.println(" Exceptions Completed. ");
}
}
}

Page No:
Department of IT, AAGAC-VPM
Advance Java

OUTPUT:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Ex. No:

Date:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Page No:
Department of IT, AAGAC-VPM
Advance Java

8. THREADS.

PROGRAM:

class Q {
int n;
boolean valueSet = false;
synchronized int get() {
if(!valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
if(valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}
class Producer implements Runnable {
Q q;
Producer(Q q){
this.q = q;

Page No:
Department of IT, AAGAC-VPM
Advance Java

new Thread(this, "Producer").start();


}
public void run() {

int i = 1;
while(i<=10) {
q.put(i++);
}
}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}
}
}
class PC {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}

Page No:
Department of IT, AAGAC-VPM
Advance Java

OUTPUT:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Ex. No:

Date:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Page No:
Department of IT, AAGAC-VPM
Advance Java

9. JAVA DATABASE CONNECTIVITY (JDBC).

PROGRAM:

import java.sql.*;
public class Ex9a {
public static void main(String args[]) {
try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Database connection details


String url = "jdbc:mysql://localhost:3306/abi";
String user = "root"; // replace with your MySQL username
String password = "Nandhu#34"; // replace with your MySQL password

// Establish connection
Connection con = DriverManager.getConnection(url, user, password);
Statement stmt = con.createStatement();
System.out.println("Created DB Connection....");

// Execute query
ResultSet rs = stmt.executeQuery("SELECT id,name,dept FROM abi11");
ResultSetMetaData rsmd = rs.getMetaData();
int ccount = rsmd.getColumnCount();

// Print column names


for (int i = 1; i <= ccount; i++) {
System.out.print(rsmd.getColumnName(i) + "\t");
}
System.out.println("");

// Print results
while (rs.next()) {
System.out.print(rs.getInt("id") + "\t");
System.out.print(rs.getString("name") + "\t");

Page No:
Department of IT, AAGAC-VPM
Advance Java

System.out.print(rs.getString("dept") + "\t");
// System.out.print(rs.getInt("salary"));
System.out.println();
}

// Close resources
rs.close();
con.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

Page No:
Department of IT, AAGAC-VPM
Advance Java

OUTPUT:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Ex. No:

Date:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Page No:
Department of IT, AAGAC-VPM
Advance Java

10. APPLET.

PROGRAM:

import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleBanner" width=700 height=50>
</applet>
*/
public class SimpleBanner extends Applet implements Runnable {
String msg = " Accept Everything Nothing is Permanent.";
Thread t = null;
int state;
boolean stopFlag;
// Set colors and initialize thread.
public void init() {
setBackground(Color.blue);
setForeground(Color.white);
}
// Start thread
public void start() {
t = new Thread(this);
stopFlag = false;
t.start();
}
// Entry point for the thread that runs the banner
public void run() {
char ch;
// Display banner
for( ; ; ) {
try {
repaint();
Thread.sleep(250);
ch = msg.charAt(0);
msg = msg.substring(1, msg.length());

Page No:
Department of IT, AAGAC-VPM
Advance Java

msg += ch;
if(stopFlag)
break;
} catch(InterruptedException e) {}
}
}
// Pause the banner.
public void stop() {
stopFlag = true;
t = null;
}
// Display the banner.
public void paint(Graphics g) {
g.drawString(msg, 500, 300);
}
}

Page No:
Department of IT, AAGAC-VPM
Advance Java

OUTPUT:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Ex. No:

Date:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Page No:
Department of IT, AAGAC-VPM
Advance Java

11. EVENT HANDLING.

PROGRAM:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*
<applet code = "Text" width=1200 height=1200>
</applet>
*/

public class Text extends Applet implements ActionListener


{
TextField a,b;
double sum;
Button ab;

public void init()


{
Label value1 = new Label("First Number : ", Label.RIGHT);
Label value2 = new Label("Second Number : ",Label.RIGHT);
a = new TextField(10);
b = new TextField(10);
ab = new Button("Add");

add(value1);
add(a);
add(value2);
add(b);
add(ab);

ab.addActionListener(this);

Page No:
Department of IT, AAGAC-VPM
Advance Java

public void actionPerformed(ActionEvent ae)


{
if(ae.getSource() == ab) {
try {
int num1 = Integer.parseInt(a.getText());
int num2 = Integer.parseInt(b.getText());
sum = num1 + num2;
}
catch(NumberFormatException e)
{
sum = 0;
}

repaint();
}
}

public void paint(Graphics g)


{
g.drawString("value 1 is : " +a.getText(),6,60);
g.drawString("value 2 is : " +b.getText(),6,80);
g.drawString("Sum of the numbers is : " +sum,6,120);
}
}

Page No:
Department of IT, AAGAC-VPM
Advance Java

OUTPUT:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Ex. No:

Date:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Page No:
Department of IT, AAGAC-VPM
Advance Java

12. SIMPLE WEB APPLICATIONS.

vote.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//@WebServlet("/vote")
public class vote extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
if (age < 18) {
out.println("<h2>" + name + " is not eligible to vote.</h2>");
} else {
out.println("<h2>" + name + " is eligible to vote.</h2>");
}
out.println("</body></html>");
}
}

Page No:
Department of IT, AAGAC-VPM
Advance Java

Index.html
<!DOCTYPE html>
<html>
<head>
<title>Voting Eligibility Check</title>
</head>
<body>
<h2>Check Voting Eligibility</h2>
<form action="vote" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age" required><br><br>
<input type="submit" value="Check Eligibility">
</form>
</body>
</html>

Page No:
Department of IT, AAGAC-VPM
Advance Java

OUTPUT:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Ex. No:

Date:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Page No:
Department of IT, AAGAC-VPM
Advance Java

13. USING SESSIONS AND COOKIES.

Index.html
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<form action="LoginServlet" method="POST">
Name: <input type="text" name="username">
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>

LoginServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginServlet extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

Page No:
Department of IT, AAGAC-VPM
Advance Java

String username = request.getParameter("username");

HttpSession session = request.getSession();


session.setAttribute("username", username);

Cookie userCookie = new Cookie("username", username);


userCookie.setMaxAge(60 * 60 * 24);
response.addCookie(userCookie);

response.sendRedirect("WelcomeServlet");
}
}

WelcomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

HttpSession session = request.getSession(false);


String username = null;
if (session != null) {
username = (String) session.getAttribute("username");
}
if (username == null) {

Page No:
Department of IT, AAGAC-VPM
Advance Java

Cookie[] cookies = request.getCookies();


if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("username")) {
username = cookie.getValue();
break;
}
}
}
}

if (username != null) {
out.println("<h2>Welcome, " + username + "!</h2>");
} else {
out.println("<h2>No user found. Please log in.</h2>");
out.println("<a href='runpage.html'>Go to Login</a>");
}}}

Page No:
Department of IT, AAGAC-VPM
Advance Java

OUTPUT:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Ex. No:

Date:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Page No:
Department of IT, AAGAC-VPM
Advance Java

14. FORWARDING REQUESTS AND REDIRECTING RESPONSES.

Homepage.html
<!DOCTYPE html>
<html>
<head>
<title>Age Verification</title>
</head>
<body>
<h2>Enter Your Details</h2>
<form action="VerifyAgeServlet" method="POST">
Name: <input type="text" name="username" required><br>
Age: <input type="number" name="age" required><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Error.html
<!DOCTYPE html>
<html>
<head>
<title>Error</title>
</head>
<body>
<h2>You are not eligible to vote.</h2>
<p>You must be 18 or older to vote. Please try again later.</p>
<a href="homepage.html">Go back to the form</a>
</body>

Page No:
Department of IT, AAGAC-VPM
Advance Java

</html>

NewServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class NewServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String username = request.getParameter("username");
int age = Integer.parseInt(request.getParameter("age"));
if (age >= 18) {
RequestDispatcher dispatcher = request.getRequestDispatcher("Welcome");
request.setAttribute("username", username); // Pass the username as a request attribute
dispatcher.forward(request, response);
//response.sendRedirect("WelcomeServlet");
} else {
response.sendRedirect("error.html");
}
} finally {
out.close();
}

Page No:
Department of IT, AAGAC-VPM
Advance Java

}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}
}

Welcome.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = {"/Welcome"})
public class Welcome extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

Page No:
Department of IT, AAGAC-VPM
Advance Java

response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String username = (String) request.getAttribute("username");
out.println("<h2>Welcome, " + username + "!</h2>");
out.println("<p>You are eligible to vote.</p>");
} finally {
out.close();
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}
}

Page No:
Department of IT, AAGAC-VPM
Advance Java

OUTPUT:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Ex. No:

Date:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Page No:
Department of IT, AAGAC-VPM
Advance Java

15. WEB APPLICATION USING DATABASE.

Home.html
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form action="LoginServlet" method="post">
<h2>Login Form</h2>
Username: <input type="text" name="username" required><br>
Password: <input type="password" name="password" required><br>
<input type="submit" value="Login">
</form>
</body>
</html>

DatabaseConnection.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
private static final String URL = "jdbc:derby://localhost:1527/sample";
private static final String USER = "app";
private static final String PASSWORD = "app";
public static Connection initializeDatabase() throws SQLException, ClassNotFoundException {
// Class.forName("com.mysql.cj.jdbc.Driver");
Class.forName("org.apache.derby.jdbc.ClientDriver");

Page No:
Department of IT, AAGAC-VPM
Advance Java

return DriverManager.getConnection(URL, USER, PASSWORD);


}
}

LoginServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = null;
try {
out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
try {
Connection conn = DatabaseConnection.initializeDatabase();
String sql = "SELECT * FROM STUD WHERE USERN=? AND PASSWORD=?";

Page No:
Department of IT, AAGAC-VPM
Advance Java

PreparedStatement stmt = conn.prepareStatement(sql);


stmt.setString(1, username);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
out.println("<h3>Login Successful! Welcome " + username + ".</h3>");
} else {
out.println("<h3>Invalid Username or Password!</h3>");
}
} catch (Exception e) {
e.printStackTrace();
out.println("<h3>Database Connection Error!</h3>"+ e);
}
} finally {
if (out != null) {
out.close();
}
}
}
}

Page No:
Department of IT, AAGAC-VPM
Advance Java

OUTPUT:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Ex. No:

Date:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Page No:
Department of IT, AAGAC-VPM
Advance Java

16. DEVELOPING SIMPLE BEANS.

Teststudent.java
import student.*;
public class Teststudent {
public static void main(String[] args) {
Student s1 = new Student();
s1.setName("Pooja");
s1.setid(20);
System.out.println("Name: " + s1.getName());
System.out.println("Age: " + s1.getid());
System.out.println(s1);
}
}

Package student:Student.java
package student;
public class Student {
private String name;
private int id;
public Student() {
}
// Constructor with parameters (optional)
public Student(String name, int id) {
this.name = name;
this.id = id;
}
// Getter and Setter for 'name'
public String getName() {

Page No:
Department of IT, AAGAC-VPM
Advance Java

return name;
}
public void setName(String name) {
this.name = name;
}
// Getter and Setter for 'age'
public int getid() {
return id;
}

public void setid(int id) {


this.id = id;
}
@Override
public String toString() {
return "Student{name='" + name + "', age=" + id + "}";
}
}

Page No:
Department of IT, AAGAC-VPM
Advance Java

OUTPUT:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Ex. No:

Date:

Page No:
Department of IT, AAGAC-VPM
Advance Java

Page No:
Department of IT, AAGAC-VPM
Advance Java

17. USE BEANS WITH JSP TAGS.

beanJSP.html
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page import="student.student" %>
<html>
<head>
<title>Student Details</title>
</head>
<body>
<h2>Student Details</h2>
<%
// Create an instance of the Student bean
Student student = new Student();
student.setName("Priya");
student.setId(15);
// Set the bean in the request scope
request.setAttribute("student", student);
%>
<p>Name: ${student.name}</p>
<p>ID: ${student.id}</p>
</body>
</html>

Package student:student.java
package student;
public class student {

Page No:
Department of IT, AAGAC-VPM
Advance Java

public student() {
}
private String name;
public String getName() {
return name;
}
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}

Page No:
Department of IT, AAGAC-VPM
Advance Java

OUTPUT:

Page No:
Department of IT, AAGAC-VPM

You might also like