Advanced Java
Advanced Java
PRACTICAL NO: 1
Aim:: Implement the following Simple Servlet application.
A: Create a simple calculator application using servlet.
INPUT::
index.html:
<html>
<head>
<title>Simple Calculator</title>
</head>
<body>
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="submit" value="Calculate">
<input type="reset" value="Reset">
</form> </body> </html>
check.java:
import java.io.* import
javax.servlet.*;
public class check extends GenericServlet {
public void service(ServletRequest req, ServletResponse res)
1
PRN No: Advanced Java Technologies
int b=Integer.parseInt(req.getParameter("n2"));
String op=req.getParameter("operator");
if(op.equals("+")){
out.println("Addition is: "+(a+b));
}
else
if(op.equals("*")){ out.println("Multiplicatio
n is: "+(a*b));
else{
}
}
OUTPUT:
2
PRN No: Advanced Java Technologies
B: Create a servlet for a login page. If the username and password are correct
then it says message “Hello <username>” else a message “Login failed”.
INPUT::
index.html:
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form action="Demo">
</body>
</html>
Demo.java:
import java.io.*;
import javax.servlet.*;
public class Demo extends GenericServlet {
3
PRN No: Advanced Java Technologies
else
{
out.println("<h1>Login Failed</h1>");
}
OUTPUT:
4
PRN No: Advanced Java Technologies
C: Create a registration servlet in java using JDBC. Accept the details such as
Username, Password, Email and Country from the user using HTML Form and
store the registration details in the database.
INPUT::
index.html:
<html>
<head>
<title>Registration Servlet</title>
</head>
<body>
<form action="register" method="get">
</html>
register.java:
import java.io.IOException;
import java.io.PrintWriter; import
java.sql.Connection; import
java.sql.DriverManager;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
5
PRN No: Advanced Java Technologies
@WebServlet(urlPatterns = {"/register"})
public class register extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
}}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
String s1 = request.getParameter("n1");
String s2 = request.getParameter("n2");
String s3 = request.getParameter("n3");
String s4 = request.getParameter("n4");
try{ Class.forName("com.mysql.jdbc.Dri
ver"); Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/register","root","system");
String sql = "Insert into register values(?,?,?,?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1,s1);
ps.setString(2,s2);
ps.setString(3,s3);
ps.setString(4,s4);
ps.executeUpdate();
out.println("Data Inserted!");
con.close();
}
catch(Exception
e){ out.println(e);
}}}
6
PRN No: Advanced Java Technologies
OUTPUT:
Database:
7
PRN No: Advanced Java Technologies
PRACTICAL NO: 2
Aim:: Implement the following Servlet applications with Cookies and Session.
A: Using Request Dispatcher Interface create a Servlet which will validate the
password entered by the user, if the user has entered "Servlet" as password, then
he will be forwarded to “Welcome” Servlet else the user will stay on the
“index.html” page and an error message will be displayed.
INPUT::
index.html:
<html>
<head>
<title>Request Dispatcher</title>
</head>
<body>
</form>
</body>
</html>
Demo.java:
import java.io.*;
import javax.servlet.*;
8
PRN No: Advanced Java Technologies
{
req.setAttribute("user",n1);
RequestDispatcher rd=req.getRequestDispatcher("welcome");
rd.forward(req, res);
else
{
out.print("Password is invalid");
}
}}
welcome.java:
import java.io.*;
import javax.servlet.*;
String s =(String)req.getAttribute("user");
PrintWriter out=res.getWriter();
}}
OUTPUT:
9
PRN No: Advanced Java Technologies
B: Create a servlet that uses Cookies to store the number of times a user has visited
servlet.
INPUT::
index.html:
<html>
<head>
<title>Using Cookies</title>
</head>
<body>
<form action="cookie">
</body>
</html>
cookie.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String k=String.valueOf(i);
Cookie c=new Cookie("visit",k);
res.addCookie(c);
int j=Integer.parseInt(c.getValue());
if(j==1){
}
10
PRN No: Advanced Java Technologies
else{
out.println("<h3>You visited "+i+" times</h3>");
}
i++;
}}
OUTPUT:
11
PRN No: Advanced Java Technologies
C: Create a servlet demonstrating the use of session creation and destruction. Also
check whether the user has visited this page first time or has visited earlier also using
sessions. INPUT::
index.html
<html>
<head>
<title>Using Session</title>
</head>
<body>
</body>
</html>
Session.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
{
PrintWriter out=res.getWriter();
out.println("<html><body>"); HttpSession
hs=req.getSession(true); if(hs.isNew())
{
String name=req.getParameter("txtName");
12
PRN No: Advanced Java Technologies
hs.setAttribute("uname", name);
hs.setAttribute("visit","1");
out.println("<h2>Welcome First Time</h2>");
else
{
out.println("<h2>Welcome Again</h2>");
int visit=Integer.parseInt((String)hs.getAttribute("visit"))+1;
out.println("<h2>You visited "+visit+" times</h2>");
hs.setAttribute("visit", visit);
logoutServlet.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;
{
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<body>");
HttpSession hs=req.getSession();
13
PRN No: Advanced Java Technologies
if(hs!=null);
{
hs.invalidate();
}
out.println("</html>");
}
}
OUTPUT:
14
PRN No: Advanced Java Technologies
PRACTICAL NO: 3
Aim:: Implement the Servlet IO and File applications.
A: Create a servlet application to upload and download a file.
Upload File:-
INPUT::
index.html:
<html>
<head>
<title>File_Upload</title>
</head>
<body>
<h2> File upload </h2> Select
the file to upload:<br>
</body>
</html>
uploadServlet.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.oreilly.servlet.MultipartRequest;
public class uploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
15
PRN No: Advanced Java Technologies
PrintWriter out=response.getWriter();
MultipartRequest m=new MultipartRequest(request,"D:\\");
out.print("<html><body><h2>Sucessfully Uploaded</html></body></h2>");
OUTPUT:
16
PRN No: Advanced Java Technologies
Download File:-
INPUT::
index.html:
<html>
<head>
<title>Download File</title>
</head>
<body> <h2> File Download </h2>
</body></html>
download.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
}
f.close();
}}
17
PRN No: Advanced Java Technologies
OUTPUT:
18
PRN No: Advanced Java Technologies
B :Develop Simple Servlet Question Answer Application.
INPUT::
index.html:
<html>
<head>
<title>Question Answer Application</title>
</head>
<body>
19
PRN No: Advanced Java Technologies
<input type="reset" value="Reset Values"/>
</form>
</body>
</html>
checkServlet.java:
import java.io.*;
import javax.servlet.*;
public class checkServlet extends GenericServlet{
String a1,a2,a3,a4;
a1=req.getParameter("r1");
a2=req.getParameter("r2");
a3=req.getParameter("r3");
a4=req.getParameter("r4");
out.println("</html>");
}finally{ out.close()
}}}
20
PRN No: Advanced Java Technologies
OUTPUT:
21
PRN No: Advanced Java Technologies
PRACTICAL NO: 4
Aim:: Implement the following JSP applications.
A: Develop a simple JSP application to display values obtained from the use of
intrinsic objects of various types.
INPUT::
Implicit.jsp:
<html><body>
OUTPUT:
22
PRN No: Advanced Java Technologies
B: Develop a simple JSP application to pass from one page to another with
validations. (Name-txt, age-txt, hobbies-checkbox, email-txt, gender-radio button).
INPUT::
Index.html:
<html>
<head>
<title>JSP Validation</title>
</head>
<body>
<form action="validate.jsp">
</form>
</body>
</html>
CheckerBean.java:
package mypack;
public class CheckerBean
{
private String name, age, hob, email, gender,error;
public CheckerBean()
23
PRN No: Advanced Java Technologies
{
error="";
}
public void setName(String n)
{
name=n;
age=a;
}
public String
getName(){ return name;
}
public String getError()
{ return error;
{
error+="<br>Enter First Name"; res=false;
}
if(age==null)
24
PRN No: Advanced Java Technologies
error+="<br>Enter age";
res=false;
}
if(age.length() > 2 )
error+="<br>Age Invalid";
res=false;
}
return res;
validate.jsp:
<%@page import="mypack.*;" %>
</jsp:useBean>
<%
if (obj.validate())
{
%>
<jsp:forward page="Successful.jsp"/>
<%
} else {
%>
<jsp:include page="index.html"/>
<%
}
25
PRN No: Advanced Java Technologies
Succesful.jsp:
<html>
<body>
<h1>DATA VALIDATED SUCCESSFULLY </h1>
<%
String s1=request.getParameter("name");
out.print(s1);
%>
</body>
</html>
OUTPUT:
26
PRN No: Advanced Java Technologies
C: Create a registration and login JSP application to register and authenticate the
user based on username and password using JDBC.
INPUT::
Index.html:
<html>
<head>
<title>JSP Registration</title>
</head>
<body>
<form action="Register.jsp">
</form>
</body>
</html>
Register.jsp:
<%@page contentType="text/html" import="java.sql.*"%>
<%
String uname=request.getParameter("txtName");
String pass1 = request.getParameter("txtPass1");
String pass2 = request.getParameter("txtPass2");
String email = request.getParameter("txtEmail");
String ctry = request.getParameter("txtCon");
if(pass1.equals(pass2))
27
PRN No: Advanced Java Technologies
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","system");
PreparedStatement stmt = con.prepareStatement("insert into user values(?,?,?,?)");
stmt.setString(1, uname);
stmt.setString(2, pass1);
stmt.setString(3, email);
stmt.setString(4, ctry);
int row = stmt.executeUpdate();
if(row==1) {
out.println("<h2>Registration Successful</h2>");
else {
out.println("<h2>Registration FAILED!!!! </h2>");
catch(Exception e)
{ out.println(e);
}}
else {
out.println("<h2>Password Mismatch</h2>");
} %>
28
PRN No: Advanced Java Technologies
OUTPUT:
29
PRN No: Advanced Java Technologies
PRACTICAL NO: 5
Aim::Implement the following JSP, JSTL and EL Applications.
A: Create an html page with fields, eno, name, age, desg, salary. Now on submit
this data to a JSP page which will update the employee table of database with
matching eno.
INPUT::
index.html:
<html>
<head>
<title>JSP Employee</title>
</head>
<body>
<form action="Update.jsp">
</body>
</html>
Update.jsp:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
String eno=request.getParameter("t1");
String ename=request.getParameter("t2");
String age=request.getParameter("t3"); String
salary=request.getParameter("t4"); try
30
PRN No: Advanced Java Technologies
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/emp1","root","system");
PreparedStatement stmt=con.prepareStatement("select * from tab where eno=?");
stmt.setString(1,eno);
ResultSet rs=stmt.executeQuery();
if(rs.next())
{
PreparedStatement pst1=con.prepareStatement("update tab set ename=?,age=?,salary=? where eno=?);
pst1.setString(3,salary);
pst1.setString(2,age);
pst1.setString(1,ename);
pst1.setString(4,eno);
pst1.executeUpdate();
out.print("<h1>record updated</h1>");
else{
out.print("<h1> record not found</h1>");
catch(Exception
e){ out.print(e);
} %>
31
PRN No: Advanced Java Technologies
OUTPUT:
Before Update:
After Update:
32
PRN No: Advanced Java Technologies
B: Create a JSP page to demonstrate the use of Expression language.
INPUT::
Index.jsp:
<html>
<body>
<%
session.setAttribute("user","Shubham");
Cookie s=new Cookie("name","Shubh");
response.addCookie(s);
%>
<a href="Expression.jsp">Visit</a>
</body>
</html>
Expression.jsp:
<html>
<body>
${"Learning Expression"}<br>
Expression1:${1>(4/2)}<br>
Expression2:${(10*10) ne 100}<br>
<h1>Use of implicit object in Expression Language</h1><br>
Expression Language session Scope Object:${sessionScope.user}<br>
</html>
33
PRN No: Advanced Java Technologies
OUTPUT:
34
PRN No: Advanced Java Technologies
<html>
<body>
<c:set var="String" value="Welcome-to-tutorials-point"/><h3>
contains:${fn:contains(String,"tutorial")}<br>
indexOf:${fn:indexOf(String,"to")}<br>
replace:${fn:replace(String,"tutorials","javat")}<br>
toLowerCase:${fn:toLowerCase(String)}<br>
toUpperCase:${fn:toUpperCase(String)}<br>
substring:${fn:substring(String,5,11)}<br>
substringAfter:${fn:substringAfter(String,"to")}<br>
</body>
</html>
OUTPUT:
35
PRN No: Advanced Java Technologies
PRACTICAL NO: 6
Aim::Implement the following EJB Applications.
A: Create a Currency Converter application using
EJB. INPUT::
index.html:
<html>
<head>
<title>Currency Converter</title>
</head>
<body>
</form>
</body>
</html>
CCBean.java:
package mybean;
import javax.ejb.Stateless;
@Stateless
public CCBean() {
}
36
PRN No: Advanced Java Technologies
}
public double d2Rupees(double d)
{ return d*83.99;
CCServlet.java:
import mybean.CCBean;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.ejb.EJB;
public class CCServlet extends HttpServlet
{ @EJB CCBean obj;
if(request.getParameter("type").equals("d2r")) {
}
}
37
PRN No: Advanced Java Technologies
OUTPUT:
38
PRN No: Advanced Java Technologies
B: Develop a Simple Room Reservation System Application using EJB.
INPUT::
index.html:
<html><head>
<option id="d">DELUXE</option>
<option id="s">SUITE</option></select><br>
<option id="c">CASH</option>
<option id="e">CREDIT CARD</option></select><br><br>
</body>
</html>
Reserver.java:
import ejb.Details;
import java.io.*;
import java.util.ArrayList;
import javax.servlet.*;
39
PRN No: Advanced Java Technologies
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.ejb.EJB;
public class Reserver extends HttpServlet
IOException
{
PrintWriter out = response.getWriter();
String cname=request.getParameter("tname");
String cadd=request.getParameter("tadd");
String cph=request.getParameter("tphone");
String croom=request.getParameter("troom");
String chin=request.getParameter("tin"); String
chout=request.getParameter("tout"); String
cmode=request.getParameter("tpay");
ArrayList<String> a=d.reserve(cname,cadd,cph,croom,chin,chout,cmode);
out.println("<html><body><h2>");
try
{
out.println(d.welmsg(cname)+"<br>");
out.println(d.rtype(croom)+"<br>");
out.println(d.roompay(croom)+"<br>");
out.println("<br>----Ur Details <br>");
out.println("<table border=1><tr><th>Name</th><th>Address</th><th>PhoneNo.</th>"
+ "<th>RoomType</th><th>ChechIn Date</th><th>CheckOut Date</th><th>Payment
Mode</th></tr>");
out.println("<tr>");
int i;
for(i=0;i<7;i++){
40
PRN No: Advanced Java Technologies
}
out.println("</tr></table>");
}
catch(Exception
e){ out.println(e);
}
out.println("</h2></body></html>");
}}
Details.java:
package ejb;
import java.util.ArrayList;
public class Details{
public String welmsg(String cust){
return "Hello" + " " + cust.toUpperCase()+ " "+"</br>Welcome to The Presidential Hotel";
}
if(rt.equalsIgnoreCase("SUITE")) { return
"You have To Pay 8000Rs Only";
}
else if(rt.equalsIgnoreCase("DELUXE"))
{ return "You have To Pay 4000Rs Only";
}
else {
41
PRN No: Advanced Java Technologies
{
ArrayList<String> a=new ArrayList();
a.add(cust);
a.add(add);
a.add(ph);
a.add(checkin);
a.add(checkout);
a.add(rt1);
a.add(pyr);
return a;
}}
OUTPUT:
42
PRN No: Advanced Java Technologies
PRACTICAL NO: 7
Aim::Implement the following EJB Applications with different types of Beans.
A: Develop simple EJB application to demonstrate Servlet Hit count using Singleton
Session Beans.
INPUT::
index.html:
<html>
<head>
<meta http-equiv="Refresh" content="0; URL=ServletClient">
</head
</html>
ServletClient.java:
import ejb.HitsBean; import
java.io.IOException; import
java.io.PrintWriter; import
javax.ejb.EJB;
import javax.servlet.http.HttpServlet;
HitsBean counter;
finally
{
43
PRN No: Advanced Java Technologies
out.close();
}
}}
HitsBean.java:
package ejb;
import javax.ejb.Singleton;
@Singleton
public class HitsBean
{
private int hitcnt;
return hitcnt++;
OUTPUT:
44
PRN No: Advanced Java Technologies
B: Develop simple Marks Entry Application to demonstrate accessing Database
using EJB.
INPUT::
index.html:
<html>
<head>
<title>Marks Entry Application</title>
</head>
<body>
<form action="MarkEntrySrv" method="get">
</body>
</html>
MarkEntrySrv.java:
import ejb.MarksEntry;
import java.io.*; import
javax.ejb.EJB; import
javax.servlet.*;
import javax.servlet.http.*;
{ @EJB
MarksEntry bean;
PrintWriter out=res.getWriter();
45
PRN No: Advanced Java Technologies
String id,name,p1,p2;
id=req.getParameter("srno");
name=req.getParameter("name");
p1=req.getParameter("m1");
p2=req.getParameter("m2"); bean.entry(id,
name, p1, p2);
out.print(bean.submit(name));
}}
MarksEntry.java:
package ejb;
import java.sql.*;
import javax.ejb.Stateless;
@Stateless
public class MarksEntry{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root
","system");
PreparedStatement ps=con.prepareStatement("insert into student values(?,?,?,?)");
ps.setString(1,srno);
ps.setString(2,sname);
ps.setString(3,p1);
ps.setString(4,p2);
ps.executeUpdate();
catch(Exception
e){ System.out.print(e);
}}
public String submit(String name){
}}
46
PRN No: Advanced Java Technologies
OUTPUT:
47
PRN No: Advanced Java Technologies
PRACTICAL NO: 8
Aim::Implement the following Hibernate application.
A: Develop a Hibernate application to store and retrieve employee details in MySQL
Database.
INPUT::
Emp2.hbm.xml:
<?xml version="1.0" encoding="UTF-8"?>
Employee.java:
package mypack; public
class employee { private
int id;
return id; }
public void setId(int id)
{ this.id = id; }
}
public void setFname(String fname)
{ this.fname = fname;
48
PRN No: Advanced Java Technologies
public String getLname() { return
lname;
}
public void setLname(String lname)
{ this.lname = lname;
}}
Store.java:
package mypack;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction; import
org.hibernate.Session;
public class store {
t.commit();
s1.close();
}}
Hybernet.cfg.xml:
⮚ Source:
<hibernate-configuration>
<session-factory>
49
PRN No: Advanced Java Technologies
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3307/mysql?zeroDat
eTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property> <property
name="hibernate.connection.password">system</property> <property
name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.sql_show">true</property>
<mapping resource="emp.hbm.xml"/>
</session-factory>
</hibernate-configuration>
OUTPUT:
50
PRN No: Advanced Java Technologies
B: Develop a Hibernate application to store Feedback of Website Visitor in MySQL
Database.
INPUT::
index.html:
<html> <body>
<form action="Store.jsp" method="get">
<table> <tr>
<td>Enter Name:</td>
<td>Enter Message:</td>
<td><input type="submit"></td>
<td><input type="reset"></td>
</tr> </table>
</form>
</body> </html>
FeedBack.java:
package mypack; public
class FeedBack {
private String visitorName;
private String message;
51
PRN No: Advanced Java Technologies
this.visitorNo = visitorNo;
}
}
public int getVisitorNo()
{ return visitorNo;
Fedd1.hbm.xml:
<hibernate-mapping>
<generator class="increment"></generator>
</id>
<property name="visitorName" column="name"/>
</hibernate-mapping>
Store.jsp:
<%@page import="java.io.IOException"%>
SessionFactory sf;
org.hibernate.Session hibSession;
52
PRN No: Advanced Java Technologies
sf = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
hibSession = sf.openSession();
Transaction tx = null; FeedBack
f = new FeedBack(); try {
tx = hibSession.beginTransaction();
String username = request.getParameter("name");
String usermsg = request.getParameter("message");
f.setVisitorName(username); f.setMessage(usermsg);
hibSession.save(f);
tx.commit();
{ out.println(e);
hibSession.close();
%>
Hibernet.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD
3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mysql?zeroDat
eTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">hassan11</property>
53
PRN No: Advanced Java Technologies
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="Feed1.hbm.xml"/>
</session-factory>
</hibernate-configuration>
OUTPUT:
54