Vous êtes sur la page 1sur 72

Advanced JAVA Programming Laboratory 13MCA47

1. Write a Java Servlet Program to implement a dynamic HTML using


Servlet (user name and password should be accepted using HTML and
displayed using a Servlet).

Steps to create project:

 File->New Project->Categories:Java Web->Projects:Web Application->Project


Name:Lab01->Next->Next->Finish

 Select Lab01->Right Click->New->Other->Categories:Web->File Types:Servlet->Next-


>Class Name:lab01->Next->Finish

Dynamic.java

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

@WebServlet(name = "Dynamic", urlPatterns = {"/Dynamic"})

public class Dynamic extends HttpServlet


{
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)

Department of MCA, Bangalore Institute Of Technology Page 1


Advanced JAVA Programming Laboratory 13MCA47

throws ServletException, IOException


{
PrintWriter out=response.getWriter();
out.println("<html>");
out.println("<body>");
String usename=request.getParameter("uname");
String password=request.getParameter("pword");
out.println("User Name : "+usename+"<br/>");
out.println("Password : "+password);
out.println("</body>");
out.println("</html>");
}
}

 Select Lab01->Right Click->New->Other->Categories:Web->File Types:HTML->Next-


>HTML File Name: lab01->Finish

Newhtml.html

<!DOCTYPE html>
<html>
<head>
<title> Dynamic </title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form name="form" method="post" action="Dynamic">
<pre>
User Name:<input type=text name="uname" />
Password:<input type=password name="pord" />
</pre>
<input type=submit value="Submit" />
</form>
</body>
</html>

Department of MCA, Bangalore Institute Of Technology Page 2


Advanced JAVA Programming Laboratory 13MCA47

 Select lab01.html->Right Click->Run

Department of MCA, Bangalore Institute Of Technology Page 3


Advanced JAVA Programming Laboratory 13MCA47

2. Write a JAVA Servlet program to Auto Web Page refresh (Consider a


webpage which is displaying Data and time or stock market status).
Steps to create project:

 File->New Project->Categories:Java Web->Projects:Web Application->Project


Name:Lab02->Next->Next->Finish

 Select Lab01->Right Click->New->Other->Categories:Web->File Types:Servlet->Next-


>Class Name:StocksRefresh->Next->Finish

StocksRefresh.java

import java.io.*;
import java.util.Random;
import javax.servlet.*;
import javax.servlet.http.*;

public class StocksRefresh extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws

ServletException,IOException {

String[] sharenames = {"Microsoft","Nintendo","Honda","General Motors"};

String title;

Department of MCA, Bangalore Institute Of Technology Page 4


Advanced JAVA Programming Laboratory 13MCA47

title = "Auto refresh stock market update";

response.setContentType("text/html");

response.addHeader("Refresh", "5");

PrintWriter out = response.getWriter();

out.println("<html><head><title>"+title+

"</title></head>\n<body>\n");

out.println("<center><h2>Stock market status</h2>");

out.println("<table border='1'><th>Share name</th><th>Price</th>");

for(int i = 0 ;i< 4;i++) {

out.println("<tr>\n");

out.println("<td>"+sharenames[i]+"</td>");

out.println("<td>Rs. "+getPrice()+"</td>");

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

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

public double getPrice() {

Random ran = new Random();

double ranNum = ran.nextInt(100)+1000.0;

return ranNum;

Department of MCA, Bangalore Institute Of Technology Page 5


Advanced JAVA Programming Laboratory 13MCA47

Output:

Department of MCA, Bangalore Institute Of Technology Page 6


Advanced JAVA Programming Laboratory 13MCA47

3. Write a Java Servlet Program to implement and demonstrate Get( )


and Post( ) methods (Using HTTP Servlet Class).

Steps to create project:

 File->New Project->Categories:Java Web->Projects:Web Application->Project


Name:Lab5->Next->Next->Finish

 Select Lab5->Right Click->New->Other->Categories:Web->File Types:Servlet->Next-


>Class Name:GetHandler->Next->Finish

GetHandler.java

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

@WebServlet(name = "GetHandler", urlPatterns = {"/GetHandler"})

public class GetHandler extends HttpServlet


{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
Department of MCA, Bangalore Institute Of Technology Page 7
Advanced JAVA Programming Laboratory 13MCA47

throws ServletException, IOException


{
String name=request.getParameter("name");
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<b>A GET request can provide a limited amount of information in
the form of a query string</b><br/>");
pw.println("Welcome "+name);
pw.close();
}
}

 Select Lab5->Right Click->New->Other->Categories:Web->File Types:Servlet->Next-


>Class Name:PostHandler->Next->Finish

PostHandler.java

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

@WebServlet(name = "PostHandler", urlPatterns = {"/PostHandler"})

public class PostHandler extends HttpServlet


{
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String name=request.getParameter("name");
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<b>A POST sends an unlimited amount of information over a socket
Connection as part of the HTTP request</b><br/>");
Department of MCA, Bangalore Institute Of Technology Page 8
Advanced JAVA Programming Laboratory 13MCA47

pw.println("Welcome "+name);
pw.close();
}
}

 Select Lab5->Right Click->New->Other->Categories:Web->File Types:HTML->Next-


>HTML File Name:Senddata->Finish

Senddata.html

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>GET METHOD</h1>
<form method="GET" action="GetHandler">
<label>Name:</label><input type="text" name="name"/><br/>
<input type="submit" value="GET"/>
</form>
<h1>POST METHOD</h1>
<form method="POST" action="PostHandler">
<label>Name:</label><input type="text" name="name"/><br/>
<input type="submit" value="POST"/>
</form>
</body>
</html>

Department of MCA, Bangalore Institute Of Technology Page 9


Advanced JAVA Programming Laboratory 13MCA47

 Select Senddata.html->Right Click->Run

Department of MCA, Bangalore Institute Of Technology Page 10


Advanced JAVA Programming Laboratory 13MCA47

Department of MCA, Bangalore Institute Of Technology Page 11


Advanced JAVA Programming Laboratory 13MCA47

4. Write a JAVA Servlet Program using cookies to remember user


preferences.
Solution explorer:

lab04.html

<html>
<head>
<title>lab04</title>
</head>
<body>
<center>
<form name="form1" method="POST" action="Lab04AddCookie">
<pre>
<b>Enter the following details</b><br/>
Name: <input type="text" name="name"/><br/>
College: <input type="text" name="college"/><br/>
Location: <input type="text" name="location"/><br/>
</pre>

Department of MCA, Bangalore Institute Of Technology Page 12


Advanced JAVA Programming Laboratory 13MCA47

<input type="submit" value="AddCookie" />


</form>
</center>
</body>
</html>

Lab04AddCookie.java

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

public class Lab04AddCookie extends HttpServlet {


public void doPost(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException {
PrintWriter out = res.getWriter();
Enumeration en = req.getParameterNames();
while(en.hasMoreElements()) {
String pname = en.nextElement();
String pvalue = req.getParameter(pname);
Cookie usecookie = new Cookie(pname,pvalue);
usecookie.setMaxAge(300); //5 minutes
res.addCookie(usecookie);
}
res.setContentType("text/html");

Department of MCA, Bangalore Institute Of Technology Page 13


Advanced JAVA Programming Laboratory 13MCA47

out.println("<html>\n<head>\n<title>" + "Lab 04 program" +


"</title>\n</head>\n<body>\n<center>\n");
out.println("<b>User preference has been stored successfully</b>");
out.println("</center>\n</body>\n</html>");
out.close();
}
}

Lab04GetCookie.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Lab04GetCookie extends HttpServlet {


public void doGet(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException {
PrintWriter out = res.getWriter();
Cookie cookies = req.getCookies();
res.setContentType("text/html");
out.println("<html>\n<head>\n<title>" + "Lab 04 program" +
"</title>\n</head>\n<body>\n<center>\n");

out.println("<h2>Welcome</h2><br/>");
for(int i = 0;i<cookies.length;i++) {
String name = cookies[i].getName();

Department of MCA, Bangalore Institute Of Technology Page 14


Advanced JAVA Programming Laboratory 13MCA47

String value = cookies[i].getValue();


out.println("<b>" + name + ": </b>"+ value + "<br/>");
}
out.println("<b>No user data stored or expired</b>\n");
out.println("</center>\n</body>\n</html>");
out.close();
}
}

lab04home.html
<html>
<head>
<title>Lab 04 user preferences</title>
</head>
<body>
<p>New Visitor: <a href="lab04.html">Click here</a></p>
<p>Existing visitor: <a href="Lab04GetCookie">click here</a></p>
</body>
</html>

Department of MCA, Bangalore Institute Of Technology Page 15


Advanced JAVA Programming Laboratory 13MCA47

Click on new visitor

Department of MCA, Bangalore Institute Of Technology Page 16


Advanced JAVA Programming Laboratory 13MCA47

Click on Existing vistor.

Department of MCA, Bangalore Institute Of Technology Page 17


Advanced JAVA Programming Laboratory 13MCA47

5. a. Write JAVA JSP Program to implement verification of a particular


user login and display a welcome page.

Steps to create project:

 File->New Project->Categories:Java Web->Projects:Web Application->Project


Name:Lab5a->Next->Next->Finish

 Select Lab5a->Right Click->New->Other->Categories:Web->File Types:HTML->Next-


>HTML File Name:Welcome->Finish

Welcome.html

<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>Hello Users</h1>
<form method="post" action="index.jsp">
<p>
Username :<input type="text" name="username"><br />
Password:<input type="password" name="password">
</p>
<p><input type="submit" value="login"></p>
</form>
</body>

Department of MCA, Bangalore Institute Of Technology Page 18


Advanced JAVA Programming Laboratory 13MCA47

</html>

 Select the index.jsp in the Lab8b->Web Pages and Type the following

Index.jsp

<%@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>
<%
if (request.getParameter("username").equals("praveen"))
{
if(request.getParameter("password").equals("praveen"))
{
<h2>Valid User Name and Password</h2>
}
else
{
%>
<h2> Invalid Password </h2>
<%
}
}
else
{
%>
<h2> Invalid User Name</h2>
<%
}
%>
</body>
</html>

Department of MCA, Bangalore Institute Of Technology Page 19


Advanced JAVA Programming Laboratory 13MCA47

 Select Welcome.html->Right Click->Run

Department of MCA, Bangalore Institute Of Technology Page 20


Advanced JAVA Programming Laboratory 13MCA47

Department of MCA, Bangalore Institute Of Technology Page 21


Advanced JAVA Programming Laboratory 13MCA47

5. b. Write JSP Program to demonstrate the import attribute.


lab05.jsp

<!DOCTYPE html>
<html>
<head>
<title>Lab05b</title>
</head>
<body>
<h1>Lab 05b</h1>
<center>
<%@page import="java.util.Random" %>
<%
Random ran = new Random();
int ranNum = ran.nextInt(100);
%>
<b>Random number generated is: </b>
<% ranNum %>
</center>
</body>
</html>

Department of MCA, Bangalore Institute Of Technology Page 22


Advanced JAVA Programming Laboratory 13MCA47

6. Write a JAVA JSP Program which uses jsp:include and jsp:forward


action to display a web page.
lab06.html
<html>
<head>
<title>Lab 06</title>
</head>
<body>
<center>
<form action="lab06.jsp" method="POST" >
<pre>
<b>Select a method</b><br/><br/>
Include: <input type="radio" name="rad" value="include" /><br/>
Forward: <input type="radio" name="rad" value="forward" /><br/>
<input type="Submit" value="Submit" />
</pre>
</form>
</center>
</body>
</html>

lab06.jsp
<html>
<head>
<title>Lab 06</title>
</head>

Department of MCA, Bangalore Institute Of Technology Page 23


Advanced JAVA Programming Laboratory 13MCA47

<body>
<% String s;
s = request.getParameter("rad");
if("include".equals(s))
{
%>
<jsp:include page="includepage.jsp"/>
}
else
{
%>
<jsp:forward page="forwardpage.jsp"/>
<% }
%>
</body>
</html>

includepage.jsp
<html>
<head>
<title>Include page</title>
</head>
<body>
<h1>Include page</h1>
</body>
</html>

Department of MCA, Bangalore Institute Of Technology Page 24


Advanced JAVA Programming Laboratory 13MCA47

forwardpage.jsp
<html>
<head>
<title>Forward page</title>
</head>
<body>
<h1>Forward page</h1>
</body>
</html>

Department of MCA, Bangalore Institute Of Technology Page 25


Advanced JAVA Programming Laboratory 13MCA47

Department of MCA, Bangalore Institute Of Technology Page 26


Advanced JAVA Programming Laboratory 13MCA47

7. Write a JAVA JSP Program which uses <jsp:plugin> tag to run a applet.

Steps to create project:

 File->New Project->Categories:Java Web->Projects:Web Application->Project


Name:Lab10->Next->Next->Finish

 Select Lab10->Right Click->New->Other->Categories:Java->File Types:Java Class-


>Next->Class Name:JavaApplet->Finish

JavaApplet.java

import java.applet.Applet;
import java.awt.Graphics;

/*<applet code="JavaApplet.class" width=300 height=300>


</applet>
*/

public class JavaApplet extends Applet


{
int x1=0, y1=20, x2, y2;

@Override
public void init()
{
setBackground (Color.yellow);

Department of MCA, Bangalore Institute Of Technology Page 27


Advanced JAVA Programming Laboratory 13MCA47

@Override
public void paint(Graphics g)
{
if(x1 > 300)
x1=0;
g.fillOval(x1, y1, 30, 30);
x1++;
try
{
Thread.Sleep(100);
}
catch(Exception e){}
repaint();
}
}

 Select the index.jsp in the Lab10->Web Pages and Type the following

Index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<title>Applet JSP Page</title>
</head>
<body>
<jsp:plugin type="applet" code="JavaApplet.class" codebase="applet"
width="400" height="400">
<jsp:fallback>
<p>Unable to load applet</p>
</jsp:fallback>
</jsp:plugin>
</body>
</html>

Department of MCA, Bangalore Institute Of Technology Page 28


Advanced JAVA Programming Laboratory 13MCA47

 Select Lab10->Right Click->Clean and Build

 Select Files Tab->Lab10->build->web->WEB-INF->classes->JavaApplet.class->Right


Click->Copy
->Right Click->Paste

 Select Projects Tab->Lab10->Right Click->Run

 The browser will be Internet Explorer

Department of MCA, Bangalore Institute Of Technology Page 29


Advanced JAVA Programming Laboratory 13MCA47

8. Write a JAVA JSP Program to get student information through a HTML


and create a JAVA Bean Class, populate Bean and display the same
information through another JSP.

Steps to create project:

 File->New Project->Categories:Java Web->Projects:Web Application->Project


Name:Lab8->Next->Next->Finish

 Select Lab9->Right Click->New->Other->Categories:Java->File Types:Java Class-


>Next->Class Name:Student->Package:std->Finish

Student.java

package std;

public class Student


{
String sname,usnno,branch;

public void setSname(String s)


{
sname=s;
}

public String getSname()


Department of MCA, Bangalore Institute Of Technology Page 30
Advanced JAVA Programming Laboratory 13MCA47

{
return sname;
}

public void setUsnno(String u)


{
usnno=u;
}

public String getUsnno()


{
return usnno;
}

public void setBranch(String b)


{
branch=b;
}

public String getBranch()


{
return branch;
}
}

 Select Lab9->Right Click->New->Other->Categories:Web->File Types:JSP->Next->File


Name:View->Finish

View.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>View JSP Page</title>
</head>
<body>
Department of MCA, Bangalore Institute Of Technology Page 31
Advanced JAVA Programming Laboratory 13MCA47

<jsp:useBean id="sd" scope="session" class="student"/>


<h1> Student Details </h1><br/>
Name:<jsp:getProperty name="sd" property="sname"/><br/>
USN:<jsp:getProperty name="sd" property="usnno"/><br/>
Branch:<jsp:getProperty name="sd" property="branch"/><br/>
</body>
</html>

 Select the index.jsp in the Lab9->Web Pages and Type the following

Index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index JSP Page</title>
</head>
<body>
<jsp:useBean id="sd" scope="session" class="std.student"/>
<jsp:setProperty name="sd" property="*" />
<jsp:forward page="view.jsp" />
</body>
</html>

 Select Lab9->Right Click->New->Other->Categories:Web->File Types:HTML->Next-


>HTML File Name:Stud->Finish

Stud.html

<!DOCTYPE html>
<html>
<head>
<title>Student Entry</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
Department of MCA, Bangalore Institute Of Technology Page 32
Advanced JAVA Programming Laboratory 13MCA47

<body>
<form action="index.jsp" method="post">
Enter Name:<input type="text" name="sname"/><br/>
Enter USN:<input type="text" name="usnno"/><br/>
Enter Branch:<input type="text" name="branch"/><br/>
<input type="submit" value="OK"/>
</form>
</body>
</html>

 Select Stud.html->Right Click->Run

Department of MCA, Bangalore Institute Of Technology Page 33


Advanced JAVA Programming Laboratory 13MCA47

9. Write a JAVA Program to insert data into Student Database and


retrieve info based on particular queries (For example update, delete,
search etc...)

Steps to create poject:

 File->New Project->Categories:Java Web->Projects:Web Application->Project


Name:Lab9->Next->Next->Finish

Steps to connection to database:

 Go to Services Tab->Databases->MySQL Server at localhost:3306[root]


->Right Click->Connect
->Create Database->New Database Name:student->OK

 It will create a database

 Right Click->Connect
->employee->Tables->Right Click->Create Table->Table Name:std
->Add Column
->Name:usn->Type:VARCHAR->Select CheckBoxes->Primary Key->Unique->OK
->Name:name->Type:VARCHAR->Size:20->OK
->Name:sem->Type:INT->OK
->OK

 Select Projects Tab->Lab9->Right Click->Properties->Categories:Libraries->Add


JAR/Folder->C:/Program Files/mysql-connector-java-5.1.5-bin.jar->Open->OK
Department of MCA, Bangalore Institute Of Technology Page 34
Advanced JAVA Programming Laboratory 13MCA47

Steps to create java class file:

 Select Lab9->Right Click->New->Other->Categories:Java->File Types:Java Class-


>Next->Class Name:Student->Package:std->Finish

Student.java

package std;
import java.sql.*;
import java.util.Scanner;

public class Student


{
Connection con;
public void estConnection()throws ClassNotFoundException, SQLException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","mca");
}
catch(ClassNotFoundException e)
{
System.err.println(e.getMessage());
System.err.println("Driver class not found");
}
catch(SQLException e)
{
System.err.println("Connection failed");
}
}

public void sInsert(String u,String n,int s) throws ClassNotFoundException, SQLException


{
estConnection();
if(con!=null)
{
Department of MCA, Bangalore Institute Of Technology Page 35
Advanced JAVA Programming Laboratory 13MCA47

try
{
PreparedStatement pst;
pst=con.prepareStatement("insert into std(usn,name,sem) values(?,?,?)");
pst.setString(1,u);
pst.setString(2,n);
pst.setInt(3,s);
int i=pst.executeUpdate();
if(i==1)
{
System.out.println("Record inserted successfully");
}
else
{
System.out.println("Invalid Insertion");
}
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
finally
{
con.close();
}
}
}
public void sSelect(String u)throws ClassNotFoundException, SQLException
{
estConnection();
if(con!=null)
{
try
{
PreparedStatement pst;
pst=con.prepareStatement("select * from std where usn=?");
pst.setString(1,u);
ResultSet res;
Department of MCA, Bangalore Institute Of Technology Page 36
Advanced JAVA Programming Laboratory 13MCA47

res=pst.executeQuery();
if(res.next())
{
System.out.println("USN="+res.getString(1)+"\tName="+res.getString(2)+"\tSem="+res.getInt(
3));
}
else
{
System.out.println("USN not found");
}
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
finally
{
con.close();
}
}
}

public void sUpdate(String u, String n,int s)throws ClassNotFoundException, SQLException


{
estConnection();
if(con!=null)
{
try
{
PreparedStatement pst;
pst=con.prepareStatement("update std set name=?,sem=? where usn=?");
pst.setString(1,n);
pst.setInt(2,s);
pst.setString(3,u);
int i=pst.executeUpdate();
if(i==1)
{
System.out.println("Record updated successfully");
Department of MCA, Bangalore Institute Of Technology Page 37
Advanced JAVA Programming Laboratory 13MCA47

}
else
{
System.out.println("USN not found");
}
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
finally
{
con.close();
}
}
}

public void sDelete(String u)throws ClassNotFoundException, SQLException


{
estConnection();
if(con!=null)
{
try
{
PreparedStatement pst;
pst=con.prepareStatement("delete from std where usn=?");
pst.setString(1,u);
int i=pst.executeUpdate();
if(i==1)
{
System.out.println("Record deleted successfully");
}
else
{
System.out.println("USN not found");
}
}
catch(SQLException e)
Department of MCA, Bangalore Institute Of Technology Page 38
Advanced JAVA Programming Laboratory 13MCA47

{
System.out.println(e.getMessage());
}
finally
{
con.close();
}
}
}

public void viewAll() throws ClassNotFoundException, SQLException


{
estConnection();
if(con!=null)
{
try
{
PreparedStatement pst;
pst=con.prepareStatement("select * from std");
ResultSet res;
res=pst.executeQuery();
System.out.println("USN\tName\tSem");
while(res.next())
{
System.out.println(res.getString(1)+"\t"+res.getString(2)+"\t"+res.getInt(3));
}
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
finally
{
con.close();
}
}
}

Department of MCA, Bangalore Institute Of Technology Page 39


Advanced JAVA Programming Laboratory 13MCA47

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


{
Student st=new Student();
String usn,name;
int sem;
Scanner sc=new Scanner(System.in);
while(true)
{
System.out.println("1.Insert\n2.Select\n3.Update\n4.Delete\n5.ViewAll\n6.Exit");
System.out.println("Select the option");
switch(sc.nextInt())
{
case 1: System.out.println("Enter usn to insert");
usn=sc.next();
System.out.println("Enter name to insert");
name=sc.next();
System.out.println("Enter sem to insert");
sem=sc.nextInt();
st.sInsert(usn,name,sem);
break;
case 2: System.out.println("Enter usn to select");
usn=sc.next();
st.sSelect(usn);
break;
case 3: System.out.println("Enter usn to update");
usn=sc.next();
System.out.println("Enter name to update");
name=sc.next();
System.out.println("Enter sem to update");
sem=sc.nextInt();
st.sUpdate(usn,name,sem);
break;
case 4: System.out.println("Enter usn to delete");
usn=sc.next();
st.sDelete(usn);
break;
case 5: st.viewAll();
break;
Department of MCA, Bangalore Institute Of Technology Page 40
Advanced JAVA Programming Laboratory 13MCA47

case 6: System.exit(0);
default: System.out.println("Invalid option");
}
}
}
}

 Select Student.java->Right Click->Run

10.Write a JSP program to implement all the attributes of the page


directive tag.
Department of MCA, Bangalore Institute Of Technology Page 41
Advanced JAVA Programming Laboratory 13MCA47

directive.jsp

<html>
<body>
<h2>This Demonstrates Content type and language</h2>
<%@ page contentType="text/html" %>
<%@ page language="java" %>

<%=response.getContentType()%>

<h2>This Demonstrates Page Info directive</h2>


<%@ page info="This JSP Page Shows page directive tags usage" %>
<%= getServletInfo()%><br/>

<h2>This Demonstrates isThreadSafe set to false, by default it is true</h2>


<%@ page isThreadSafe="false" %>

<h2>This Demonstrates page Import directive</h2>


<%@ page import="java.util.Date" %>
<% out.println("Todays date is "+ new Date());%><br/>

<h2>This Demonstrates isELIIgnored directive,set to true here</h2>


<%@ page isELIgnored="true" %>
<b>2 raised to 3 is ${2*2*2}</b></br>

<h2>This Demonstrates errorPage and isErrorPage</h2>


<%@ page errorPage="myerrorpage.jsp" %>
<b>100/5 is <%= 100/5 %></b> <br/>

<h2>This Demonstrates Session</h2>


<%@ page session="true"%>
<% session.setAttribute("Name","Bubba"); %>
<a href="session.jsp">Click here to test session directive</a><br/><br/><br/>

<h2>This Demonstrates buffer and autoFlush directives</h2>


<%@ page buffer="2kb" %>
Department of MCA, Bangalore Institute Of Technology Page 42
Advanced JAVA Programming Laboratory 13MCA47

<%@ page autoFlush="true" %>


<%
for(int i=0;i<=500;i++)
{
out.println("Hello world!!");
} %>
</body>
</html>

myerrorpage.jsp

<html>
<body>
<%@ page isErrorPage="true" %>

Sorry an exception occured!<br/>


The exception is: <%= exception %>

</body>
</html>

session.jsp

<html>
<body>

<h2>This Demonstrates Content type</h2>


<%@ page contentType="text/plain" %>
Content type set to <%=response.getContentType()%>
<%@ page session="true"%>
<b>Your name is : <%=session.getAttribute("Name")%> </b>

<body>
</html>

Department of MCA, Bangalore Institute Of Technology Page 43


Advanced JAVA Programming Laboratory 13MCA47

when seesion.jsp is set to true


Department of MCA, Bangalore Institute Of Technology Page 44
Advanced JAVA Programming Laboratory 13MCA47

myerrorpage when 100/0

myerrorpage when autoflush is set to false.

11. An EJB Application that demonstrates Session Bean(with appropriate


business logic).
Department of MCA, Bangalore Institute Of Technology Page 45
Advanced JAVA Programming Laboratory 13MCA47

Steps to create project:

 File->New Project->Categories:Java EE->Projects:Enterprise Applications->Next-


>Project Name:Lab11->Next->Finish

 It will create 3 projects:


 Lab11
 Lab11-ejb
 Lab11-war

 Select Lab11-ejb->Right Click->New->Other->Categories:Enterprise JavaBeans->File


Types:Session Bean->Next->EJB Name:CircleEJBBean->Create Interface:Local-
>Finish.

 It Creates 2 Files

Department of MCA, Bangalore Institute Of Technology Page 46


Advanced JAVA Programming Laboratory 13MCA47

 CircleEJBBean.java
 CircleEJBBeanLocal.java

 Select CircleEJBBean->In Source Code->In Body Of the Class->Right click->Insert


Code->Add Business Method
->Name:area->Return Type:->Browse->Double->Parameters->Add->Name:r-
>Type:double->OK
->Name:circum->Return Type:->Browse->Double->Parametrs->Add->Name:r-
>Type:double->OK

CircleEJBBean.java

package stateless;

import javax.ejb.Stateless;

@Stateless
public class CircleEJBBean implements CircleEJBBeanLocal
{
@Override
public Double area(double r)
{
return (3.14*r*r);
}

@Override
public Double circum(double r)
{
return (2*3.14*r);
}
}

CircleEJBBeanLocal.java

package stateless;

import javax.ejb.Local;

Department of MCA, Bangalore Institute Of Technology Page 47


Advanced JAVA Programming Laboratory 13MCA47

@Local
public interface CircleEJBBeanLocal
{

Double area(double r);

Double circum(double r);

 Select Lab11-war->Right Click->New->Web->Servlet->Next->Class


Name:CircleServlet->Package:servlets->Next->Finish

 Select NewServlet.java->In the Source Code->In processRequest() method->In try block-


>In the Comment Line->Right Click->Insert Code->Call Enterprise Bean->select Lab11-
ejb->in that Select CircleEJBBean->Press OK

 Type the following source code into that try block

CircleServlet.java

package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
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 stateless.CircleEJBBeanLocal;

@WebServlet(name = "CircleServlet", urlPatterns = {"/CircleServlet"})


Department of MCA, Bangalore Institute Of Technology Page 48
Advanced JAVA Programming Laboratory 13MCA47

public class CircleServlet extends HttpServlet


{
@EJB
private CircleEJBBeanLocal circleEJBBean;

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
double result=0.0;
String s1=request.getParameter("rad");
String s2=request.getParameter("group1");
if(s2.equals("carea"))
{
result=circleEJBBean.area(Double.valueOf(s1));
}
if(s2.equals("ccircum"))
{
result=circleEJBBean.circum(Double.valueOf(s1));
}
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet CircleServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet CircleServlet at " + request.getContextPath() +
"</h1>");
out.println("<h4>Result="+result+"</h4>");
out.println("</body>");
out.println("</html>");
}
finally
{
Department of MCA, Bangalore Institute Of Technology Page 49
Advanced JAVA Programming Laboratory 13MCA47

out.close();
}
}
}

 Select the index.jsp in the Lab12->Web Pages and Type the following

Index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Circle</title>
</head>
<body bgcolor="Ivory">
<h1>Circle</h1>
<hr>
<form action="CircleServlet">
<p>
Enter radius value:<input type="text" name="rad" size="25">
</p>
<b>Select your choice:</b><br>
<input type="radio" name="group1" value="carea">Area<br>
<input type="radio" name="group1"
value="ccircum">Circumference<br>
<p>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</p>
</form>
</body>
</html>

 Select Lab12-ejb->Right Click->Clean and Build


->Deploy

Department of MCA, Bangalore Institute Of Technology Page 50


Advanced JAVA Programming Laboratory 13MCA47

 Select Lab12->Right Click->Clean and Build


->Deploy
->Run

Department of MCA, Bangalore Institute Of Technology Page 51


Advanced JAVA Programming Laboratory 13MCA47

Department of MCA, Bangalore Institute Of Technology Page 52


Advanced JAVA Programming Laboratory 13MCA47

12. An EJB Application that demonstrates MDB.

Steps to create project:

 File->New Project->Categories:Java EE->Projects:Enterprise Applications->Next-


>Project Name:Lab12->Next->Finish

 It will create 3 projects:


 Lab12
 Lab12-ejb
 Lab12-war

Department of MCA, Bangalore Institute Of Technology Page 53


Advanced JAVA Programming Laboratory 13MCA47

Steps to create JMS Resources:

 Go to Services->Servers->GlassFish Server 3.1.2->Right Click->Start


->View Domain Admin Console

 It opens the browser

 In that Select in Common Tasks->Resources->JMS Resources->Connection Factories

 In the Destination Resources->Select New ->Destination Resources

 JNDI Name:jms/dest
 Physical Destination Name:Destination
 Resource Type:javax.jms.Queue

->OK
 Close Browser

Department of MCA, Bangalore Institute Of Technology Page 54


Advanced JAVA Programming Laboratory 13MCA47

 Go to NetBeans
 Select Lab12-ejb->Right Click->New->Other->Categories:Enterprise JavaBeans->File
Types:Message-Driven Bean->Next

 EJB Name:Mymdb
 Package:mdb
 Server Destination:jms/dest
->Finish

Mymdb.java

package mdb;

import java.util.logging.Level;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import java.util.logging.Logger;

@MessageDriven(mappedName = "jms/dest", activationConfig = {


@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-
acknowledge"),
@ActivationConfigProperty(propertyName = "destinationType", propertyValue =
"javax.jms.Queue")
})

public class Mymdb implements MessageListener


{
public Mymdb()
{
}

@Override
public void onMessage(Message message)
Department of MCA, Bangalore Institute Of Technology Page 55
Advanced JAVA Programming Laboratory 13MCA47

{
TextMessage tmsg=null;
tmsg=(TextMessage)message;
try
{
System.out.println(tmsg.getText());
}
catch(JMSException ex)
{
Logger.getLogger(Mymdb.class.getName()).log(Level.SEVERE, null,
ex);
}
}
}

 Select Lab12-war->Right Click->New->Other->Web->Servlet->Next->Class


Name:mdbservlet->Package:servlet->Next->Finish

 Select mdbservlet.java->in Source Code->processRequest()->try{}->Right Click->Insert


Code->Send JMS Message->Connection Factory:jms/queue->OK

 Type the following code in processRequest() method…….

mdbservlet.java

package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Queue;
Department of MCA, Bangalore Institute Of Technology Page 56
Advanced JAVA Programming Laboratory 13MCA47

import javax.jms.Session;
import javax.jms.TextMessage;
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(name = "mdbservlet", urlPatterns = {"/mdbservlet"})

public class mdbservlet extends HttpServlet


{
@Resource(mappedName = "jms/dest")
private Queue dest;
@Resource(mappedName = "jms/queue")
private ConnectionFactory queue;

protected void processRequest(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException
{
String msg;
msg=request.getParameter("message");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
sendJMSMessageToDest(msg);
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet mdbservlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Message Sent</h1>");
out.println("<h2>Please Chek your server log!</h2>");
out.println("</body>");
out.println("</html>");
}
Department of MCA, Bangalore Institute Of Technology Page 57
Advanced JAVA Programming Laboratory 13MCA47

catch(JMSException ex)
{
Logger.getLogger(mdbservlet.class.getName()).log(Level.SEVERE,null,ex);
}
finally
{
out.close();
}
}

private Message createJMSMessageForjmsDest(Session session, Object messageData)


throws JMSException
{
TextMessage tm = session.createTextMessage();
tm.setText(messageData.toString());
return tm;
}

private void sendJMSMessageToDest(Object messageData) throws JMSException


{
Connection connection = null;
Session session = null;
try
{
connection = queue.createConnection();
session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(dest);
messageProducer.send(createJMSMessageForjmsDest(session,
messageData));
}
finally
{
if (session != null)
{
try
{
session.close();
Department of MCA, Bangalore Institute Of Technology Page 58
Advanced JAVA Programming Laboratory 13MCA47

}
catch (JMSException e)
{
Logger.getLogger(this.getClass().getName()).log(Level.WARNING,
"Cannot close session", e);
}
}
if (connection != null)
{
connection.close();
}
}
}
}

 Select Lab12-war->Web Pages->index.jsp->Type the following Source code

Index.jsp

<%@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="mdbservlet" method="post">
Message:<input type="text" name="message" size="100"/><br/>
<input type="submit" value="send"/>
</form>
</body>
</html>

 Select Lab12-ejb->Right Click->Clean and Build

Department of MCA, Bangalore Institute Of Technology Page 59


Advanced JAVA Programming Laboratory 13MCA47

->Deploy
 Select Lab12->Right Click->Clean and Build
->Deploy
->Run

Output:

Department of MCA, Bangalore Institute Of Technology Page 60


Advanced JAVA Programming Laboratory 13MCA47

 Close Browser and Goto NetBeans->Output window->Glass Fish Server Tab


.

13. An EJB Application that demonstrates persistence(with appropriate


business logic).

Steps to create project:

 File->New Project->Categories:Java EE->Projects:Enterprise Applications->Next-


>Project Name:Lab13->Next->Finish

 It will create 3 projects:

Department of MCA, Bangalore Institute Of Technology Page 61


Advanced JAVA Programming Laboratory 13MCA47

 Lab13
 Lab13-ejb
 Lab13-war

Steps to connect database:

 Go to Services->Databases->MySQL Server at localhost:3306[root]


->Right Click->Connect
->Create Database->New Database Name:employee->OK

 It will create a database

 jdbc:mysql://localhost:3306/employee?zeroDateTimeBehavior=convertToNull [root on
Default schema]->Right Click->Connect
->employee->Tables->Right Click->Create Table->Table Name:Emp
Department of MCA, Bangalore Institute Of Technology Page 62
Advanced JAVA Programming Laboratory 13MCA47

->Add Column->Name:ID->Type:INT->Select CheckBoxes->Primary Key->Unique-


>OK
->Name:name->Type:VARCHAR->Size:20->OK
->OK

 Select Projects Tab->Lab13->Right Click->Properties->Categories:Libraries->Add


JAR/Folder->C:/Program Files/mysql-connector-java-5.1.5-bin.jar->Open->OK

 Select Lab13-ejb->Right Click->New->Other->Categories:Persistence->File


Types:Entity Classes from Databases->Next->Data Source:New Data Source->JNDI
Name:employee->Database Connection:
jdbc:mysql://localhost:3306/employee?zeroDateTimeBehavior=convertToNull [root on
Default schema]->OK->Select Available Tables:emp->Add->Next->Package:server-
>Next->Finish

Emp.java

package server;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;

@Entity
@Table(name = "emp")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Emp.findAll", query = "SELECT e FROM Emp e"),
@NamedQuery(name = "Emp.findById", query = "SELECT e FROM Emp e WHERE e.id =
:id"),
Department of MCA, Bangalore Institute Of Technology Page 63
Advanced JAVA Programming Laboratory 13MCA47

@NamedQuery(name = "Emp.findByName", query = "SELECT e FROM Emp e WHERE


e.name = :name")})

public class Emp implements Serializable


{
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "ID")
private Integer id;
@Size(max = 20)
@Column(name = "Name")
private String name;

public Emp()
{
}

public Emp(Integer id)


{
this.id = id;
}

public Integer getId()


{
return id;
}

public void setId(Integer id)


{
this.id = id;
}

public String getName()


{
return name;
}
Department of MCA, Bangalore Institute Of Technology Page 64
Advanced JAVA Programming Laboratory 13MCA47

public void setName(String name)


{
this.name = name;
}

@Override
public int hashCode()
{
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}

@Override
public boolean equals(Object object)
{
if (!(object instanceof Emp))
{
return false;
}
Emp other = (Emp) object;
if ((this.id == null && other.id != null) || (this.id != null &&
!this.id.equals(other.id)))
{
return false;
}
return true;
}

@Override
public String toString()
{
return "server.Emp[ id=" + id + " ]";
}

Department of MCA, Bangalore Institute Of Technology Page 65


Advanced JAVA Programming Laboratory 13MCA47

 Select Lab13-ejb->Right click->New->Other->Enterprise JavaBeans->Session Beans For


Entity Classes->Next->Select the Availability Entity Classes and Press Add->Next-
>Select the Local checkbox in Create Interfaces->Finish

 It will create 3 files


 AbstractFacade.java
 EmpFacade.java
 EmpFacadeLocal.java

 Select the AbstractFacade.java and Erase all methods in below create() method….

AbstractFacade.java

package server;

import java.util.List;
import javax.persistence.EntityManager;

public abstract class AbstractFacade<T>


{
private Class<T> entityClass;

public AbstractFacade(Class<T> entityClass)


{
this.entityClass = entityClass;
}

protected abstract EntityManager getEntityManager();

public void create(T entity)


{
getEntityManager().persistent(entity);
}
}

 Select the EmpFacadeLocal.java and Erase all methods in below create() method…

 Right click in the body of the class->Insert Code->Add Business Method…


Department of MCA, Bangalore Institute Of Technology Page 66
Advanced JAVA Programming Laboratory 13MCA47

 Name:addEmp
 Return Type:void
 Parameters->Add->Name:id->Type:int
->Add->Name:name->Type:String
->OK

 In the addEmp() type the following

EmpFacade.java

package server;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class EmpFacade extends AbstractFacade<Emp> implements EmpFacadeLocal
{
@PersistenceContext(unitName = "Lab13-ejbPU")
private EntityManager em;

@Override
protected EntityManager getEntityManager()
{
return em;
}

public EmpFacade()
{
super(Emp.class);
}

@Override
public void addEmp(int id, String name)
{
Emp e=new Emp();
e.setId(id);
Department of MCA, Bangalore Institute Of Technology Page 67
Advanced JAVA Programming Laboratory 13MCA47

e.setName(name);
create(e);
}
}

EmpFacadeLocal.java

package server;

import javax.ejb.Local;

@Local
public interface EmpFacadeLocal
{
void create(Emp emp);

void addEmp(int id, String name);


}

 Select Lab13-war->Right click->New->Other->Web->Servlet->Next->Class


Name:NewServlet->Package:servlets->Next->Finish

 Select NewServlet.java->In the Source Code->In try block->In the Comment Line-
>Right Click->Insert Code->Call Enterprise Bean->select Lab13-ejb->in that Select
EmpFacade->Press OK

 Type the following source code into that try block


NewServlet.java

package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
Department of MCA, Bangalore Institute Of Technology Page 68
Advanced JAVA Programming Laboratory 13MCA47

import javax.servlet.http.HttpServletResponse;
import server.EmpFacadeLocal;

@WebServlet(name = "NewServlet", urlPatterns = {"/NewServlet"})

public class NewServlet extends HttpServlet


{
@EJB
private EmpFacadeLocal empFacade;

protected void processRequest(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
int eid;
String ename;
eid=Integer.parseInt(request.getParameter("id"));
ename=request.getParameter("name");
empFacade.addEmp(eid, ename);
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet NewServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>ID:"+eid+"</h1>");
out.println("<h1>Name:"+ename+"</h1>");
out.println("<h1>Database Updated</h1>");
out.println("</body>");
out.println("</html>");
}
finally
{
out.close();
}
Department of MCA, Bangalore Institute Of Technology Page 69
Advanced JAVA Programming Laboratory 13MCA47

}
}

 Select the index.jsp in the Lab13-war->Web Pages and Type the following

Index.jsp

<%@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 bgcolor="cream">
<form action="NewServlet" method="get">
<h3>Session Entity Bean</h3><br>
<h3>Employee Details</h3>
<hr>
Employee ID:<input type="text" size="3" name="id"><br><br>
Employee Name:<input type="text" size="15" name="name"><br><br>
<input type="submit" name="post" value="post">
<input type="reset" name="clear" value="clear">
</form>
</body>
</html>

 Select Lab13-ejb->Right Click->Clean and Build


->Deploy
 Select Lab13->Right Click->Clean and Build
->Deploy
->Run

Department of MCA, Bangalore Institute Of Technology Page 70


Advanced JAVA Programming Laboratory 13MCA47

Select * from Emp;

 Right click->Run File

Department of MCA, Bangalore Institute Of Technology Page 71


Advanced JAVA Programming Laboratory 13MCA47

Department of MCA, Bangalore Institute Of Technology Page 72

Vous aimerez peut-être aussi