Practical 1:-
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
publicclass MyServer {
while(!msg.equals("quit"))
{
b=newbyte[1024];
pack=new DatagramPacket(b,b.length);
ds.receive(pack);
b=pack.getData();
msg=new String(b);
msg=msg.trim();
System.out.println("\nFrom Client::"+msg);
System.out.println("Msg to Client::");
msg=scan.nextLine();
b=msg.getBytes();
InetAddress ip=InetAddress.getByName("localhost");
pack=new DatagramPacket(b,b.length,ip,2345);
ds.send(pack);
SVIT-VASAD 1|Page
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
}}
catch(Exception e)
{
System.out.println("Server error..."+e.getMessage());
}}}
MyClient.java file :-
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
pack=new DatagramPacket(b,b.length,ip,4567);
ds.send(pack);
b=new byte[1024];
pack=new DatagramPacket(b,b.length);
ds.receive(pack);
b=pack.getData();
msg=new String(b);
msg=msg.trim();
SVIT-VASAD 2|Page
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Output :-
1)server:-
2)client:-
SVIT-VASAD 3|Page
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
1(b) Implement TCP Server for transferring files using Socket and
ServerSocket.
MyServer.java file :-
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileReader;
import java.net.ServerSocket;
import java.net.Socket;
String fname=dis.readUTF();
SVIT-VASAD 4|Page
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
if(line!=null)
send=send+line+"\n";
}
dos.writeUTF(send);
}
else
dos.writeUTF("File Not Found");
client.close();
ser.close();
}
catch(Exception e)
{
System.out.println("Server Error..."+e.getMessage());
}
}
}
MyClient.java file :-
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileWriter;
import java.net.Socket;
import java.util.Scanner;
publicclass MyClient {
SVIT-VASAD 5|Page
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
dos.writeUTF(fname);
String found=dis.readUTF();
System.out.println(found);
Output :-
SVIT-VASAD 6|Page
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Practical 2:-
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
publicclass SortServer
{
publicstaticvoid main(String[] args)
{
try
{
ServerSocket ser=new ServerSocket(1234);
System.out.println("\n\nSERVER IS WAITING...");
Socket client=ser.accept();
System.out.println("\n\nWEL-COME CLIENT...");
DataInputStream dis=new DataInputStream(client.getInputStream());
DataOutputStream dos=new DataOutputStream(client.getOutputStream());
int a;
a=dis.readInt();
int b[]=newint[a];
for(int i=0;i<a;i++)
{
b[i]=dis.readInt();
}
Arrays.sort(b);
for(int i=0;i<a;i++)
{
dos.writeInt(b[i]);
}
client.close();
SVIT-VASAD 7|Page
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
ser.close();
}
catch(Exception e)
{
System.out.println("\nSERVER ERROR::"+e.getMessage());
}
}}
SortServer.java file :-
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner;
publicclass SortClient
{
publicstaticvoid main(String[] args)
{
try
{
Socket server=new Socket("localhost",1234);
DataInputStream dis=new DataInputStream(server.getInputStream());
DataOutputStream dos=new DataOutputStream(server.getOutputStream());
Scanner scan=new Scanner(System.in);
int a,b,c;
System.out.println("Enter how many Numbers you want to sort::");
a=scan.nextInt();
//int c[]=new int[a];
dos.writeInt(a);
System.out.println("Enter numbers");
for(int i=0;i<a;i++)
{
b=scan.nextInt();
dos.writeInt(b);
}
System.out.println("Sendind data to server completed...");
System.out.println("Receiving sorted data from server...\n");
for(int i=0;i<a;i++)
SVIT-VASAD 8|Page
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
{
c=dis.readInt();
System.out.println("\t"+c);
}
server.close();
}
catch(Exception e)
{
System.out.println("CLIENT ERROR..."+e.getMessage());
}
}}
Output:-
SVIT-VASAD 9|Page
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
RevServer.java file :-
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
RevString(Socket client)
{
th=new Thread(this);
this.client=client;
th.start();
}
publicvoid run()
{
try
{
dis=new DataInputStream(client.getInputStream());
dos=new DataOutputStream(client.getOutputStream());
str_msg=dis.readUTF();
StringBuffer sb=new StringBuffer(str_msg);
sb=sb.reverse();
str_msg=sb.toString();
dos.writeUTF(str_msg);
dos.close();
dis.close();
client.close();
SVIT-VASAD 10 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
}
catch(Exception e)
{
System.out.println("serverthread error : "+e.getMessage());
}
}
}
publicclass RevServer
{
publicstaticvoid main(String[] args)throws Exception
{
ServerSocket ss=null;
Socket client=null;
Try
{
ss=new ServerSocket(1010);
int count=0;
while(count<2)
{
client=ss.accept();
new RevString(client);
count++;
}
}
catch(Exception e)
{
System.out.println("serverside error : "+e.getMessage());
}
finally {
ss.close();
}
}}
RevClient1.java file :-
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner;
SVIT-VASAD 11 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Output :-
SVIT-VASAD 12 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
RevClient2.java file :-
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner;
publicclass RevClient02
{
publicstaticvoid main(String[] args)throws Exception
{
Socket server=null;
Scanner scan=null;
DataInputStream dis=null;
DataOutputStream dos=null;
try {
scan=new Scanner(System.in);
server=new Socket("localhost",1010);
dis=new DataInputStream(server.getInputStream());
dos=new DataOutputStream(server.getOutputStream());
String str_msg="";
System.out.println("enter the msg...!!!");
str_msg=scan.next();
dos.writeUTF(str_msg);
str_msg=dis.readUTF();
System.out.print("Reverse : "+str_msg);
}
catch(Exception e)
{System.out.println("Client02 error : "+e.getMessage());}
finally {
dos.close();
dis.close();
scan.close();
server.close();
}}}
Output :-
SVIT-VASAD 13 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Practical 3:-
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
SVIT-VASAD 14 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Output :-
SVIT-VASAD 15 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
3(b ) User can create a new database and also create new table
under that database. Once database has been created then user
can perform database operation by calling above functions. Use
following Java Statement interface to implement program: 1.
Statement 2. Prepared statement 3. Callable statement
StatementExample.java File :-
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.Types;
import java.util.Scanner;
class DataOperation
{
Scanner scan=new Scanner(System.in);
void statement()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/stddb19","root",""
);
Statement st=con.createStatement();
int id,age;
String na;
System.out.println("ENTER ID-NAME-AGE::");
id=scan.nextInt();
na=scan.next();
age=scan.nextInt();
int a=st.executeUpdate("insert into mytab values("+id+",'"+na+"',"+age+")");
System.out.println(a+" rows updated");
st.close();
con.close();
SVIT-VASAD 16 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
}
catch(Exception e)
{
System.out.println("\nDATABASE ERROR:"+e.getMessage());
}
}
void prepared()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/stddb19","root",""
);
PreparedStatement pst=con.prepareStatement("insert into mytab
values(?,?,?)");
int id=1,age,c=0,a=0;
String na;
while(id!=0)
{
System.out.println("ENTER ID-NAME-AGE::");
id=scan.nextInt();
na=scan.next();
age=scan.nextInt();
pst.setInt(1, id);
pst.setString(2,na);
pst.setInt(3,age);
if(id!=0)
{
a=pst.executeUpdate();
c+=a;
}
System.out.println(c+" rows updated");
}
pst.close();
con.close();
}
catch(Exception e)
{
SVIT-VASAD 17 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
System.out.println("\nDATABASE ERROR:"+e.getMessage());
}
}
void callableout()
{try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/stddb19","root",""
);
CallableStatement cst=con.prepareCall(" { call without(?,?) } ");
int id,age,c=0;
String na;
System.out.println("ENTER ID::");
id=scan.nextInt();
cst.setInt(1, id);
cst.registerOutParameter(2,Types.VARCHAR);
cst.execute();
na=cst.getString(2);
System.out.println("\n\nNAME::"+na);
cst.close();
con.close();
}
catch(Exception e)
{
System.out.println("\nDATABASE ERROR:"+e.getMessage());
}
}
}
public class StatementExample
{
public static void main(String[] args)
{
Scanner scan=new Scanner(System.in);
int ch=0;
DataOperation dp=new DataOperation();
while(ch!=4)
{
System.out.println("\n::DATABASE MENU::");
System.out.println("1. STATEMET INSERT");
SVIT-VASAD 18 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Output :-
SVIT-VASAD 19 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Practical 4:-
Create Servlet file and study web descriptor file
Web.xml file :-
<?xmlversion="1.0"encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>gtu</servlet-name>
<servlet-class>PowerNo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>gtu</servlet-name>
<url-pattern>/Power</url-pattern>
</servlet-mapping>
</web-app>
index.html file :-
<!DOCTYPEhtml>
<html>
<head>
<metacharset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<formaction="Power">
Enter Base::<inputtype="text"name="t1"/><br><br>
Enter Power::<inputtype="text"name="t2"/><br><br>
<inputtype="submit"value="power"/>
</form>
</body>
</html>
PowerNo.java file :-
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
SVIT-VASAD 20 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PowerNo extends HttpServlet
{
Output :-
SVIT-VASAD 21 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Practical 5:-
Create Servlet file which contains following functions: 1. Connect
2. Create Database 3. Create Table 4. Insert Records into respective
table 5. Update records of particular table of database 6. Delete
Records from table. 7. Delete table and also database.
Index.html file :-
<html>
<head>
<title>LogInpage</title>
</head>
<body>
<formaction="RedirectServlet"name="ind">
<inputtype="radio"name="rad"value="createdatabase">create database<br>
<inputtype="radio"name="rad"value="createtable">create table<br>
<inputtype="radio"name="rad"value="insertrecord">insert record<br>
<inputtype="radio"name="rad"value="updaterecord">update record<br>
<inputtype="radio"name="rad"value="deleterecord">delete record<br>
<inputtype="radio"name="rad"value="deletetable">delete table<br>
<inputtype="radio"name="rad"value="deletedatabase">delete
database<br><br>
<inputtype="submit"name="sub"value="execute">
<inputtype="reset"value="Reset"><br><br>
</form>
</body>
</html>
Record.html
<html>
<head>
</head>
<body>
<formaction="checkPlayer"name="signupform">
table name : <inputtype="text"name="tbname"><br>
id : <inputtype="text"name="sid"><br>
name : <inputtype="text"name="sna"><br>
age : <inputtype="text"name="sag"><br>
<inputtype="submit"name="sub"value="insert record">
SVIT-VASAD 22 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
<inputtype="submit"name="sub"value="delete record">
</form>
</body>
</html>
Deldb.html:-
<!DOCTYPEhtml>
<html>
<head>
<metacharset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<formaction="checkPlayer">
enter the database name : <inputtype="text"name="name"><br>
<inputtype="submit"name="sub"value="create db">
<inputtype="submit"name="sub"value="delete db">
</form>
</body>
</html>
Deltab.html :-
<!DOCTYPEhtml>
<html>
<head>
<metacharset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<formaction="checkPlayer"name="signupform">
enter the table name : <inputtype="text"name="name"><br>
<inputtype="submit"name="sub"value="create table">
<inputtype="submit"name="sub"value="delete table">
</form>
</body>
</html>
Update.html :-
<!DOCTYPEhtml>
SVIT-VASAD 23 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
<html>
<head>
<metacharset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<formaction="checkPlayer"name="signupform">
table name : <inputtype="text"name="tbname"><br>
<h2>set</h2>
name : <inputtype="text"name="sna"><br><br>
age : <inputtype="text"name="sag"><br>
<h2>where</h2>
id : <inputtype="text"name="sid"><br><br>
<inputtype="submit"name="sub"value="update">
</form>
</body>
</html>
Error.html:-
<html>
<head>
<title>Errorpage</title>
</head>
<body>
<ahref="index.html">back to </a>
</body>
</html>
AccountLog.java File :-
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
SVIT-VASAD 24 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/checkPlayer")
public class AccountLog extends HttpServlet
{
protected void service(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
String type=request.getParameter("sub");
if(type.matches("create db"))
{
String na=request.getParameter("name");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost","root","");
Statement st=con.createStatement();
st.executeUpdate("create database "+na);
PrintWriter pout=response.getWriter();
pout.print("database created successfully : ");
st.close();
con.close();
}
catch(Exception e)
{
System.out.println("LoginServlet error : "+e.getMessage());
}
}
else if(type.matches("delete db"))
{
String na=request.getParameter("name");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost","root","");
Statement st=con.createStatement();
st.executeUpdate("drop database "+na);
SVIT-VASAD 25 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
PrintWriter pout=response.getWriter();
pout.print("database delete successfully : ");
st.close();
con.close();
}
catch(Exception e)
{
System.out.println("LoginServlet error : "+e.getMessage());
}
}
else if(type.matches("create table"))
{
String na=request.getParameter("name");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/stddb19","root",""
);
Statement st=con.createStatement();
st.executeUpdate("create table "+na+"(sid int,sna text,sag int,primary
key(sid))");
PrintWriter pout=response.getWriter();
pout.print("table created successfully : ");
st.close();
con.close();
}
catch(Exception e)
{
System.out.println("LoginServlet error : "+e.getMessage());
}
}
else if(type.matches("delete table"))
{
String na=request.getParameter("name");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/stddb19","root",""
);
Statement st=con.createStatement();
SVIT-VASAD 26 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
SVIT-VASAD 27 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/stddb19","root",""
);
Statement st=con.createStatement();
st.executeUpdate("delete from "+na+" where sid="+sid);
PrintWriter pout=response.getWriter();
pout.print("record deleted successfully : ");
st.close();
con.close();
}
catch(Exception e)
{
System.out.println("LoginServlet error : "+e.getMessage());
}
}
else if(type.matches("update"))
{
String na=request.getParameter("tbname");
int sid=Integer.parseInt(request.getParameter("sid"));
String sna=request.getParameter("sna");
int sag=Integer.parseInt(request.getParameter("sag"));
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/stddb19","root",""
);
Statement st=con.createStatement();
st.executeUpdate("update "+na+" set sna='"+sna+"' and sag="+sag+" where
sid="+sid);
PrintWriter pout=response.getWriter();
pout.print("record updated successfully : ");
st.close();
con.close();
}
catch(Exception e)
{
System.out.println("LoginServlet error : "+e.getMessage());
}
}
else
SVIT-VASAD 28 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
{
request.getRequestDispatcher("/error.html").forward(request,response);
}
}
}
RedirectServlet.java file :-
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;
@WebServlet("/RedirectServlet")
public class RedirectServlet extends HttpServlet
{
protected void service(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
String page=request.getParameter("rad");
if(page.matches("createdatabase") || page.matches("deletedatabase"))
{
request.getRequestDispatcher("/deldb.html").forward(request, response);
}
else if(page.matches("createtable") || page.matches("deletetable"))
{
request.getRequestDispatcher("/deltab.html").forward(request, response);
}
else if(page.matches("insertrecord") || page.matches("deleterecord"))
{
request.getRequestDispatcher("/record.html").forward(request, response);
}
SVIT-VASAD 29 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
else if(page.matches("updaterecord"))
{
request.getRequestDispatcher("/update.html").forward(request, response);
}
else
{
request.getRequestDispatcher("/error.html").forward(request, response);
}
}}
Output :-
1)index.html
2)create database
3)database created
4)create table
SVIT-VASAD 30 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
5)table created
6)insert data
7)update data
SVIT-VASAD 31 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Practical 6 :-
Create login form and perform state management using Cookies,
HttpSession and URL Rewriting.
Index.jsp file :
<%@pagelanguage="java"contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!-- <%@includefile="header.jsp"%>-->
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01
Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
Cookie c[]=request.getCookies();
if(c!=null)
{
for(int i=0;i<c.length;i++)
{
if(c[i].getValue().equals("allow"))
{
HttpSession hs=request.getSession();
hs.setAttribute("allowme", "yes");
request.getRequestDispatcher("/Mul.jsp").forward(request,response);
}
}
}
%>
<formname=f1action="forLogin">
UserNmae::<inputtype="text"name="tus"/><br><br>
Password::<inputtype="password"name="tpa"/><br><br>
<inputtype="checkbox"name="keep"value="keepme"/>KEEP ME LOGGED IN
<BR>
<inputtype="submit"name="sub"value="Login"/>
<inputtype="reset"name="res"value="Cancle"/>
SVIT-VASAD 32 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
<inputtype="submit"name="sub"value="Sign-up"/>
</form>
</body>
</html>
LoginSevlet.java File
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/forLogin")
public class LoginServlet extends HttpServlet {
protected void service(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
PrintWriter out=response.getWriter();
HttpSession hs=request.getSession(); //used to create new session
hs.setAttribute("allowme", "yes");
String keep=request.getParameter("keep");
if(keep!=null)
{
Cookie c1=new Cookie("always","allow");
response.addCookie(c1);
}
String us=request.getParameter("tus");
String pa=request.getParameter("tpa");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/multipleservlet","r
oot","");
Statement st=con.createStatement();
SVIT-VASAD 33 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Output :-
SVIT-VASAD 34 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Practical 7 :-
Implement Authentication filter using filter API.
Index.jsp file:-
<%@pagelanguage="java"contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@includefile="header.jsp"%>
<%
Cookie c[]=request.getCookies();
if(c!=null)
{
for(int i=0;i<c.length;i++)
{
if(c[i].getValue().equals("allow"))
{
HttpSession hs=request.getSession();
hs.setAttribute("allowme", "yes");
request.getRequestDispatcher("/Mul.jsp").forward(request,response);
}
}
}
%>
<formname=f1action="forLogin">
UserNmae::<inputtype="text"name="tus"/><br><br>
Password::<inputtype="password"name="tpa"/><br><br>
<inputtype="checkbox"name="keep"value="keepme"/>KEEP ME LOGGED IN
<BR>
SVIT-VASAD 35 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
<inputtype="submit"name="sub"value="Login"/>
<inputtype="reset"name="res"value="Cancle"/>
<inputtype="submit"name="sub"value="Sign-up"/>
</form>
</body>
</html>
header.jsp file :-
<%@pagelanguage="java"contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@pageimport="java.util.*"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01
Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1align="center"style="color:red; text-decoration:underline;">
SardarVallabhbhaiPatel Institute Of Technology(SVIT)
</h1>
<h2>Information Technology Department</h2>
<%
Date d1=new Date();
out.print("<h2 align='right'>"+d1+"</h2>");
%>
<hr>
</body>
</html>
Signup.jsp file :-
<%@pagelanguage="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@includefile="header.jsp" %>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01
Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
SVIT-VASAD 36 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Mul.jsp file:-
<%@pagelanguage="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@include file="header.jsp" %>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD HTML 4.01
Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String check=(String)session.getAttribute("allowme");
if(check==null)
{
request.getRequestDispatcher("/Index.jsp").forward(request,response);
}
else
{
%> <!-- scriptlet Finished -->
<br><br>
<formaction="mul">
Enter No::<inputtype="text" name="t1"/><br><br>
<inputtype="submit" value="multiplication Table"/>
</form>
<%} %>
</body>
</html>
SVIT-VASAD 37 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
LoginFilter.java File :-
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
@WebFilter("/forLogin")
public class LoginFilter implements Filter
{
public LoginFilter()
{}
public void destroy()
{}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException
{
String us=request.getParameter("tus");
String pa=request.getParameter("tpa");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/multipleservlet","r
oot","");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from mulser where uname='"+us+"'
and password='"+pa+"'");
if(rs.next())
{ chain.doFilter(request, response); }
else if(request.getParameter("sub").matches("Sign-up"))
{
st.executeUpdate("insert into mulser values('"+us+"','"+pa+"')");
SVIT-VASAD 38 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
request.getRequestDispatcher("/signup.jsp").forward(request,response);
}
else
{
request.getRequestDispatcher("/error.jsp").forward(request,response);
}
}
catch(Exception e)
{
System.out.println("Error..."+e.getMessage());
}
}
public void init(FilterConfig fConfig) throws ServletException
{}
}
LoginServlet.java File :-
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/forLogin")
public class LoginServlet extends HttpServlet {
SVIT-VASAD 39 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
if(keep!=null)
{
Cookie c1=new Cookie("always","allow");
response.addCookie(c1);
}
request.getRequestDispatcher("/Mul.jsp").include(request, response);
}
}
Output :-
1)
2)
SVIT-VASAD 40 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
3)
SVIT-VASAD 41 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Practical 8 :-
Create database of student subject-wise data and retrieve all data using JSP
and generate xml structure along with DTD and XML Schema definition
index.jsp file :-
<%--
Document: index
Created on: Mar 29, 2018, 9:51:41 AM
Author: admin
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h3>Students Info:</h3>
<c:import var="studentInfo" url="student.xml"/>
<x:parse xml="${studentInfo}" var="output"/>
<table border="1">
<tr>
<th>Student id</th>
<th>Student name</th>
<th>Subject1 name</th>
<th>Subject1 marks</th>
<th>Subject2 name</th>
<th>Subject2 marks</th>
</tr>
<x:forEach select="$output/students/student" var="item">
<tr>
<td>
<x:out select="$item/id" />
</td>
<td>
<x:out select="$item/name" />
</td>
<td>
SVIT-VASAD 42 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
<x:out select="$item/subject[1]/subject_name"/>
</td>
<td>
<x:out select="$item/subject[1]/subject_marks"/>
</td>
<td>
<x:out select="$item/subject[2]/subject_name"/>
</td>
<td>
<x:out select="$item/subject[2]/subject_marks"/>
</td>
</tr>
</x:forEach>
</table>
</body>
</html>
student.xml file :-
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE students [
<!ELEMENT students (student+)>
<!ELEMENT student (id,name,subject+)>
<!ELEMENT subject (subject_name,subject_marks)>
<!ELEMENT id (#PCDATA)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT subject_name (#PCDATA)>
<!ELEMENT subject_marks (#PCDATA)>
]>
<students>
<student>
<id>1</id>
<name>Rishi</name>
<subject>
<subject_name>AJ</subject_name>
<subject_marks>80</subject_marks>
</subject>
<subject>
<subject_name>WT</subject_name>
<subject_marks>90</subject_marks>
SVIT-VASAD 43 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
</subject>
</student>
<student>
<id>2</id>
<name>Varun</name>
<subject>
<subject_name>AJ</subject_name>
<subject_marks>85</subject_marks>
</subject>
<subject>
<subject_name>WT</subject_name>
<subject_marks>85</subject_marks>
</subject>
</student>
<student>
<id>3</id>
<name>Hetul</name>
<subject>
<subject_name>AJ</subject_name>
<subject_marks>85</subject_marks>
</subject>
<subject>
<subject_name>WT</subject_name>
<subject_marks>75</subject_marks>
</subject>
</student>
</students>
student2.xml
<?xml version="1.0"?>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<xs:schema version="1.0"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:element name="students">
SVIT-VASAD 44 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
<xs:complexType>
<xs:sequence>
<xs:element name="student" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="id" type="xs:decimal"/>
<xs:element name="name" type="xs:string"/>
<xs:element name="subject" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="sub_name" type="xs:string"/>
<xs:element name="sub_marks" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element></xs:schema>
Output:-
SVIT-VASAD 45 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Practical 9 :-
Implement Action tags using JSP.
JSP Action
JSP actions use the construct in XML syntax to control the behavior of the
servlet engine.
We can dynamically insert a file, reuse the beans components, forward user to
another page, etc. through JSP Actions like include and forward.
Unlike directives, actions are re-evaluated each time the page is accessed.
Syntax:
jsp:useBean
jsp:include
jsp:setProperty
jsp:getProperty
jsp:forward
jsp:plugin
jsp:attribute
jsp:body
jsp:text
jsp:param
jsp:attribute
jsp:output
1. jsp:useBean:
This action name is used when we want to use beans in the JSP page.
SVIT-VASAD 46 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Here it specifies the identifier for this bean and class is full path of the bean class
Example:
pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Action JSP1</title>
</head>
<body>
</body>
</html>
Code Line 10: In the above code we use "bean id" and "class path" of the bean.
2. include
It also used to insert a jsp file into another file, just like include directive.
Syntax of jsp:include
Example:
SVIT-VASAD 47 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Date JSP</title>
</head>
<body>
</body>
</html>
Date.jsp
pageEncoding="ISO-8859-1"%>
<html>
<head>
</head>
<body>
<p>
SVIT-VASAD 48 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
</p>
</body>
</html>
Action_jsp2.jsp
Code Line 10: In the first file we are including the date.jsp file in action_jsp2.jsp
Date.jsp:
Code Line 11: We are printing today's date in code line 11 in date.jsp
Output:
It displays today's date with time as date file is included in the main jsp
3. setProperty
Syntax:
Here, the name defines the bean whose property is set and property which we want to
set.
Here value is not mandatory, and it defines the value which is assigned to the
property.
SVIT-VASAD 49 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Here param is the name of the request parameter using which value can be fetched.
4. getProperty
Syntax:
Here, the name of the bean from which the property has to be retrieved and bean
should be defined. The property attribute is the name of the bean property to be
retrieved.
TestBean.java:
package demotest;
import java.iO.Serializable;
return msg;
this.msg = msg;
SVIT-VASAD 50 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Action_jsp3.jsp
pageEncoding="ISO-8859-1"%>
<html>
<head>
</head>
<body>
</body>
</html>
TestBean.java:
Code Line 7: Here we are taking private string variable msg as "null"
Code Line 9-14: Here we are using getters and setters of variable "msg".
Action_jsp3.jsp
Code Line 10: Here we are using "useBean" tag, where it specifies the bean i.e
TestBean which has to be used in this jsp class
SVIT-VASAD 51 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Code Line 11: Here we are setting the value for the property msg for bean TestBean
as "Tutorial."
CodeLine12: Here using getProperty, we are getting the value of property msg for
bean TestBean i.e Tutorial which is there in the output
When you execute the above code you get the following output:
Output:
In this example, using TestBean we are trying to set the property "test" using
setProperty and get the value of property using getProperty as "Tutorial"
5. forward:
Syntax:
<jsp:forward page="value">
Example:
Action_jsp41.jsp
pageEncoding="ISO-8859-1"%>
<html>
<head>
SVIT-VASAD 52 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
</head>
<body>
</body>
</html>
Jsp_action_42.jsp
Action JSP2</title>
</head>
<body>
</body>
</html>
Action_jsp41.jsp
Code Line 10: Here we are using forward JSP Action to forward the request to the
page mentioned in the attribute, i.e., jsp_action_42.jsp
Jsp_action_42.jsp
Code Line 10: Once we call action_jsp41.jsp, the request gets forwarded to this page,
and we get the output as "This is after forward page."
SVIT-VASAD 53 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Output:
6. plugin
It is used to introduce Java components into jsp, i.e., the java components can
be either an applet or bean.
It detects the browser and adds <object> or <embed> tags into the file
Syntax:
Code base contains the base URL that contains files of classes
7) param
Syntax:
<jsp:params>
</jsp:params>
Action_jsp5.jsp
pageEncoding="ISO-8859-1"%>
<html>
<head>
SVIT-VASAD 54 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
<title>Action jsp5</title>
</head>
<body>
<jsp:params>
</jsp:params>
</jsp:plugin>
</body>
</html>
Student.java
package demotest;
import java.io.Serializable;
return name;
this.name = name;
SVIT-VASAD 55 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
return id;
this.id = id;
private int id = 0;
Action_jsp5.jsp
Code Line 10: Here we are taking jsp: plugin object where we are taking three
attributes
Code Line 11-14: Here we are taking jsp: params object under which there is a child
param object with the attributes of name and value, and we are setting the values of id
and name in this attributes.
Student.java
Code 7- 17: We are using getters and setters for variables id and name
Here we will get output in the case when the set values of param will be used in
Student Bean. In this case, we won't have any output as we are just setting and getting
values of param but not printing it anywhere.
8) body:
This tag is used to define the XML dynamically i.e., the elements can generate
during request time than compilation time.
SVIT-VASAD 56 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Syntax:
<jsp:body></jsp:body>
9) attribute:
This tag is used to define the XML dynamically i.e. the elements can be
generated during request time than compilation time
Syntax:
<jsp:attribute></jsp:attribute>
Action_jsp6.jsp
pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Action JSP6</title>
</head>
<body>
<jsp:element name="XMLElement">
<jsp:attribute name="XMLattribute">
Value
SVIT-VASAD 57 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
</jsp:attribute>
<jsp:body> XML</jsp:body>
</jsp:element>
</body>
</html>
Code Line 10: Here we are defining element, which dynamically generated as XML,
and its name will be XMLElement
Code Line 11-13: Here we are defining an attribute which will XML attribute of the
dynamically generated XML.
Code Line 14: Here we have body action where we are writing the XML body which
will be generated in dynamically XML.
When you execute the above code, you get the following output:
Output:
Here we get the output from the body tag of generated XML.
10) text
Its body does not contain any other elements, and it contains only text and EL
expressions.
Syntax:
<jsp:text>template text</jsp:text>
Here template text refers to only template text (which can be any generic text which
needs to be printed on jsp ) or any EL expression.
Example:
SVIT-VASAD 58 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Action_jsp7.jsp
pageEncoding="ISO-8859-1"%>
<html>
<head>
</head>
<body>
<jsp:text>Template Text</jsp:text>
</body>
</html>
Code Line 10: Here we are taking text object to print the template text
When you execute the above code, you get the following output
Output:
We are getting Template Text, which is placed within text action objects.
11) output:
Syntax:
SVIT-VASAD 59 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Example:
pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Action JSP8</title>
</head>
<body>
</body>
</html>
Code Line 10: Here we are using output action object to generate a DOCTYPE, and
internally it will be generated in this format:
There won't be any output for this as this will be generated internally.
SVIT-VASAD 60 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Practical 10 :-
SVIT-VASAD 61 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Jsp file :-
<%--
Document : newjsp
Created on: Mar 30, 2018, 2:06:23 PM
Author : admin
--%>\
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="index.jsp">
Id: <input type="text" name="sid"/><br>
<input type="submit" value="view_data"/>
</form>
</body>
</html>
Output :-
SVIT-VASAD 62 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
SVIT-VASAD 63 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
10(b) Create Web Service client which consume above service and
display student data by entering student id.
Html file:-
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="index.jsp">
Id: <input type="text" name="sid"/><br>
<input type="submit" value="view_data"/>
</form>
</body>
</html>
Java file:
package abc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
@WebService(serviceName = "NewWebService")
public class NewWebService {
@WebMethod(operationName = "View_data")
public String View_data(@WebParam(name = "name") String id) {
int sid = 0;
String name = null;
try
{
SVIT-VASAD 64 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection
con=DriverManager.getConnection("jdbc:derby://localhost:1527/sample","ap
p","app");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from student where id="+id+"");
if(rs.next())
{
sid = rs.getInt("id");
name = rs.getString("name");
}
}
catch(Exception e)
{
}
return "ID:" + sid +" "+ "Name: " + name;
}
}
Output :-
SVIT-VASAD 65 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Practical 11 :-
Study and implement Hibernate
The ORM tool internally uses the JDBC API to interact with the database.
What is JPA?
Java Persistence API (JPA) is a Java specification that provides certain
functionality and standard to ORM tools. The javax.persistence package
contains the JPA classes and interfaces.
Advantages of Hibernate Framework
Following are the advantages of hibernate framework:
1) Open Source and Lightweight
Hibernate framework is open source under the LGPL license and lightweight.
2) Fast Performance
The performance of hibernate framework is fast because cache is internally
used in hibernate framework. There are two types of cache in hibernate
framework first level cache and second level cache. First level cache is enabled
by default.
3) Database Independent Query
HQL (Hibernate Query Language) is the object-oriented version of SQL. It
generates the database independent queries. So you don't need to write
database specific queries. Before Hibernate, if database is changed for the
project, we need to change the SQL query as well that leads to the
maintenance problem.
4) Automatic Table Creation
SVIT-VASAD 66 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Hibernate framework provides the facility to create the tables of the database
automatically. So there is no need to create tables in the database manually.
5) Simplifies Complex Join
Fetching data from multiple tables is easy in hibernate framework.
6) Provides Query Statistics and Database Status
Hibernate supports Query cache and provide statistics about query and
database status.
1) Create the Persistent class
A simple Persistent class should follow some rules:
A no-arg constructor: It is recommended that you have a default constructor at
least package visibility so that hibernate can create the instance of the
Persistent class by newInstance() method.
Provide an identifier property: It is better to assign an attribute as id. This
attribute behaves as a primary key in database.
Declare getter and setter methods: The Hibernate recognizes the method by
getter and setter method names by default.
Prefer non-final class: Hibernate uses the concept of proxies, that depends on
the persistent class. The application programmer will not be able to use
proxies for lazy association fetching.
SVIT-VASAD 67 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
employee.hbm.xml :-
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp1000">
<id name="id">
<generator class="assigned"></generator>
</id>
SVIT-VASAD 68 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
<property name="firstName"></property>
<property name="lastName"></property>
</class>
</hibernate-mapping>
hibernate.cfg.xml file :-
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property
>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</p
roperty>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDrive
r</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
StoreData.java file :-
package com.javatpoint.mypackage;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
SVIT-VASAD 69 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
session.save(e1);
t.commit();
System.out.println("successfully saved");
factory.close();
session.close();
}
}
SVIT-VASAD 70 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Output :-
SVIT-VASAD 71 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Practical 12 :-
Study and Implement MVC using Spring Framework
Spring MVC :-
Spring MVC is a module for enabling us to implement the MVC pattern.
Following image shows the Spring’s MVC architecture
DispatcherServlet
This class is a front controller that acts as central dispatcher for HTTP web
requests. Based on the handler mappings we provide in spring configuration, it
routes control from view to other controllers and gets processed result back
and routes it back to view.
SVIT-VASAD 72 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
<servlet>
<servlet-name>springDispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/spring-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
SVIT-VASAD 73 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Spring Configuration:-
This spring configuration file provides context information to spring container.
In our case,
The tag mvc:annotation-driven says that we are using annotation based
configurations. context:component-scan says that the annotated components
like Controller, Service are to be scanned automatically by Spring container
starting from the given package.
<context:component-scan base-package="com.javapapers.spring.mvc"
/>
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewRes
olver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
SVIT-VASAD 74 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
org.springframework.core-3.1.2.RELEASE.jar
org.springframework.expression-3.1.2.RELEASE.jar
org.springframework.web.servlet-3.1.2.RELEASE.jar
org.springframework.web-3.1.2.RELEASE.jar
javax.servlet.jsp.jstl-1.2.1.jar (http://jstl.java.net/download.html -> JSTL
Implementation)
These jars are part of standard spring framework download except the jstl.
Controller:-
Following controller class has got methods. First one hello maps to the url ‘/’.
Annotation has made our job easier by just declaring the annotation we order
Spring container to invoke this method whenever this url is called. return
“hello” means this is used for selecting the view. In spring configuration we
have declared InternalResourceViewResolver and have given a prefix and
suffix. Based on this, the prefix and suffix is added to the returned word “hello”
thus making it as “/WEB-INF/view/hello.jsp”. So on invoking of “/” the control
gets forwarded to the hello.jsp. In hello.jsp we just print “Hello World”.
org.springframework.web.servlet.view.InternalResourceViewResolver
Added to printing Hello World I wanted to give you a small bonus with this
sample. Just get an input from user and send a response back based on it. The
second method “hi” serves that purpose in controller. It gets the user input
and concatenates “Hi” to it and sets the value in model object. ‘model’ is a
special hashmap passed by spring container while invoking this method. When
we set a key-value pair, it becomes available in the view. We can use the key to
get the value and display it in the view which is our hi.jsp. As explained above
InternalResourceViewResolver is used to resole the view.
package com.javapapers.spring.mvc;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class HelloWorldController {
@RequestMapping("/")
public String hello() {
SVIT-VASAD 75 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
return "hello";
}
<hr/>
<form action="hi">
Name: <input type="text" name="name"><input type="submit"
value="Submit">
</form>
</body>
</html>
Use key “message” in model to get the value and print it.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Result</title>
</head>
<body>
<h1><c:out value="${message}"></c:out></h1>
</body>
</html>
SVIT-VASAD 76 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Output :-
SVIT-VASAD 77 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
(1)index.jsp
<%@ 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>Insert title here</title>
</head>
<body>
<form action="forLogin">
name : <input type="text" name="name"><br><br>
password : <input type="text" name="id"><br><br>
<input type="submit" name="sub" value="login"><br><br>
<a href="signup.jsp">create new account?</a><br><br>
<a href="display.jsp">blogs</a><br>
</form>
</body>
</html>
OUTPUT:
SVIT-VASAD 78 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
(2)signup.jsp
<%@ 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>Insert title here</title>
</head>
<body>
<form action="forLogin">
name : <input type="text" name="name"><br><br>
college : <input type="text" name="college"><br><br>
<input type="radio" name="rad" value="student">Student
<input type="radio" name="rad" value="teacher">Teacher<br><br>
email : <input type="text" name="email"><br><br>
<input type="submit" name="sub" value="signup"><br><br>
</form>
</body>
</html>
OUTPUT:
(3)blog.php
<%@page import="java.io.PrintWriter"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.io.*" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
SVIT-VASAD 79 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
HttpSession hs=request.getSession();
String isValid=(String)hs.getAttribute("user");
if(isValid==null)
{
request.getRequestDispatcher("/index.html").forward(request,
response);
}
else
{
String name=request.getParameter("name");
out.println("<h1>welcome "+name+"</h1><br><br>");
int _sno[]=new int[100];
int _id[]=new int[100];
int _lik[]=new int[100];
int _dik[]=new int[100];
String _topic[]=new String[100];
String _para[]=new String[100];
String _name[]=new String[100];
String _post[]=new String[100];
String _comment[]=new String[100];
int size=0;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/stddb","root","");
Statement st=con.createStatement();
ResultSet rs1=st.executeQuery("select * from blog");
int i=0;
while(rs1.next())
{
_sno[i]=rs1.getInt(1);
_id[i]=rs1.getInt(2);
_topic[i]=rs1.getString(3);
_para[i]=rs1.getString(4);
i++;
size++;
}
i=0;
for(int j=0;j<size;j++)
{
ResultSet rs2=st.executeQuery("select * from user
where id="+_id[j]);
while(rs2.next())
{
_name[j]=rs2.getString("name");
_post[j]=rs2.getString("post");
}
rs2.close();
i=0;
ResultSet rs3=st.executeQuery("select * from review");
SVIT-VASAD 80 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
while(rs3.next())
{
_lik[i]=rs3.getInt("lik");
_dik[i]=rs3.getInt("dik");
i++;
}
rs1.close();
rs3.close();
st.close();
con.close();
}
catch(Exception e)
{
System.out.println("LoginServlet error :
"+e.getMessage());
}
%>
<table border="1">
<tr>
<th>topic no.</th>
<th>topic</th>
<th>name</th>
<th>user id</th>
<th>post</th>
<th>blog</th>
<th>likes</th>
<th>dislikes</th>
</tr>
<%
for(int j=0;j<size;j++)
{
out.print("<tr>");
out.print("<td>");
out.println(_sno[j]);
out.print("</td>");
out.print("<td>");
out.println(_topic[j]);
out.print("</td>");
out.print("<td>");
out.println(_name[j]);
out.print("</td>");
out.print("<td>");
out.println(_id[j]);
out.print("</td>");
out.print("<td>");
out.println(_post[j]);
out.print("</td>");
out.print("<td>");
out.println(_para[j]);
out.print("</td>");
out.print("<td>");
out.println(_lik[j]);
out.print("</td>");
SVIT-VASAD 81 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
out.print("<td>");
out.println(_dik[j]);
out.print("</td>");
out.print("</tr>");
}
%>
</table>
<br><br>
<h1>Give your review</h1>
<form action="forReview">
<h4>
topic on. : <input type="text" name="sno"><br><br>
id : <input type="text" name="id" ><br><br>
<input type="radio" name="rad" value="like">Like
<input type="radio" name="rad" value="dislike">Dislike<br><br>
comment : <input type="text" name="comm"><br><br>
<input type="submit" name="sub1" value="submit"><br>
<a href="newblog.jsp">enter your blog</a>
</h4>
</form>
<%
}
%>
</body>
</html>
OUTPUT:
SVIT-VASAD 82 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
(4)newblog.php
OUTPUT:
(5)LoginServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
SVIT-VASAD 83 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/forLogin")
public class LoginServlet extends HttpServlet
{
protected void service(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
String acc=request.getParameter("sub");
if(acc.matches("login"))
{
int id=Integer.parseInt(request.getParameter("id"));
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/stddb","root","");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from user");
while(rs.next())
{
if(id==rs.getInt(1))
{
HttpSession hs=request.getSession();
hs.setAttribute("user", "logged");
request.getRequestDispatcher("/blog.jsp").forward(request, response);
}
}
st.close();
con.close();
}
catch(Exception e)
SVIT-VASAD 84 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
{
System.out.println("LoginServlet error :
"+e.getMessage());
}
}
else if(acc.matches("signup"))
{
HttpSession hs=request.getSession();
hs.setAttribute("user", "logged");
String name=request.getParameter("name");
String college=request.getParameter("college");
String post=request.getParameter("rad");
String email=request.getParameter("email");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/stddb","root","");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from user");
int i=0;
while(rs.next())
{
i++;
}
st.executeUpdate("insert into user
values("+(++i)+",'"+name+"','"+college+"','"+post+"','"+email+"')");
request.getRequestDispatcher("/blog.jsp").forward(request, response);
st.close();
con.close();
}
catch(Exception e)
{
System.out.println("LoginServlet error :
"+e.getMessage());
}
}
SVIT-VASAD 85 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
else
{
}
}
(6)ReviewServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
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("/forReview")
public class ReviewServlet extends HttpServlet
{
protected void service(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
String click=request.getParameter("sub1");
if(click.matches("submit"))
{
int sno=Integer.parseInt(request.getParameter("sno"));
int id=Integer.parseInt(request.getParameter("id"));
String rev=request.getParameter("rad");
String comment=request.getParameter("comm");
int count1=0,count2=0;
SVIT-VASAD 86 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/stddb","root","");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from
review where sno="+sno);
while(rs.next())
{
count1=rs.getInt("lik");
count2=rs.getInt("dik");
}
}
catch(Exception e)
{
System.out.println("LoginServlet error :
"+e.getMessage());
}
if(rev.matches("like"))
{
count1++;
}
else if(rev.matches("dislike"))
{
count2++;
}
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/stddb","root","");
Statement st=con.createStatement();
st.executeUpdate("update review set
lik="+count1+",dik="+count2+" where sno="+sno+" and id="+id);
SVIT-VASAD 87 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
{
System.out.println("LoginServlet error :
"+e.getMessage());
}
request.getRequestDispatcher("/blog.jsp").forward(request,
response);
}
else if(click.matches("publish"))
{
String topic=request.getParameter("topic");
int id=Integer.parseInt(request.getParameter("id"));
String blog=request.getParameter("para");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/stddb","root","");
Statement st=con.createStatement();
SVIT-VASAD 88 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
}
}
Practical 1
Write a Client-server application using UDP Protocol in which client sends a
message to server. Server will convert that message into upper case and
returns the result back to client.
**server.java**
package alapractical1;
import java.io.*;
import java.net.*;
import java.util.*;
public class server
{
public static void main(String [] args){
try{
SVIT-VASAD 89 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
**client.java**
package alapractical1;
import java.io.*;
import java.net.*;
import java.util.*;
public class client
{
public static void main(String [] args){
DatagramSocket ds=null;
Scanner sc=new Scanner(System.in);
try{
ds=new DatagramSocket();
System.out.println("Socket created.");
System.out.println("Enter a String: ");
String s="";
s=sc.nextLine();
byte[] m=s.getBytes();
InetAddress ip=InetAddress.getLocalHost();
int serverport=3333;
SVIT-VASAD 90 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
DatagramPacket request
=new DatagramPacket(m,m.length,ip,3333);
ds.send(request);
byte[] buffer=new byte[1000];
DatagramPacket reply
= new DatagramPacket(buffer,buffer.length);
ds.receive(reply);
System.out.println("Reply from server"+
":"+new String(reply.getData()));
}
catch(Exception e){
System.out.println(e);
}
}
}
Output :-
SVIT-VASAD 91 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
SVIT-VASAD 92 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Practical 2
2(a) Learn how to process the database metadata.
Package Practical2;
import java.sql.*;
public class alapractical2a {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
String username = "root";
String password = "himalaypatel";
Connection c =
DriverManager.getConnection("jdbc:mysql://localhost:3306/himalay",usernam
e,password);
DatabaseMetaData dmd = c.getMetaData();
System.out.println("The Database Product
Name : "+dmd.getDatabaseProductName());
System.out.println("The Username : "+dmd.getUserName());
System.out.println("The Catalogs are : ");
ResultSet rs = dmd.getCatalogs();
while(rs.next()){
System.out.println(rs.getString(1));
}
String catalog = null;
String schema = null;
String table = null;
String[] types = {"TABLE"};
ResultSet rs1 = dmd.getTables(catalog, schema, table, types);
System.out.println("Table names : ");
while(rs1.next()){
System.out.println(rs1.getString(3));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}}
SVIT-VASAD 93 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Output :-
package ALAPractical2;
import java.sql.*;
public class alapractical2b {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
String username = "root";
String password = "himalaypatel";
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/himalay",usernam
e,password);
ParameterMetaData pmd;
String sql = "select * from Student where Semester=? ";
PreparedStatement ps = conn.prepareStatement(sql);
pmd = ps.getParameterMetaData();
int count = pmd.getParameterCount();
System.out.println("The Parameter Count is : "+count);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace(); }}}
SVIT-VASAD 94 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Output :-
package ALAPractical2;
import java.sql.*;
public class alapractical2c {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/himalay","root","
himalaypatel");
String query = "select * from Student";
Statement s = con.createStatement();
ResultSet rs = s.executeQuery(query);
java.sql.ResultSetMetaData rmd = rs.getMetaData();
int noCol = rmd.getColumnCount();
System.out.println("The Number of columns is : "+noCol);
String ColName[] = new String[noCol];
for(int i=0;i<noCol;i++){
ColName[i] = rmd.getColumnName(i+1);
}
String ColType[] = new String[noCol];
for(int i=0;i<noCol;i++){
ColType[i] = rmd.getColumnTypeName(i+1);
}
SVIT-VASAD 95 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Output :-
SVIT-VASAD 96 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Practical 3
Write a servlet that shows all request headers and response headers.
**index.html**
<html>
<head>
<title>Request and Response Headers</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<a href="Servlet1">Get Headers</a>
</body>
</html>
SVIT-VASAD 97 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
SVIT-VASAD 98 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
SVIT-VASAD 99 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
response.setHeader("Himalay", "Patel");
response.setHeader("BrowserUsed", "Chrome");
RequestDispatcher dispatcher =
getServletContext().getNamedDispatcher("Servlet2");
dispatcher.forward(request, response);
}}
**web.xml**
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>
<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>Servlet2</servlet-class>
</servlet>
<servlet>
<servlet-name>Servlet3</servlet-name>
<servlet-class>Servlet3</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/Servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/Servlet2</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet3</servlet-name>
<url-pattern>/Servlet3</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list></web-app>
SVIT-VASAD 100 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Output :-
SVIT-VASAD 101 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Practical 4
Write a servlet that instructs the browser to reconnect every five seconds.
Display the time (print new java.util.Date()) on each connection. (response
header)
**index.html**
<html>
<head>
<title>Time</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<a href="Servlet1">Time</a>
</body>
</html>
SVIT-VASAD 102 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
else
am_pm = "PM";
String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
PrintWriter out = response.getWriter();
String title = "Auto Refresh Webpage";
String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n"+
"<body bgcolor=\"orange\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<p>Current Time is: " + CT + "</p>\n");
}}
**web.xml**
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/Servlet1</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
SVIT-VASAD 103 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Output :-
After 15 seconds :
SVIT-VASAD 104 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
After 25 seconds :
SVIT-VASAD 105 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Practical 5 :-
Invoke the method from within template text using JSP elements (example
o/p - Sum of 3 and 4 is 7.) Print above line to console as well using JSP
elements.
**index.html**
<html>
<head>
<title>Addition</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="AddJSP.jsp" method="post">
Number 1: <input type="text" name="n1"><br>
Number 2: <input type="text" name="n2"><br>
<input type="submit" value="Add">
</form>
</body>
</html>
**AddJSP.jsp**
<%--
Document : AddJSP
Created on : Mar 24, 2017, 1:11:52 PM
Author : Himalay
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Addition of 2 numbers</title>
</head>
<body>
<%
int x= Integer.parseInt(request.getParameter("n1"));
int y=Integer.parseInt(request.getParameter("n2"));
%>
<%!
SVIT-VASAD 106 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Output :-
SVIT-VASAD 107 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Practical 6
Write a servlet that sends the first 9 requests to Welcome Page, the next
request to Reject Page, and then repeats. That is, every tenth request should
get sent to Reject Page and the rest should get sent to Welcome Page.
**index.html**
<html>
<head>
<title>Multiple Requests</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<a href="Servlet1">Start</a>
</body>
</html>
SVIT-VASAD 108 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
rd.include(request,response);
count++;
}
else{
out.println("<html><body><h2>Count is "+count+" </h2></body></html");
RequestDispatcher rd= request.getRequestDispatcher("reject.html");
rd.include(request,response);
count=1;
}
out.println("<html><body><a href=\"Servlet1\">Again</a></body></html");
}
}
**welcome.html**
<html>
<head>
<title>Welcome</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h2>Welcome Page</h2>
</body>
</html>
**reject.html**
<html>
<head>
<title>Reject</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h2>Reject Page</h2>
</body>
</html>
SVIT-VASAD 109 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
**web.xml**
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/Servlet1</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Output :-
Initially count=1 :
SVIT-VASAD 110 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
After 6 requests:
SVIT-VASAD 111 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Practical 7 :-
JSP Scripting Elements Do the following with only JSPs (and no servlets) and
using JSP scripting elements Create a method that take two int numbers and
return their sum as int. Invoke the method from within template text using
JSP elements (example o/p - Sum of 3 and 4 is 7.) Print above line to console
as well using JSP elements.
**index.html**
<html>
<head>
<title>Addition</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="AddJSP.jsp" method="post">
Number 1: <input type="text" name="n1"><br>
Number 2: <input type="text" name="n2"><br>
<input type="submit" value="Add">
</form>
</body>
</html>
**AddJSP.jsp**
<%--
Document : AddJSP
Created on : Mar 24, 2017, 1:11:52 PM
Author : Himalay
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Addition of 2 numbers</title>
</head>
<body>
<%
int x= Integer.parseInt(request.getParameter("n1"));
int y=Integer.parseInt(request.getParameter("n2"));
SVIT-VASAD 112 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
%>
<%!
int add(int a,int b)
{
return a+b;
}
%>
<%= "Addition of " + x + " and " + y + " is " + add(x,y)%>
</body>
</html>
Output :-
SVIT-VASAD 113 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Practical 8 :-
JSP Forms and Standard Actions Create a JSP web form to submit the name
and age of an employee. Form should be submitted to a JSP file.
Create a bean class called Employee for storing the name and age of the
employee Within the JSP to which form is submitted, do the following using
only standard actions-Declare an instance of the Employee JavaBean
Populate the Employee object with values from form submission Retrieve the
values and display it with proper template text:
Employee name is John
Employee age is 30
**index.jsp**
<%--
Document : index
Created on : Mar 24, 2017, 1:59:58 PM
Author : Himalay
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Employee form</title>
</head>
<body>
<form action="nextJSP.jsp">
Name: <input type="text" name="name">
Age: <input type="text" name="age">
<input type="submit" value="Go">
</form>
</body>
</html>
**nextJSP.jsp**
<%--
Document : nextJSP
Created on : Mar 24, 2017, 2:01:48 PM
Author : Himalay
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
SVIT-VASAD 114 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome</title>
</head>
<body>
<jsp:useBean id="emp" class="test.Employee" scope="request">
<jsp:setProperty name="emp" property="*" />
<jsp:getProperty property="name" name="emp"/><br>
<jsp:getProperty property="age" name="emp"/><br>
</jsp:useBean>
</body>
</html>
**test/Employee.java**
package test;
public class Employee {
public Employee(){}
private String name;
private int age;
public void setName(String str){
name=str;
}
public void setAge(int x){
age=x;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}
SVIT-VASAD 115 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Output :-
SVIT-VASAD 116 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Practical 9:-
Create two simple JSP files. A JSP web form that will submit data to the
second JSP Second JSP may simply print the values of the form submission.
**index.jsp**
<%--
Document : index
Created on : Apr 4, 2017, 11:19:23 AM
Author : Himalay
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP web form</title>
</head>
<body>
<form name="ff" method="post" action="show.jsp">
First Name- <input type="text" name="fName" /><br>
Last Name- <input type="text" name="lName" /><br>
<input type="radio" name="gender" value="Male"/>Male<br>
<input type="radio" name="gender" value="Female"/>Female<br>
Date of Birth- <input type="text" name="dob" /><br>
College- <input type="text" name="college" /><br>
Home town- <input type="text" name="home" /><br>
<input type="submit" name="submit" value="Submit" />
</form></body></html>
**show.jsp**
<%--
Document : show
Created on : Apr 4, 2017, 11:24:09 AM
Author : Himalay
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Show page</title>
SVIT-VASAD 117 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
</head>
<body>
<%
String fname=request.getParameter("fName");
String lname=request.getParameter("lName");
String gender=request.getParameter("gender");
String dob=request.getParameter("dob");
String college=request.getParameter("college");
String home=request.getParameter("home");
%>
<%= "First Name is " + fname + "<br>" %>
<%= "Last Name is " + lname + "<br>" %>
<%= "Gender is " + gender + "<br>" %>
<%= "Date of Birth is " + dob + "<br>" %>
<%= "College is " + college + "<br>" %>
<%= "Hometowm is " + home + "<br>" %>
</body></html>
Output :-
SVIT-VASAD 118 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
**insert.html**
<!DOCTYPE html>
<html>
<head>
<title>Registration form</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form name="f1" method="post" action="insert.jsp">
Name- <input type="text" name="name" /><br>
Phone number- <input type="text" name="phone" /><br>
Address- <textarea rows="5" name="address"></textarea><br>
<input type="submit" name="submit" />
<input type="reset" name="reset" />
</form>
</body>
</html>
**insert.jsp**
<%--
Document : insert
Created on : Apr 4, 2017, 8:06:37 AM
Author : Himalay
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix='c'%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix='sql'%>
<sql:setDataSource var="dataSource" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/himalay" user="root"
password="himalaypatel" />
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert details</title>
SVIT-VASAD 119 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
</head>
<body>
<%
String name= request.getParameter("name");
String phone= request.getParameter("phone");
String address= request.getParameter("address");
%>
<sql:update dataSource="${dataSource}" var="result">
insert into customer(name,phone,address) values (?,?,?);
<sql:param value="${param.name}" />
<sql:param value="${param.phone}" />
<sql:param value="${param.address}" />
</sql:update>
<h2>Data inserted successfully.</h2>
</body>
</html>
Output :-
SVIT-VASAD 120 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
**display.html**
<html>
<head>
<title>Display details</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form name="f2" method="post" action="display.jsp">
<input type="submit" name="submit" value="Display details of customer
table" />
</form>
</body>
</html>
**display.jsp**
<%--
Document : display
Created on : Apr 4, 2017, 8:38:17 AM
Author : Himalay
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix='c'%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix='sql'%>
<sql:setDataSource var="dataSource" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/himalay" user="root"
password="himalaypatel" />
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Display details</title>
<style type="text/css">
table{
border-collapse:collapse;
}
SVIT-VASAD 121 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
</style>
</head>
<body>
<sql:query var="customers" dataSource="${dataSource}">
select * from customer;
</sql:query>
<center><h2>Customer table</h2></center>
<table border="1" cellspacing="3" cellpadding="5" align="center">
<tr>
<c:forEach var="column" items="${customers.columnNames}" >
<td><c:out value="${column}" /></td>
</c:forEach>
</tr>
<c:forEach var="row" items="${customers.rows}">
<tr>
<td><c:out value="${row.name}" /></td>
<td><c:out value="${row.phone}" /></td>
<td><c:out value="${row.address}" /></td>
</tr>
</c:forEach>
</table>
</body>
</html>
Output :-
SVIT-VASAD 122 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Practical 12 :-
Create a servlet that makes an array of Name objects, which have firstName
and lastName properties. Have your JSP page make an HTML table with first
names in the left table cell and last names in the right table cell. Use the JSP
2.0 expression language as well as JSTL.
**index.html**
<html>
<head>
<title>Name objects</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form name="f" method="post" action="Servlet1">
<button type="submit">Display Names in tabular form</button>
</form>
</body>
</html>
**test/Servlet1.java**
package test;
import test.Name;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class Servlet1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
doPost(request,response);
}
@Override
SVIT-VASAD 123 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
**test/Name.java**
package test;
public class Name {
private String firstName;
private String lastName;
public Name(){ }
public void setFirstName(String fname){
firstName=fname;
}
public void setLastName(String lname){
lastName=lname;
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
}
SVIT-VASAD 124 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
**go.jsp**
<%--
Document : go
Created on : Apr 4, 2017, 11:55:28 AM
Author : Himalay
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix='c'%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Display Names</title>
<style type="text/css">
table{
border-collapse:collapse;
}
</style>
</head>
<body>
<center><h2>In JSP file</h2></center>
<center>
<table border="1" cellspacing="3" cellpadding="5">
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
<c:forEach var="n" items="${names}">
<tr>
<td><c:out value="${n.firstName}" /></td>
<td><c:out value="${n.lastName}" /></td>
</tr>
</c:forEach>
</table>
</center>
</body>
</html>
SVIT-VASAD 125 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Output :-
SVIT-VASAD 126 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Practical13
Using JSTL XML taglib.Write a JSP which parses an XML file containing
Customer details like Name, Age, phoneno, email.. Displays the result in
tabular form.
**student.xml**
<?xml version="1.0" encoding="UTF-8"?>
<customers>
<customer>
<name>Himalay</name>
<age>20</age>
<phoneno>9978407550</phoneno>
<email>himalayp8@gmail.com</email>
</customer>
<customer>
<name>Parva</name>
<age>21</age>
<phoneno>9039039022</phoneno>
<email>p@gmail.com</email>
</customer>
<customer>
<name>Kaival</name>
<age>19</age>
<phoneno>9990009990</phoneno>
<email>k@gmail.com</email>
</customer>
<customer>
<name>Rajan</name>
<age>20</age>
<phoneno>1234567890</phoneno>
<email>r@gmail.com</email>
</customer>
<customer>
<name>Tirth</name>
<age>21</age>
<phoneno>9998887770</phoneno>
<email>t@gmail.com</email>
</customer>
</customers>
SVIT-VASAD 127 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
**ParseXML.jsp*
<%--
Document : ParseXML
Created on : Apr 4, 2017, 4:37:27 PM
Author : Himalay
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix='c'%>
<%@taglib uri="http://java.sun.com/jsp/jstl/xml" prefix='x'%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Parsing XML document</title>
<style type="text/css">
table{
border-collapse:collapse;
}
</style>
</head>
<body>
<c:import var="customerInfo"
url="http://localhost:7777/practicals/customer.xml"/>
<x:parse xml="${customerInfo}" var="output"/>
<center><h2>Parsing customer.xml and displaying in tabular
form</h2></center>
<center><table border="1" cellspacing="3" cellpadding="5">
<tr>
<th>Name</th>
<th>Age</th>
<th>Phone number</th>
<th>Email id</th>
</tr>
<x:forEach select="$output/customers/customer" var="xx">
<tr>
<td><x:out select="$xx/name" /></td>
<td><x:out select="$xx/age" /></td>
<td><x:out select="$xx/phoneno" /></td>
<td><x:out select="$xx/email" /></td>
SVIT-VASAD 128 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
</tr>
</x:forEach>
</table></center>
</body>
</html>
Output :-
SVIT-VASAD 129 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Practical 14
Make a JSF page which takes input for two numbers and has command
buttons for different operation. When any button is clicked that operation is
performed and result will be displayed in a text box. Should show an error
message if any number is missing.
**index.xhtml**
<?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">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>Calculator using JSF</title>
</h:head>
<h:body>
<h2><h:outputText value="Simple Calculator using JSF" /></h2>
<h:form id="f1">
<h:outputText value="Enter a-"/>
<h:inputText value="#{test.a}" /><br></br>
<h:outputText value="Enter b-"/>
<h:inputText value="#{test.b}" /><br></br>
<h:commandButton action="#{test.add}" value="Add" /><br></br>
<h:commandButton action="#{test.subtract}" value="Subtract" /><br></br>
<h:commandButton action="#{test.multiply}" value="Multiply" /><br></br>
<h:commandButton action="#{test.divide}" value="Divide" /><br></br>
<h:outputText value="Answer is-"/>
<h:inputText value="#{test.result}" /><br></br>
<h:outputText value="#{test.error}"/><br></br>
</h:form>
</h:body>
</html>
**bean/test.java**
package bean;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
@ManagedBean
@RequestScoped
public class test {
SVIT-VASAD 130 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
private String a;
private String b;
private int result;
private String error;
public test(){ }
public String getA(){return a;}
public void setA(String str){a=str;}
public String getB(){return b;}
public void setB(String str){b=str;}
public int getResult(){return result;}
public void setResult(int str){result=str;}
public String getError(){return error;}
public void setError(String str){error=str;}
public void add(){
if(a.equals("") || b.equals("")){
error="One of the two numbers is missing.";
result=-9999999;
return;
}
result=Integer.parseInt(a)+Integer.parseInt(b);
}
public void subtract(){
if(a.equals("") || b.equals("")){
error="One of the two numbers is missing.";
result=-9999999;
return;
}
result=Integer.parseInt(a)-Integer.parseInt(b);
}
public void multiply(){
if(a.equals("") || b.equals("")){
error="One of the two numbers is missing.";
result=-9999999;
return;
}
result=Integer.parseInt(a)*Integer.parseInt(b);
}
public void divide(){
if(a.equals("") || b.equals("")){
error="One of the two numbers is missing.";
SVIT-VASAD 131 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
result=-9999999;
return;
}
result=Integer.parseInt(a)/Integer.parseInt(b);
}
}
Output :-
Initially :
Add :
Subtract :
SVIT-VASAD 132 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Multiply :
Divide :
Number missing :
SVIT-VASAD 133 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
Beyond Syllabus
Addition.idl File :-
/**
*
* @author imed
*/
module AdditionApp
{
interface Addition
{
long add(in long a,in long b);
oneway void shutdown();
};
};
cd C:\Users\imed\workspace\CorbaAdditionServer\src:-
CorbaAdditionServer::AdditionObj.java file:-
/**
*
* @author imed
*/
import AdditionApp.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
SVIT-VASAD 134 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
import org.omg.CORBA.*;
import org.omg.PortableServer.*;
import org.omg.PortableServer.POA;
import java.util.Properties;
class AdditionObj extends AdditionPOA {
private ORB orb;
public void setORB(ORB orb_val) {
orb = orb_val;
}
// implement add() method
public int add(int a, int b) {
int r=a+b;
return r;
}
// implement shutdown() method
public void shutdown() {
orb.shutdown(false);
}
}
CorbaAdditionServer::StartServer.java file:-
/**
*
* @author imed
*/
import AdditionApp.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;
import org.omg.PortableServer.*;
import org.omg.PortableServer.POA;
import java.util.Properties;
public class StartServer {
SVIT-VASAD 135 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
POA rootpoa =
POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
rootpoa.the_POAManager().activate();
org.omg.CORBA.Object objRef =
orb.resolve_initial_references("NameService");
NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);
Output :-
SVIT-VASAD 136 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
CorbaAdditionClient::StartClient.java file :-
/**
*
* @author imed
*/
import AdditionApp.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;
import java.io.*;
import java.util.*;
SVIT-VASAD 137 | P a g e
Gadre Shlok S. Advance Java TY IT-1
160410116031 BATCH-B
catch (Exception e) {
System.out.println("Hello Client exception: " + e);
e.printStackTrace();
}
}
}
Output :-
SVIT-VASAD 138 | P a g e