Adv Java

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

1

1. Write a JAVA Swing program using event Handling A Frame with three buttons
Red blue and green and change the background color according to button pressed
by user
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class Color_Frame implements ActionListener


{
Frame F;
Button btnred,btnblue,btncyan;
public Color_Frame()
{
F = new Frame("Default Frame");
F.setLayout(new FlowLayout());
F.setSize(300,300);
F.setVisible(true);

btnred = new Button("Red Frame");


btnred.addActionListener(this);
F.add(btnred);

btnblue = new Button("Blue Frame");


btnblue.addActionListener(this);
F.add(btnblue);

btncyan = new Button("Cyan Frame");


btncyan.addActionListener(this);
F.add(btncyan);

F.add(btnred);
F.add(btnblue);
F.add(btncyan);
}
public static void main(String[] args)
{
Color_Frame F= new Color_Frame();
}
public void actionPerformed(ActionEvent AE)
{
if(AE.getActionCommand()=="Red Frame")
{
F.setTitle("Red Frame");
F.setBackground(Color.RED);
F.setVisible(true);
}
if(AE.getActionCommand()=="Blue Frame")
{
2

F.setTitle("Blue Frame");
F.setBackground(Color.BLUE);
F.setVisible(true);
}
if(AE.getActionCommand()=="Cyan Frame")
{
F.setTitle("Cyan Frame");
F.setBackground(Color.CYAN);
F.setVisible(true);
}
}
}
//<applet code="Color_Frame.class" height=500 width=500> </applet>

Output:
3

2. Write a JDBC program to establish connection with oracle and perform following
operation on emp table.
a. Display the table data
b. Insert a new record into emp table
c. Delete record by emp no. From emp table.
d. Update emp data using emp number.
Program:
import java.sql.*;
class EmployeeRecord
{
public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:XE";
public static final String DBUSER = "local";
public static final String DBPASS = "test";
public static void main(String args[])
{
try
{
//Loading the driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//Cretae the connection object
Connection con = DriverManager.getConnection(DBURL, DBUSER,
DBPASS);
//Insert the record
String sql = "INSERT INTO emp (emp_id, empname, email, city) VALUES
(?, ?, ?, ?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setInt(1, 100);
statement.setString(2, "Prashant");
statement.setString(3, "prasant@saxena.com");
statement.setString(4, "Pune");

int rowsInserted = statement.executeUpdate();


if (rowsInserted > 0)
{
System.out.println("A new employee was inserted successfully!\n");
}
// Display the record
String sql1 = "SELECT * FROM Emp";
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery(sql1);

while (result.next())
{
System.out.println (result.getInt(1)+" "+
result.getString(2)+" "+
result.getString(3)+" "+
4

result.getString(4));
}

//Update the record


String sql2 = "Update Emp set email = ? where empname = ?";
PreparedStatement pstmt = con.prepareStatement(sql2);
pstmt.setString(1, "Jaya@gmail.com");
pstmt.setString(2, "Jaya");
int rowUpdate = pstmt.executeUpdate();
if (rowUpdate > 0)
{
System.out.println("\nRecord updated successfully!!\n");
}

//Delete the record


String sql3 = "DELETE FROM Emp WHERE empname=?";
PreparedStatement statement1 = con.prepareStatement(sql3);
statement1.setString(1, "Prashant");

int rowsDeleted = statement1.executeUpdate();


if (rowsDeleted > 0)
{
System.out.println("A Employee was deleted successfully!\n");
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
Output:
5

3. Write a java program which shows how to read the data from the keyboard and
write it to the myfile.txt also read the data from the file and display on output
screen.
Program:
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class Tester {

public static void main(String[] args) {

Scanner reader = null;


FileWriter writer = null;
String inputText;

try {

reader = new Scanner(System.in);

writer = new FileWriter("C:\\myfile.txt");

while (true) {

inputText = reader.nextLine();

// If you type 'EXIT', the application quits


if (inputText.equals("EXIT")) {
break;
}

writer.write(inputText);

writer.write("\n");

} catch (IOException e) {

// This exception may occur while reading or writing a line


System.out.println("A fatal exception occurred!");

} finally {

// The finally branch is ALWAYS executed after the try


6

// or potential catch block execution

if (reader != null) {
reader.close();
}

try {

if (writer != null) {
writer.close();
}

} catch (IOException e) {

// This second catch block is a clumsy notation we need in Java,


// because the 'close()' call can itself throw an IOException.
System.out.println("Closing was not successful.");

}
Output:
7

4. Write a java program to accept a website name and return its IP address, after
checking it on internet.
Program:
import java.net.*;
import java.util.*;

public class IPDemo


{
public static void main(String[] args){
String host;
Scanner input = new Scanner(System.in);
System.out.print("\n Enter host name: ");
host = input.nextLine();
try {
InetAddress address = InetAddress.getByName(host);
System.out.println("IP address: " + address.getHostAddress());
System.out.println("Host name : " + address.getHostName());
System.out.println("Host name and IP address: " +
address.toString());

}
catch (UnknownHostException ex) {
System.out.println("Could not find " + host);
}
}
}
Output:
8

5. Write a JAVA program using Servlet to accept the user name from client
page and generate response with welcome message.
Program:
Index.html

<!doctype html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<form action="servlet1" method="post">
<fieldset style="width:20%; background-color:#ccffcc">
<h2 align="center">Login Page</h2>
<hr>
<table>
<tr><td>Name</td><td><input type="text"
name="username"/></td>
<tr><td>Password</td><td><input type="password"
name="userpass"/></td></tr>
<tr><td></td><td><input type="submit"
value="login"/></td></tr>
</table>
</fieldset>
</form>
</body>
</html>
FirstServlet.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 FirstServlet extends HttpServlet


9

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

String n=request.getParameter("username");
String p=request.getParameter("userpass");
if(LoginDao.validate(n, p))
{
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request,response);
}
else
{
out.print("Sorry username or password error");
RequestDispatcher
rd=request.getRequestDispatcher("index.html");
rd.include(request,response);
}
out.close();
}
}
LoginDao.java
import java.sql.*;
public class LoginDao
{
public static boolean validate(String name,String pass)
{
boolean status=false;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
10

Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","lo
cal","test");

PreparedStatement ps=con.prepareStatement(
"select * from userreg where name=? and pass=?");
ps.setString(1,name);
ps.setString(2,pass);
ResultSet rs=ps.executeQuery();
status=rs.next();
}
catch(Exception e)
{
System.out.println(e);
}
return status;
}
}
WelcomeServlet.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;

public class WelcomeServlet extends HttpServlet


{
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
out.print("Welcome "+n);
11

out.close();
}
}
web.xml

<web-app>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

</web-app>
12
13

6. WAP that showcases how cookies will work. in this example first servlet will
collect data from user and store data in session so that second servlet can
access the data by using cookies.
Program:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class UseCookies extends HttpServlet {


public void doGet ( HttpServletRequest request,
HttpServletResponse response )throws ServletException,
IOException {
PrintWriter out;
response.setContentType("text/html");
out = response.getWriter();
Cookie cookie = new Cookie("CName","Cookie Value");
cookie.setMaxAge(100);
response.addCookie(cookie);

out.println("<HTML><HEAD><TITLE>");
out.println(" Use of cookie in servlet");
out.println("</TITLE></HEAD><BODY BGCOLOR='cyan'>");
out.println(" <b>This is a Cookie example</b>");
out.println("</BODY></HTML>");
out.close();
}
}
14

7. Write a JAVA program using Servlet to forward the client request to


another page using of Request Dispatcher
Program:
HTML file:-
<html>
<head>
<body>
<form action="login" method="post">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>
</form>
</body>
</html>

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

public class Login extends HttpServlet {

public void doPost(HttpServletRequest req,


HttpServletResponse res)
throws ServletException, IOException
{
// The method to receive client requests
// which are sent using 'post'

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

// fetches username
String n = request.getParameter("userName");

// fetches password
String p = request.getParameter("userPass");
if(p.equals("Thanos"){
15

RequestDispatcher rd =
request.getRequestDispatcher("servlet2");
// Getting RequestDispatcher object
// for collaborating with servlet2

// forwarding the request to servlet2


rd.forward(request, response);
}
else{
out.print("Password mismatch");
RequestDispatcher rd =
request.getRequestDispatcher("/index.html");

rd.include(request, response);

}
}

}
Welcome.java
// Called servlet in case password matches
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Welcome extends HttpServlet {

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{

response.setContentType("text/html");
PrintWriter out = response.getWriter();
16

// fetches username
String n = request.getParameter("userName");

// prints the message


out.print("Welcome " + n);
}
}
Html file:-
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>Welcome</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Output:
Index.html
17

When password is correct:

When password is incorrect:


18

8. Write a Servlet to include the response of an Html Page with the current page.
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Servlet implementation class SearchServlet


@WebServlet("/searchServlet")
public class SearchServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public SearchServlet() {
super();
// TODO Auto-generated constructor stub
}

// @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse


response)
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {

// set response content type


response.setContentType("text/html");

// New location to be redirected, it is an example


String site = new String("https://www.geeksforgeeks.org/learn-java-on-
your-own-in-20-days-free/");

// We have different response status types.


// It is an optional also. Here it is a valid site
// and hence it comes with response.SC_ACCEPTED
response.setStatus(response.SC_ACCEPTED);
response.setHeader("Location", site);
response.sendRedirect(site);
return;
}

}
XML file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
19

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>sampleProject1</display-name>
<!-- We are using only index.jsp. in some cases if we want to
specify other welcome files, they need
to be listed here, hence shown here -->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
Output:
20

9. Write a java program to configure web.xml file using initialization and context
parameters.
Program:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DemoServlet extends HttpServlet{


public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();

//creating ServletContext object


ServletContext context=getServletContext();

//Getting the value of the initialization parameter and printing it


String driverName=context.getInitParameter("dname");
pw.println("driver name is="+driverName);

pw.close();

}}

Web.xml
<web-app>

<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>

<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>

<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>

</web-app>
21

10. Write a jsp program to accept a client request and return its IP address.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>What is my IP?</title>
</head>
<body>
<%! String ipAddress; %>
<%
ipAddress = request.getRemoteAddr();
%>
<h1>Your IP Address : <%=ipAddress %></h1>
</body>
</html>

Output:
22

11. Write a jsp program to validate Login ID and Password from client request. And if it is
correct forward the control to welcome page.
Program
Login.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>
<h1>User Details</h1>
<%-- The form data will be passed to acceptuser.jsp
for validation on clicking submit
--%>
<form method ="get" action="acceptuser.jsp">
Enter Username : <input type="text" name="user"><br/><br/>
Enter Password : <input type="password" name ="pass"><br/>
<input type ="submit" value="SUBMIT">
</form>
</body>
</html>

acceptuser.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Accept User Page</title>
</head>
<body>
<h1>Verifying Details</h1>
<%-- Include the ValidateUser.java class whose method
boolean validate(String, String) we will be using
--%>
<%-- Create and instantiate a bean and assign an id to
uniquely identify the action element throughout the jsp
--%>
<jsp:useBean id="snr" class="saagnik.ValidateUser"/>

<%-- Set the value of the created bean using form data --%>
<jsp:setProperty name="snr" property="user"/>
<jsp:setProperty name="snr" property="pass"/>

<%-- Display the form data --%>


The Details Entered Are as Under<br/>
<p>Username : <jsp:getProperty name="snr" property="user"/></p>
<p>Password : <jsp:getProperty name="snr" property="pass"/></p>
23

<%-- Validate the user using the validate() of


ValidateUser.java class
--%>
<%if(snr.validate("GeeksforGeeks", "GfG")){%>
Welcome! You are a VALID USER<br/>
<%}else{%>
Error! You are an INVALID USER<br/>
<%}%>
</body>
</html>

ValidateUser.java
package saagnik;
import java.io.Serializable;

// To persist the data for future use,


// implement serializable
public class ValidateUser implements Serializable {
private String user, pass;

// Methods to set username and password


// according to form data
public void setUser(String u1) { this.user = u1; }
public void setPass(String p1) { this.pass = p1; }

// Methods to obtain back the values set


// by setter methods
public String getUser() { return user; }
public String getPass() { return pass; }

// Method to validate a user


public boolean validate(String u1, String p1)
{
if (u1.equals(user) && p1.equals(pass))
return true;
else
return false;
}
}
24

Output:
25

12. Write a JSP program to perform session Handling using session Tracking API

Session.jsp
<%@page import = "java.io.*,java.util.*"%>
<%
Date creationTime = new Date(session.getCreationTime());
Date lastaccessTime = new Date(session.getLastAccessedTime());

String title = "My website";


Integer visit = new Integer(0);
String visitCount = new String("visit");
String userID = new String("XYZ");
String userIDCount = new String("userID");

if (session.isNew())
{
title = "My website";
session.setAttribute(userIDCount, userID);
session.setAttribute(visitCount, visit);
}
visit = (Integer)session.getAttribute(visitCount);
visit = visit+1;
userID =(String)session.getAttribute(userIDCount);
session.setAttribute(visitCount, visit);
%>
<html>
<head><title>Session</title>
</head>
<body>
<h2>Session tracking</h2>
<table width = "75%" border = "2" align = "left">
<tr>
<th>SessionInfo</th>
<th>Value</th>
</tr>
<tr>
<td>Session ID</td>
<td><%out.print(session.getId());%></td>
</tr>
<tr>
<td>Session Creation Time</td>
<td><%out.print(creationTime);%></td>
</tr>
<tr>
<td>Last Access Time</td>
<td><%out.print(lastaccessTime);%></td>
</tr>
<tr>
<td>User ID</td>
26

<td><%out.print(userID);%></td>
</tr>
<tr>
<td>No. of Visits</td>
<td><%out.print(visit);%></td>
</tr>
</table>
</body>
</html>

Output:

When we load the page again the no. of visits increases by 1.

You might also like