0% found this document useful (0 votes)
7 views53 pages

AJP Practical File

The document outlines several practical exercises for an Advanced Java Programming course, focusing on JDBC applications, servlets, and session management. It includes code examples for retrieving and manipulating database records, creating web applications with shared resources, and implementing cookies and session management. Each practical exercise is accompanied by specific aims, code snippets, and expected outputs.

Uploaded by

parthsjha786
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views53 pages

AJP Practical File

The document outlines several practical exercises for an Advanced Java Programming course, focusing on JDBC applications, servlets, and session management. It includes code examples for retrieving and manipulating database records, creating web applications with shared resources, and implementing cookies and session management. Each practical exercise is accompanied by specific aims, code snippets, and expected outputs.

Uploaded by

parthsjha786
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

220860131021 Advanced Java Programming (3160707)

Practical: 1
AIM: Write a program to create simple JDBC Application to retrieve
records from Database (resultSet).
Code:

import java.sql.*;

class RetrieveRecord

public static void main(String args[]) throws SQLException,


ClassNotFoundException

Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Driver is loaded and registered");

String url= "jdbc:oracle:thin:@localhost:1521:XE";

Connection con= DriverManager.getConnection(url,"system","system");

System.out.println("Connection is established");

Statement st= con.createStatement();

ResultSet rs= st.executeQuery("select * from Emp1");

System.out.println("ID Name Department");

while(rs.next())
{

System.out.println(rs.getInt(1)+ " " + rs.getString(2)+ " " +


rs.getString(3));

rs.close();

st.close();

con.close();

LIT/CSE/2024-25 1
220860131021 Advanced Java Programming (3160707)

Output:

LIT/CSE/2024-25 2
220860131021 Advanced Java Programming (3160707)

Practical: 2
AIM: Write a program to create simple JDBC Application using
Prepared Statement insert and delete data from database.
Code:

import java.sql.*;

import java.util.*;

import java.io.*;

class preparedstatement
{

public static void main(String args[]) throws SQLException, IOException,


ClassNotFoundException

int i,id;

float cpi;

String sname;

Class.forName("oracle.jdbc.driver.OracleDriver");

System.out.println("Driver is loaded and registered");

String url = "jdbc:oracle:thin:@localhost:1521:XE";


Connection con = DriverManager.getConnection(url,"system","system");

System.out.println("Connection established");

PreparedStatement ps1= con.prepareStatement("Insert into stu1


values(?,?,?)");

PreparedStatement ps2= con.prepareStatement("delete from stu1 where


id=?");

Scanner sc = new Scanner(System.in);

do

System.out.println("1.Insert");

System.out.println("2.Delete");

LIT/CSE/2024-25 3
220860131021 Advanced Java Programming (3160707)

System.out.println("0.Exit");

System.out.println("Enter your choice:");

i= sc.nextInt();

if(i==1)

System.out.println("Enter Student ID:");

id = sc.nextInt();

System.out.println("Enter Student Name:");


sname = sc.next();

System.out.println("Enter Student CPI:");

cpi = sc.nextFloat();

ps1.setInt(1,id);

ps1.setString(2,sname);

ps1.setFloat(3,cpi);

ps1.executeUpdate();

System.out.println("Data is Inserted");

else if(i==2)

System.out.println("Enter the Student ID");

id = sc.nextInt();

ps2.setInt(1,id);

ps2.executeUpdate();
System.out.println("Selected row is deleted");

else if(i!=0)

System.out.println("Invalid Choice..!!");

LIT/CSE/2024-25 4
220860131021 Advanced Java Programming (3160707)

else

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

}while(i!=0);

sc.close();

ps2.close();

ps1.close();
con.close();

Output:

LIT/CSE/2024-25 5
220860131021 Advanced Java Programming (3160707)

LIT/CSE/2024-25 6
220860131021 Advanced Java Programming (3160707)

Practical: 3
AIM: Write a program to create simple JDBC Application using
callable statement to retrieve data from database (make use of stored
procedure).
Code for Stored Procedure proc1:
CREATE OR REPLACE PROCEDURE proc1 (emp_id IN NUMBER, emp_name
OUT VARCHAR) AS

BEGIN

SELECT NAME INTO emp_name

FROM EMP9

WHERE ID = emp_id;

-- If no employee is found, return a default message

IF emp_name IS NULL THEN

emp_name := 'Employee Not Found';


END IF;

END proc1;

Code:
import java.sql.*;

class Callablestatement

public static void main(String args[]) throws SQLException,


ClassNotFoundException
{

Class.forName("oracle.jdbc.driver.OracleDriver");

System.out.println("Driver is loaded and registered");

String url = "jdbc:oracle:thin:@localhost:1521:XE";

Connection con = DriverManager.getConnection(url,"system","system");

LIT/CSE/2024-25 7
220860131021 Advanced Java Programming (3160707)

System.out.println("Connection established");

CallableStatement cst = con.prepareCall("{call proc1(?,?)}");

cst.registerOutParameter(2,Types.VARCHAR);

cst.setInt(1,102);

cst.execute();

String str = cst.getString(2);

System.out.println("Employee Name: "+str);

cst.close();
con.close();

Output:

LIT/CSE/2024-25 8
220860131021 Advanced Java Programming (3160707)

Practical: 4
AIM: Write a program of web application to explore the concept of
sharing the resource (connection object) across multiple servlets of the
same web application (ServletConfig & ServletContext example).
Code:
Data.html file:

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Employee Details</title>

</head>

<body>

<center>

<h1>Personal Details</h1>

<form method="get" action="/Prcatical4/store">

Email Id:<input type="text" name="email"><br><br>

Phone number:<input type="text" name="phone"><br><br>

<input type="submit" value="Submit Details">

</form>
</center>

</body>

</html>

LIT/CSE/2024-25 9
220860131021 Advanced Java Programming (3160707)

Web.xml file:

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

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">

<servlet>

<servlet-name>Storage</servlet-name>

<servlet-class>StorageServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>Storage</servlet-name>

<url-pattern> /store </url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>Retrieve</servlet-name>

<servlet-class>RetrieveServlet</servlet-class>
</servlet>

<servlet-mapping>

<servlet-name>Retrieve</servlet-name>

<url-pattern> /retrieve </url-pattern>

</servlet-mapping>

</web-app>

LIT/CSE/2024-25 10
220860131021 Advanced Java Programming (3160707)

StorageServlet.java file:

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class StorageServlet extends HttpServlet

private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest req, HttpServletResponse res) throws


ServletException, IOException

res.setContentType("text/html");

PrintWriter out = res.getWriter();

String email = req.getParameter("email");

String phone = req.getParameter("phone");

ServletContext sc = getServletContext();

sc.setAttribute("email2",email);
sc.setAttribute("phone2",phone);

out.println("<html>");

out.println("<body>");

out.println("<h2><a href= /Prcatical4/retrieve>Get Your Details</a></h2>");

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

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

out.close();

LIT/CSE/2024-25 11
220860131021 Advanced Java Programming (3160707)

RetrieveServlet.java file:

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class RetrieveServlet extends HttpServlet

private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest req, HttpServletResponse res) throws


ServletException, IOException

res.setContentType("text/html");

PrintWriter out = res.getWriter();

ServletContext sc = getServletContext();

String email3 = (String)sc.getAttribute("email2");

String phone3 = (String)sc.getAttribute("phone2");

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

out.println("<h2>Your Personal details:</h2>");

out.println("<h3>Email id:"+email3+"</h3>");

out.println("<h3>Phone number:"+phone3+"</h3>");

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

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

out.close();

LIT/CSE/2024-25 12
220860131021 Advanced Java Programming (3160707)

Output:

LIT/CSE/2024-25 13
220860131021 Advanced Java Programming (3160707)

Practical: 5
AIM: Write a program of web application to implement state
management using cookies.
Code:

CookieExample.html file:

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">
<title>Cookie Example</title>

</head>
<body>

<center><h2>Welcome To Shopping Mall</h2></center>

<form method="post" action="/Practical_5/create">

<b>User Name: </b><input type="text" name="user"><br><br>

<input type="submit" value="Welcome">

</form>

</body>

</html>

Welcome.html file:

<!DOCTYPE html>

<html>
<head>

<meta charset="UTF-8">

<title>Welcome</title>

</head>

<body>

LIT/CSE/2024-25 14
220860131021 Advanced Java Programming (3160707)

<marquee><font color=green size=6>Welcome To Shopping


Mall</font></marquee>

</body>
</html>

Web.xml file:

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

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">

<servlet>
<servlet-name>Create</servlet-name>

<servlet-class>CreateCookie</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>Create</servlet-name>

<url-pattern>/create</url-pattern>

</servlet-mapping>
<servlet>

<servlet-name>Check</servlet-name>

<servlet-class>CheckCookie</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>Check</servlet-name>

<url-pattern>/check</url-pattern>
</servlet-mapping>

</web-app>

LIT/CSE/2024-25 15
220860131021 Advanced Java Programming (3160707)

CreateCookie.java file:

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class CreateCookie extends HttpServlet

private static final long serialVersionUID = 1L;

public void doPost(HttpServletRequest req, HttpServletResponse res) throws


ServletException, IOException

res.setContentType("text/html");

PrintWriter out = res.getWriter();

String name = req.getParameter("user");

Cookie c = new Cookie("user",name);

res.addCookie(c);

out.println("<html>");
out.println("<body bgcolor= wheat><center>");

req.getRequestDispatcher("/Welcome.html").include(req,res);

out.println("<h2><a href= /Practical_5/check>Shopping Goes


Here</a></h2>");

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

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

out.close();

LIT/CSE/2024-25 16
220860131021 Advanced Java Programming (3160707)

CheckCookie.java file:

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class CheckCookie extends HttpServlet

private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest req, HttpServletResponse res) throws


ServletException, IOException

res.setContentType("text/html");

PrintWriter out = res.getWriter();

Cookie c[] = req.getCookies();

out.println("<html>");

out.println("<body bgcolor= wheat><h2>");

for(int i=0;i<c.length;i++)
{

Cookie c1 = c[i];

if(c1.getName().equals("user"))

out.println("Hey "+c1.getValue()+" ! Hope Enjoying


Shopping Here</h2>");

break;

}
out.close();

LIT/CSE/2024-25 17
220860131021 Advanced Java Programming (3160707)

Output:

LIT/CSE/2024-25 18
220860131021 Advanced Java Programming (3160707)

Practical: 6
AIM: Write a program of web application to implement session
management using session API.
Code:

ShoppingPage.html file:

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">
<title>Shop Page</title>

</head>
<body bgcolor= "#f9f9f9">

<form method="post" action="/Practical6/shopsession">

<center>

<h2>Welcome To Shopping Mall</h2>

<font color= "blue" size= "4">

Select Product Code:<select name= "pCode">

<option value= 101>101</option>

<option value= 102>102</option>

<option value= 103>103</option>

<option value= 104>104</option>

<option value= 105>105</option>

</select><br><br>
Product Name:

</font>

<input type="text" name="pname" value=""><br><br>

<input type="submit" name="submit" value="ADD ITEM">

<input type="submit" name="submit" value="REMOVE ITEM">

<input type="submit" name="submit" value="SHOW ITEM">

LIT/CSE/2024-25 19
220860131021 Advanced Java Programming (3160707)

<input type="submit" name="submit" value="PAY AMOUNT">

<input type="submit" name="submit" value="LOGOUT">

</center>

</form>

</body>

</html>

Web.xml file:
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">

<servlet>

<servlet-name>Shopping</servlet-name>

<servlet-class>ShopServlet</servlet-class>

</servlet>
<servlet-mapping>

<servlet-name>Shopping</servlet-name>

<url-pattern>/shopsession</url-pattern>

</servlet-mapping>

</web-app>

ShopServlet.java file:

import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

LIT/CSE/2024-25 20
220860131021 Advanced Java Programming (3160707)

public class ShopServlet extends HttpServlet

private static final long serialVersionUID = 1L;

HttpSession session;

String pCode,pname,clickButton;

public void doPost(HttpServletRequest req, HttpServletResponse res) throws


ServletException, IOException

res.setContentType("text/html");

PrintWriter out = res.getWriter();

session = req.getSession(true);

clickButton = req.getParameter("submit");

if(clickButton.equals("ADD ITEM"))

pCode = req.getParameter("pCode");

pname = req.getParameter("pname");
if(!(pCode.equals("")|| pname.equals("")))

session.setAttribute(pCode,pname);

res.sendRedirect("ShoppingPage.html");

else if(clickButton.equals("REMOVE ITEM"))

pCode = req.getParameter("pCode");

session.removeAttribute(pCode);

res.sendRedirect("ShoppingPage.html");

LIT/CSE/2024-25 21
220860131021 Advanced Java Programming (3160707)

else if(clickButton.equals("SHOW ITEM"))

Enumeration e = session.getAttributeNames();

if(e.hasMoreElements())

out.println("<h2><font color=blue>Your Shopping Cart


Items</font></h2>");

while(e.hasMoreElements())

out.println("<body bgcolor=#F7F7F7>");

String code = (String)e.nextElement();

out.println("<h2>Product Code:"+code+"<br>");

out.println("Product
Name:"+session.getAttribute(code)+"</h2>");

else

{
out.println("<body bgcolor= #E0F2F1>");

out.println("<h2><font color= red>No Item On


Cart</font></h2>");

}
}

else if(clickButton.equals("LOGOUT"))

session.invalidate();

res.sendRedirect("ShoppingPage.html");

else if(clickButton.equals("PAY AMOUNT"))

LIT/CSE/2024-25 22
220860131021 Advanced Java Programming (3160707)

out.println("<body bgcolor= #D1E8E2>");

out.println("<h2><font color= red>Payment Logic Goes


Here</font></h2>");

Output:

LIT/CSE/2024-25 23
220860131021 Advanced Java Programming (3160707)

LIT/CSE/2024-25 24
220860131021 Advanced Java Programming (3160707)

Practical: 7
AIM: Write a program for simple JSP application (using scripting
elements & implicit object).
Code:

Home.html file:

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">
<title>Invoke JSP Parameter</title>

</head>
<body>

<form method="get" action="Request.jsp">

Name:<input type="text" name="uname">

<input type="submit" value="Submit">

</form>

</body>

</html>

Web.xml file:

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

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID"
version="4.0">

<context-param>

<param-name>param1</param-name>
<param-value>param1</param-value>

</context-param>

LIT/CSE/2024-25 25
220860131021 Advanced Java Programming (3160707)

<servlet>

<servlet-name>myjsp</servlet-name>

<jsp-file>/Other.jsp</jsp-file>

<init-param>

<param-name>count</param-name>

<param-value>10</param-value>

</init-param>

</servlet>
<servlet-mapping>

<servlet-name>myjsp</servlet-name>

<url-pattern>/other</url-pattern>

</servlet-mapping>

</web-app>

Request.jsp file:

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Invoke JSP</title>

</head>
<body>

Hello!!!!<b><%=request.getParameter("uname") %></b><br>

Your Request Details are <br>

<table border="1">

<tr><th>Name</th><th>Values</th></tr>

<tr>

LIT/CSE/2024-25 26
220860131021 Advanced Java Programming (3160707)

<td>Request Method</td>

<td><%=request.getMethod() %></td>

</tr>

<tr>

<td>Request URL</td>

<td><%=request.getRequestURL() %></td>

</tr>

<tr>
<td>Request Protocol</td>

<td><%=request.getProtocol() %></td>

</tr>

<tr>

<td>Browser</td>

<td><%=request.getHeader("user-agent") %></td>

</tr>

</table>

<%

if(session.getAttribute("sessionVar")==null)

session.setAttribute("sessionVar",new Integer(0));

%>

<table>
<tr>

<th align=left>Would you like to see use of remaining implicit object?</th>

</tr>

<tr>

<td>

<form method="post" action="pageContext.jsp" name=form1>

LIT/CSE/2024-25 27
220860131021 Advanced Java Programming (3160707)

<input type="radio" name="other" value="Yes">Yes

<input type="radio" name="other" value="No">No

<input type="submit" value="Submit">

</form>

</td>

</tr>

<tr><td></td></tr>

</table>
</body>

</html>

pageContext.jsp file:

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Page Context</title>

</head>

<body>

<%

if("Yes".equals(request.getParameter("other")))
{

pageContext.forward("/other");

%>

</body>

</html>

LIT/CSE/2024-25 28
220860131021 Advanced Java Programming (3160707)

Other.jsp file:

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Other JSP</title>
</head>

<body>

<%! int count;

public void jspInit()

ServletConfig sc = getServletConfig();

count = Integer.parseInt(sc.getInitParameter("count"));

System.out.println("In jspInit");

%>

<%

out.println("<h1>Using Page,session,out,config and application Implicit


Object</h1>");

%>

Count value without using config implicit object: <b><%=count %></b><br>

<%

this.log("log Message");

((HttpServlet)page).log("another message");

ServletContext ct = config.getServletContext();

out.println("Value of SessionVar
is:"+"&nbsp;&nbsp;<b>"+session.getAttribute("sessionVar")+"</b><br>");

LIT/CSE/2024-25 29
220860131021 Advanced Java Programming (3160707)

out.println("server name and version using config implicit


object:"+"&nbsp;&nbsp;<b>"+ct.getServerInfo()+"</b><br>");

out.println("Value of context parameter param1 obtained using application implicit


object:"+"&nbsp;&nbsp;<b>"+application.getInitParameter("param1")+"</b><br>");

out.println("count value retrieved using config implicit


object:"+"&nbsp;&nbsp;<b>"+config.getInitParameter("count")+"</b>");

%>

</body>
</html>

Output:

LIT/CSE/2024-25 30
220860131021 Advanced Java Programming (3160707)

LIT/CSE/2024-25 31
220860131021 Advanced Java Programming (3160707)

Practical: 8
AIM: Write a program to create simple database application using
JSP.
Code:

getDetail.html file:

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">
<title>Detail Page</title>

</head>
<body>

<center>

<form action="Database.jsp">

<br>

<b>Enter Employee ID:</b><input type="text" name="empid"><br><br>

<input type="submit" value="Get Data">

</form>

</center>

</body>

</html>

Database.jsp file:
<%@ page import="java.sql.*" language="java" contentType="text/html;
charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>

<head>

LIT/CSE/2024-25 32
220860131021 Advanced Java Programming (3160707)

<meta charset="UTF-8">

<title>Employee Database</title>

</head>

<body>

<%

Connection con = null;

String id = request.getParameter("empid");

int empid = Integer.parseInt(id);


try

Class.forName("oracle.jdbc.driver.OracleDriver");

String url = "jdbc:oracle:thin:@localhost:1521:XE";

con = DriverManager.getConnection(url,"system","system");

Statement st = con.createStatement();

%><center><h1><%out.println("Employee Details");
%></h1></center><br>

<%

ResultSet rs = st.executeQuery("select * from EMP12 where eid="+empid);


if(rs.next())

out.println("<b>Employee
Id:</b>"+rs.getInt(1)+"<br><b>Employee
Name:</b>"+rs.getString(2)+"<br><b>Employee Salary:</b>"+rs.getInt(3));
}

catch(ClassNotFoundException e)

System.out.println(e);

catch(SQLException e1)

LIT/CSE/2024-25 33
220860131021 Advanced Java Programming (3160707)

System.out.println(e1);

%>

</body>

</html>

Output:

LIT/CSE/2024-25 34
220860131021 Advanced Java Programming (3160707)

Practical: 9
AIM: Write a program using java beans.
Code:

Login.jsp file:

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Login</title>

</head>
<body>

<form method="post" action="Loginbean.jsp" name="loginform">

<br><br>

<table align="center"><tr><td><h2>Login Authentication</h2></td></tr></table>

<table width="300px" align="center" style="border:1px solid #000000;


background-color:#efefef;">

<tr><td colspan=2></td></tr>

<tr><td colspan=2></td></tr>

<tr>

<td><b>Login Name</b></td>
<td><input type="text" name="userName" value=""></td>

</tr>

<tr>

<td><b>Password</b></td>

<td><input type="password" name="password" value=""></td>

</tr>

<tr>

LIT/CSE/2024-25 35
220860131021 Advanced Java Programming (3160707)

<td></td>

<td><input type="submit" name="Submit" value="Submit"></td>

</tr>

<tr><td colspan=2></td></tr>

</table>

</form>

</body>

</html>

Welcome.jsp file:

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Welcome</title>

</head>

<body>

<br><br><br><br>

<table align="center" style="border:1px solid #000000;">

<%

if(session.getAttribute("username")!=null &&
session.getAttribute("username")!="")

String user = session.getAttribute("username").toString();

%>

<tr><td align="center"><h1>Welcome <b><%=user


%></b></h1></td></tr>

<%

LIT/CSE/2024-25 36
220860131021 Advanced Java Programming (3160707)

%>

</table>

</body>

</html>

Loginbean.jsp file:

<%@ page import="java.sql.*" language="java" contentType="text/html;


charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>DatabaseSearch</title>

</head>

<body>

<jsp:useBean id="db" scope="request" class="logbean.LoginBean">


<jsp:setProperty name="db" property="userName" param="userName"/>

<jsp:setProperty name="db" property="password" param="password"/>

</jsp:useBean>

<%

session.setAttribute("username", db.getUserName());

session.setAttribute("password", db.getPassword());

response.sendRedirect("Welcome.jsp");

%>

</body>

</html>

LIT/CSE/2024-25 37
220860131021 Advanced Java Programming (3160707)

LoginBean.java file:

package logbean;

public class LoginBean

String userName="";

String password="";

public String getUserName()

return userName;

public void setUserName(String userName)

this.userName=userName;

public String getPassword()

return password;

public void setPassword(String password)

this.password=password;

LIT/CSE/2024-25 38
220860131021 Advanced Java Programming (3160707)

Login.java file:

package logbean;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.sql.*;

import javax.sql.*;

public class Login extends HttpServlet

private static final long serialVersionUID = 1L;

@SuppressWarnings("deprecation")

public void doPost(HttpServletRequest req, HttpServletResponse res) throws


ServletException, IOException

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

System.out.println("MySQL Connect Example");

Connection con = null;

String url = "jdbc:mysql://localhost:3306/user_register?";

String driver = "com.mysql.cj.jdbc.Driver";

String userName = "root";

String password = "root";

String username = "";

String userpass = "";

String strQuery = "";

PreparedStatement ps = null;

LIT/CSE/2024-25 39
220860131021 Advanced Java Programming (3160707)

ResultSet rs = null;

HttpSession session = req.getSession(true);

try

Class.forName(driver).newInstance();

con = DriverManager.getConnection(url,userName,password);

if(req.getParameter("username")!=null &&
req.getParameter("username")!="" && req.getParameter("password")!=null &&
req.getParameter("password")!="")

username = req.getParameter("username").toString();

userpass = req.getParameter("password").toString();

strQuery = "select * from userregister where username= ? and


password= ?";

System.out.println(strQuery);

ps = con.prepareStatement(strQuery);

ps.setString(1, username);

ps.setString(2, password);

rs = ps.executeQuery();

int count = 0;

while(rs.next())

session.setAttribute("username",rs.getString(2));
count++;

if(count>0)

res.sendRedirect("Welcome.jsp");

else

LIT/CSE/2024-25 40
220860131021 Advanced Java Programming (3160707)

res.sendRedirect("Login.jsp");

else

res.sendRedirect("Login.jsp");

}
System.out.println("Connected to the database");

con.close();

System.out.println("Disconnected from database");

catch(Exception e)

e.printStackTrace();

Output:

LIT/CSE/2024-25 41
220860131021 Advanced Java Programming (3160707)

LIT/CSE/2024-25 42
220860131021 Advanced Java Programming (3160707)

Practical: 10
AIM: Write a Client Server program using TCP where client sends two
numbers and server responds with the sum of them.
Code:

Server.java file:

import java.io.*;

import java.net.*;

class Server
{

public static void main(String args[]) throws Exception


{

ServerSocket ss = new ServerSocket(555);

Socket s = ss.accept();

System.out.println("Client get Connected");

BufferedReader br = new BufferedReader(new


InputStreamReader(s.getInputStream()));

double sum, num1, num2;

String result;
num1 = Double.parseDouble(br.readLine());

System.out.println("From Client:" + num1);

num2 = Double.parseDouble(br.readLine());
System.out.println("From Client:" + num2);

sum = num1 + num2;

result = "Sum is :" + sum;

PrintStream ps = new PrintStream(s.getOutputStream());

ps.print(result);
br.close();

ps.close();

LIT/CSE/2024-25 43
220860131021 Advanced Java Programming (3160707)

s.close();

ss.close();

Client.java file:

import java.net.*;

import java.io.*;

class Client

public static void main(String args[]) throws Exception

Socket s = new Socket("localhost", 555);

BufferedReader br1 = new BufferedReader(new


InputStreamReader(System.in));

String num1, num2;

System.out.println("Enter the first number:");


num1 = br1.readLine();

System.out.println("Enter the second number:");

num2 = br1.readLine();

PrintStream ps = new PrintStream(s.getOutputStream());

ps.println(num1);

ps.println(num2);

BufferedReader br = new BufferedReader(new


InputStreamReader(s.getInputStream()));

String result = br.readLine();


System.out.println("From Server" + result);

br.close();

br1.close();

LIT/CSE/2024-25 44
220860131021 Advanced Java Programming (3160707)

ps.close();

s.close();

Output:

Server side:

Client side:

LIT/CSE/2024-25 45
220860131021 Advanced Java Programming (3160707)

Practical: 11
AIM: Write a two-way chat application using swing and socket
programming.
Code:

ChatServer.java:

import java.io.*;

import java.util.*;

import java.net.*;

import static java.lang.System.out;

class ChatServer
{

Vector<String> users = new Vector<String>();

Vector<HandleClient> clients = new Vector<HandleClient>();

public void process() throws Exception

ServerSocket server = new ServerSocket(777,10);

System.out.println("Server Started....");

while(true)

Socket client = server.accept();

HandleClient c = new HandleClient(client);


clients.add(c);

public static void main(String args[]) throws Exception

LIT/CSE/2024-25 46
220860131021 Advanced Java Programming (3160707)

new ChatServer().process();

public void broadcast(String user, String message)

for(HandleClient c : clients)

if(! c.getUserName().equals(user))
{

c.sendMessage(user,message);

class HandleClient extends Thread

String name = "";

BufferedReader input;

PrintWriter output;

public HandleClient(Socket client) throws Exception

input = new BufferedReader(new


InputStreamReader(client.getInputStream()));

output = new PrintWriter(client.getOutputStream(),true);

name = input.readLine();

users.add(name);

start();

public void sendMessage(String uname, String msg)

LIT/CSE/2024-25 47
220860131021 Advanced Java Programming (3160707)

output.println(uname+":"+msg);

public String getUserName()

return name;

public void run()


{

String line;

try

while(true)

line = input.readLine();

if(line.equals("end"))

clients.remove(this);

users.remove(name);

break;

ChatServer.this.broadcast(name,line);

}
}

catch(Exception ex)

System.out.println(ex.getMessage());

LIT/CSE/2024-25 48
220860131021 Advanced Java Programming (3160707)

ChatClient.java:

import java.io.*;

import java.util.*;

import java.net.*;

import javax.swing.*;
import java.awt.*;

import java.awt.event.*;

import static java.lang.System.out;

class ChatClient extends JFrame implements ActionListener

String uname;

PrintWriter pw;

BufferedReader br;

JTextArea taMessages;

JTextField tfInput;

JButton btnSend,btnExit;

Socket client;

public ChatClient(String uname,String servername) throws Exception


{

super(uname);

this.uname = uname;

client = new Socket("localhost",777);

br = new BufferedReader(new InputStreamReader(client.getInputStream()));

pw = new PrintWriter(client.getOutputStream(),true);

LIT/CSE/2024-25 49
220860131021 Advanced Java Programming (3160707)

pw.println(uname);

buildInterface();

new MessagesThread().start();

public void buildInterface()

btnSend = new JButton("Send");

btnExit = new JButton("Exit");


taMessages = new JTextArea();

taMessages.setRows(10);

taMessages.setColumns(50);

taMessages.setEditable(false);

tfInput = new JTextField(50);

JScrollPane sp = new
JScrollPane(taMessages,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScr
ollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

add(sp,"Center");

JPanel bp = new JPanel(new FlowLayout());

bp.add(tfInput);
bp.add(btnSend);

bp.add(btnExit);

add(bp,"South");

btnSend.addActionListener(this);

btnExit.addActionListener(this);

setSize(500,300);

setVisible(true);

pack();
}

public void actionPerformed(ActionEvent evt)

LIT/CSE/2024-25 50
220860131021 Advanced Java Programming (3160707)

if(evt.getSource() == btnExit)

pw.println("end");

System.exit(0);

else

{
pw.println(tfInput.getText());

tfInput.setText("");

public static void main(String args[])

String name = JOptionPane.showInputDialog(null,"Enter your


name:","Username",JOptionPane.PLAIN_MESSAGE);

String servername = "localhost";


try

new ChatClient(name,servername);

catch(Exception ex)

System.out.println("Error -->"+ex.getMessage());

class MessagesThread extends Thread

LIT/CSE/2024-25 51
220860131021 Advanced Java Programming (3160707)

public void run()

String line;

try

while(true)

{
line = br.readLine();

taMessages.append(line+"\n");

catch(Exception ex)

Output:

Client 1:

LIT/CSE/2024-25 52
220860131021 Advanced Java Programming (3160707)

Client 2:

LIT/CSE/2024-25 53

You might also like