0% found this document useful (0 votes)
225 views

Java Manual 16MCA41

The document contains 4 Java servlet programs: 1. A servlet that accepts user input from an HTML form and displays it. 2. A servlet that automatically refreshes a webpage every 2 seconds to display updated date and time. 3. A servlet that demonstrates the GET and POST HTTP methods by displaying submitted form data. 4. A servlet that uses cookies to remember user preferences like name and email from a registration form.

Uploaded by

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

Java Manual 16MCA41

The document contains 4 Java servlet programs: 1. A servlet that accepts user input from an HTML form and displays it. 2. A servlet that automatically refreshes a webpage every 2 seconds to display updated date and time. 3. A servlet that demonstrates the GET and POST HTTP methods by displaying submitted form data. 4. A servlet that uses cookies to remember user preferences like name and email from a registration form.

Uploaded by

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

16MCA46 Advance Java Programming Laboratory

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).

index.html

<html>
<head>
<title>User Input Form</title>
</head>
<body>
<h2>User Input Form</h2>
<form action="EchoServlet" method="Get">
<fieldset>
<legend>Personal Information</legend>
User Name: <input type="text" name="username"/><br/>
Password: <input type="password" name="password"/><br/>
</fieldset>
<input type="submit" value="SEND"/>
<input type="reset" value="CLEAR"/>
</form>
</body>
</html>

EchoServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class EchoServlet extends HttpServlet {


@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String name=request.getParameter("username");
String secretword=request.getParameter("password");
out.println("<html>");
out.println("<head>");
out.println("<title>EchoServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h2>You have Entered</h2>");
out.println("<p>Name: " + name + "</p>");
out.println("<p>Password: " + secretword + "</p>");
out.println("</body>");
out.println("</html>");
}
}

By Suma M G, Dept. of MCA, RNSIT 1


16MCA46 Advance Java Programming Laboratory

2. Write a JAVA Servlet Program to Auto Web Page Refresh (Consider a webpage which is displaying Date
and time or stock market status. For all such type of pages, you would need to refresh your web page
regularly; Java Servlet makes this job easy by providing refresh automatically after a given interval).

RefreshPage2.java

import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RefreshPage2 extends HttpServlet {


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

resp onse.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

try {
response.addHeader("Refresh", "2");
out.println("<h1>Servlet says Wonderful day:"
+ new Date() + "</h1>");
}
finally{
out.println("<br><h2>My Page Automatically Refreshed!
Don't Press F5</h2>");
}
}
}

By Suma M G, Dept. of MCA, RNSIT 2


16MCA46 Advance Java Programming Laboratory

3. Write a JAVA Servlet Program to implement and demonstrate get() and Post methods(Using HTTP Servlet
Class).

index.html

<html>
<head>
<title>Lab3</title>
</head>
<body>
<H1>Post Method</H1>
<form name="form1" action="DispColor" method="Post">
Choose the page color <select name="color">
<option> Red </option>
<option> Green </option>
<option> Blue </option>
<option> Pink </option>
<option> Yellow </option>
<option> White </option>
</select>
<input type="submit"/>
</form>
<H1>Get Method</H1>
<form name="form2" action="DispColor" method="Get">
Choose your gender:
<input type="Radio" name="gen" value="Male"/> Male
<input type="Radio" name="gen" value="Female"/>
Female <br>
<input type="submit"/>
</form>
</body>
</html>

DispColor.java

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

public class DispColor extends HttpServlet {


@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

PrintWriter out = response.getWriter();


out.println("<body>");

By Suma M G, Dept. of MCA, RNSIT 3


16MCA46 Advance Java Programming Laboratory

DispColor.java(continued)

out.println("<h1>Http Method is "+request.getMethod()+ </h1>");


out.println("Gender is " + request.getParameter("gen"));
out.println("</body>");
}

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

PrintWriter out = response.getWriter();

String clr = request.getParameter("color");

out.println("<body bgcolor="+clr+">");
out.println("<h1>Http Method is " +request.getMethod()+
"</h1>");
out.println("Color name is " + clr);
out.println("</body>");
}
}

By Suma M G, Dept. of MCA, RNSIT 4


16MCA46 Advance Java Programming Laboratory

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

index.html

<html>
<head>
<title>Cookies to remember user preferences</title>
</head>
<body>
<form action="RegistrationForm">
<fieldset>
<legend>Information</legend>
First Name: <input type="text" placeholder="Enter First
Name" name="firstName"/><br><br>
Last Name : <input type="text" placeholder="Enter Last
Name" name="lastName"/><br><br>
Email-ID : <input type="text" placeholder="Enter Email
Name" name="email"/><br><br>
<input type="submit">
</fieldset>
</form>
</body>
</html>

RegistrationForm.java

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

public class RegistrationForm extends HttpServlet {

@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
boolean isMissingValue=false;
PrintWriter out = response.getWriter();

String fn = request.getParameter("firstName");

//creating cookie object


Cookie FnCookie = new Cookie("fname", fn);
Cookie LnCookie = new Cookie("lname", ln);
Cookie EmailCookie = new Cookie("email", email);

By Suma M G, Dept. of MCA, RNSIT 5


16MCA46 Advance Java Programming Laboratory

RegistrationForm.java(cont..)

//setting lifespan to a cookie(1 year)


FnCookie.setMaxAge(60*60*24*365);
LnCookie.setMaxAge(60*60*24*365);
EmailCookie.setMaxAge(60*60*24*365);

//adding cookie in the response object


response.addCookie(FnCookie);
response.addCookie(LnCookie);
response.addCookie(EmailCookie);

out.println("Cookie Created....! <BR>" +


"<A HREF='ReadCookie'> Read Cookies Servlet </A>");
}
}

ReadCookie.java

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

public class ReadCookie extends HttpServlet {


@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String title = "Active Cookies";
out.println("<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +
"<TABLE BORDER=1 ALIGN=\"CENTER\">\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" + "<TH>Cookie Name</TH>" +
"<TH>Cookie Value</TH>");
//Read array of cookies from the request object
Cookie[] cks = request.getCookies();
Cookie ck; //Declare a cookie object
for(int i=0; i<cks.length; i++) {
ck = cks[i]; //single value from cks is copy to ck
out.println("<TR>" + " <TD>" + ck.getName() + "</TD>" +
"<TD>" + ck.getValue()+ "</TD>" + "</TR>");
}
out.println("</TABLE></BODY></HTML>");
}
finally {
out.close();
}} }

By Suma M G, Dept. of MCA, RNSIT 6


16MCA46 Advance Java Programming Laboratory
5. Write a JAVA Servlet program to track HttpSession by accepting user name and password using
HTML and display the profile page on successful login.

index.html

<html>
<head><title>Lab5 - Using HttpSession</title></head>
<body>
<form action="LoginForm" method="Post">
<fieldset>
<legend>Login Information</legend>
User Name: <input type="text" placeholder="Enter User Name"
name="username"/><br><br>
Password : <input type="password" placeholder="Enter password"
name="password"/><br><br>
<input type="submit" value="login">
</fieldset>
</form>
</body>
</html>

LoginForm.jsp

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

public class LoginForm extends HttpServlet {


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

String uname=request.getParameter("username");
String password=request.getParameter("password");

if(password.equals("admin123")) {
//out.print("Welcome, "+uname);
HttpSession session=request.getSession();
session.setAttribute("name",uname);
response.sendRedirect("ProfilePage");
}
else{
out.print("Sorry, username or password error!");
//response.sendRedirect("index.html");
request.getRequestDispatcher("index.html").include(request,
response);
}
}

By Suma M G, Dept. of MCA, RNSIT 7


16MCA46 Advance Java Programming Laboratory

ProfilePage.java

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

public class ProfilePage extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse
response)throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

HttpSession session=request.getSession(false);
if(session!=null){
String name=(String)session.getAttribute("name");
out.println("<center>");
out.println("<h3>Hello, " + name +
" You have Successfully logged in<br><br>"
+ "Welcome to Profile Page</h3><br>");
out.println("</center>");
}
else{
out.print("Please login first");
response.sendRedirect("index.html");
}
}
}

By Suma M G, Dept. of MCA, RNSIT 8


16MCA46 Advance Java Programming Laboratory

6. Write a JAVA JSP Program which uses jsp:include and jsp:forward action to display a Webpage.

ReadValue.html

<html><head><title>Lab-6</title></head>
<body>
<form action="Login.jsp" method="post">
<H3>Please enter Login Details</H3>
UserName: <input type="text" name="user"/><br/><br/>
Password: <input type="password" name="pass"/><br/><br>
<input type="submit" value="login"/>
</form>
</body>
</html>

Login.jsp

<html><head><title>Login Page</title></head>
<body>
<% String s2=request.getParameter("pass");
if(s2.equals("admin123")) { %>
<jsp:forward page="Welcome.jsp"/>
<% } else{ %>
<h3>Please Re-Enter valid username and password</h3>
<jsp:include page="index.html"/>
<% } %>
</body>
</html>

Welcome.jsp

<html><head><title>Welcome Page</title></head>
<body>
<h3> Login Successful</h1><br/>
Welcome, <%= request.getParameter("user") %>
</body>
</html>

By Suma M G, Dept. of MCA, RNSIT 9


16MCA46 Advance Java Programming Laboratory

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

Lab7.jsp

<html><head><title>JSP Page</title></head>
<body>
<h1>Lab7: implement using jsp:plugin tag to run a applet</h1>

<jsp:plugin type="applet" code="Lab7applet.class"


codebase="." width="400" height="400">

<jsp:fallback>There is a error to download the plugin


</jsp:fallback>
</jsp:plugin>

</body>
</html>

Lab7applet.java

import java.awt.*;
import java.applet.*;

public class Lab7applet extends Applet {


public void init() {
setBackground(Color.red);
}

@Override
public void paint(Graphics g){
g.drawString("RNS Institute of Technology", 30,50);
g.drawString("VTU Belgavi", 60, 80);
}
}

By Suma M G, Dept. of MCA, RNSIT 10


16MCA46 Advance Java Programming Laboratory

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.

index.html

<html>
<body>
<center><br/><br/>
<form action="Lab8.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="submit"/></center>
</form>
</body>
</html>

Student.java

package Bean;
import java.io.Serializable;

public class Student implements Serializable{

private String sname, usnno, branch;

public void setsname(String s){


sname=s;
}
public String getsname(){
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;
}
}

By Suma M G, Dept. of MCA, RNSIT 11


16MCA46 Advance Java Programming Laboratory

BeanProperty.jsp

<html><head><title>JSP Page</title></head>
<body>
<jsp:useBean id="bean" class="Bean.Student" scope="request"/>
<jsp:setProperty name="bean" property="*"/>
<jsp:forward page="viewStudentDetail.jsp"/>
</body>
</html>

viewStudentDetail.jsp

<html><head><title>JSP Page</title></head>
<body>
<jsp:useBean id="bean" class="Bean.Student" scope="request"/>
<center>
<h1><ul><b>Student Information</b></ul></h1>
<h3>Name: <jsp:getProperty name="bean" property="sname"/><br>
USN:<jsp:getProperty name="bean" property="usnno"/><br><br>
Branch:<jsp:getProperty name="bean" property="branch"/>
<br><br></h3>
</center>
</body>
</html>

By Suma M G, Dept. of MCA, RNSIT 12


16MCA46 Advance Java Programming Laboratory

9. Write a JSP program to implement all the attributes of page directive tag.

index.html
<html><head><title>TODO supply a title</title></head>
<body>
<h2>Read two value to divide</h2>
<form action="dividePage.jsp">
Enter First Value: <input type="text" name="val1"/><br><br>
Enter Second Value: <input type="text" name="val2"/><br><br>
<input type="submit" value="Calculate"/>
</form>
</body>
</html>

dividePage.jsp

<%@page import ="java.util.Date"


contentType="application/msword"
pageEncoding="UTF-8"
session="true" buffer="16kb"
autoFlush="true"
isThreadSafe="false"
isELIgnored="true"
extends="org.apache.jasper.runtime.HttpJspBase"
info="Lab 10: demonstrate all attributes of the page directive"
language="java"
errorPage="receiveError.jsp"%>

<html><head><title>JSP Page</title></head>

<%! int a, b;
Date d=new Date();%>
<body>
<h2>Welcome! Today is <%= d.getDate()%></h2>
<%
String str1=request.getParameter("val1");
String str2=request.getParameter("val2");
a=Integer.parseInt(str1);
b=Integer.parseInt(str2);
%>
<h2>Using Expression Language</h2>
A= ${param.val1} <br>
B= ${param.val2} <br>
<h3>Result: <%= a/b %> </h3>
</body>
</html>

By Suma M G, Dept. of MCA, RNSIT 13


16MCA46 Advance Java Programming Laboratory

receiveError.jsp

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


isErrorPage="true"%>
<html><head><title>JSP Page</title></head>
<body>
<%
String str1=request.getParameter("val1");
String str2=request.getParameter("val2");
if(str1.equals("")||str2.equals("")){ %>
<h3> Please enter the values properly </h3>
<jsp:include page="index.html"/>
<% } else { %>
<h3>Sorry an exception occured!</h3>
<h2>The exception is: <%= exception %> </h2>
<% } %>
</body>
</html>

By Suma M G, Dept. of MCA, RNSIT 14


16MCA46 Advance Java Programming Laboratory
10. Write a JAVA Program to insert data into Student DATA BASE and retrieve info based on
particular queries(For example update, delete, search etc…).

StudentInfo.java

package lab9;

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

public class StudentInfo {


Connection con;
public void establishConnection(){
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3309
/studentdb", "root", "rnsit");
}
catch(Exception e){
System.err.println("Connection failed" +e);
}
}

public void sInsert(String usn, String name, String dept)


throws ClassNotFoundException, SQLException{

PreparedStatement pst=null;
establishConnection();
try {
if(con!=null){
pst=con.prepareStatement("insert into student
values(?,?,?)");
pst.setString(1, usn); pst.setString(2,name);
pst.setString(3,dept);
int i=pst.executeUpdate();
if(i==1){
System.out.println("Record inserted successfully");
}
}
catch(SQLException e){
System.err.println(e.getMessage());
}
finally {
pst.close(); con.close();
}
}

By Suma M G, Dept. of MCA, RNSIT 15


16MCA46 Advance Java Programming Laboratory

StudentInfo.java(continued)

public void sSelect(String usn)throws ClassNotFoundException,


SQLException{
PreparedStatement pst=null; ResultSet res;
establishConnection();
try{
if(con!=null){
pst=con.prepareStatement("select * from student where usn=?");
pst.setString(1, usn);
res=pst.executeQuery();

if(res.next()){
System.out.println("USN= "+res.getString(1)
+"\tName="+ res.getString(2)
+ "\tDepartment= "+res.getString(3));
}
}
}
catch(SQLException e){
System.err.println(e.getMessage());
}
finally{
pst.close();
con.close();
}
}

public void sUpdate(String usn, String name, String dept)


throws ClassNotFoundException, SQLException{
PreparedStatement pst=null;
establishConnection();
try{
if(con!=null){
pst=con.prepareStatement("update student set name=?, dept=?
where usn=?");
pst.setString(1, name);
pst.setString(2,dept);
pst.setString(3,usn);
int i=pst.executeUpdate();
if(i==1)
System.out.println("Record updated successfully");
else
System.out.println("No such record");
}
}
catch(SQLException e){System.err.println(e.getMessage()); }
finally{ pst.close(); con.close(); }
}

By Suma M G, Dept. of MCA, RNSIT 16


16MCA46 Advance Java Programming Laboratory

StudentInfo.java(continued)

public void sDelete(String usn)throws ClassNotFoundException,


SQLException{

PreparedStatement pst=null;
establishConnection();
try{
if(con!=null){
pst=con.prepareStatement("delete from student where usn=?");
pst.setString(1, usn);
int i=pst.executeUpdate();
if(i==1)
System.out.println("Record deleted successfully");
else
System.out.println("No such record");
}
}
catch(SQLException e){
System.err.println(e.getMessage());
}
finally{
pst.close();
con.close();
}
}

public void viewAll( )throws ClassNotFoundException,


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

By Suma M G, Dept. of MCA, RNSIT 17


16MCA46 Advance Java Programming Laboratory

StudentInfo.java(continued)

public static void main(String[] args)throws


ClassNotFoundException, SQLException {
StudentInfo std=new StudentInfo();

String usn,name,dept;
Scanner sc=new Scanner(System.in);

while(true){
System.out.println("Operations on Student table");
System.out.println("1.Insert\n2.Select\n3.Update\n 4.Delete\n
5.View All\n6.Exit");
System.out.println("select the operation");
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 Deapartment to insert");
dept=sc.next();
std.sInsert(usn, name, dept);
break;
case 2: System.out.println("Enter USN to select");
usn=sc.next();
std.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 department to update");
dept=sc.next();
std.sUpdate(usn, name, dept);
break;
case 4: System.out.println("Enter USN to delete");
usn=sc.next();
std.sDelete(usn);
break;
case 5: std.viewAll();
break;
case 6: System.exit(0);
default: System.out.println("Invalid operation");
break;
}
}
}
}

By Suma M G, Dept. of MCA, RNSIT 18


16MCA46 Advance Java Programming Laboratory
11. An EJB application that demonstrates Session Bean (with appropriate business logic).

NewSessionBeanLocal.java (SessionBean)

package lab11;

import javax.ejb.Local;

@Local
public interface NewSessionBeanLocal {

double FindSquare(double num);

NewSessionBean.java (SessionBean)

package lab11;

import javax.ejb.Stateless;

@Stateless
public class NewSessionBean implements NewSessionBeanLocal {

@Override
public double FindSquare(double num) {
return (num*num);
}
}

index.html

<!DOCTYPE html>
<html>
<body>
<form action="Lab11">
<input type="text" name="val"/>
<input type="submit"/>
</form>
</body>
</html>

By Suma M G, Dept. of MCA, RNSIT 19


16MCA46 Advance Java Programming Laboratory

Lab11.java (Servlet)

package lab11;

import java.io.*;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class Lab11 extends HttpServlet {

@EJB
private NewSessionBeanLocal newSessionBean;

@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException,
IOException {

response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {

out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Lab11</title>");
out.println("</head>");
out.println("<body>");

double input, output;


input = Double.parseDouble(request.getParameter("val"));
output = newSessionBean.FindSquare(input);
out.println(" Result =" + output);

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

By Suma M G, Dept. of MCA, RNSIT 20


16MCA46 Advance Java Programming Laboratory

12. An EJB application that demonstrates MDB (with appropriate business logic).

MBean.java (Message Driven Bean)

package MSG;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.*;
import javax.jms.MessageListener;

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


@ActivationConfigProperty(propertyName = "destinationType",
propertyValue = "javax.jms.Queue")
})
public class MBean implements MessageListener {
public MBean() {
}

@Override
public void onMessage(Message message) {
TextMessage tmsg=null;
tmsg=(TextMessage)message;
try {
System.out.println(“Message is: ” + tmsg.getText());
}
catch (JMSException ex) {
Logger.getLogger(MBean.class.getName()).log(Level.SEVERE,
null, ex);
}
}
}

index.jsp

<!DOCTYPE html>
<html>
<body>
<form action="MServlet">
Enter Message:<input type="text" name="msg" size="80"></br>
<input type="submit" value="Send Message" />
</form>
</body>
</html>

By Suma M G, Dept. of MCA, RNSIT 21


16MCA46 Advance Java Programming Laboratory

MServlet.java(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;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class MServlet extends HttpServlet {

@Resource(mappedName = "jms/dm")
private Queue dm;
@Resource(mappedName = "jms/ queue1")
private ConnectionFactory queue1;

@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException{

response.setContentType("text/html;charset=UTF-8");
String str=request.getParameter("msg");
try {
sendJMSMessageToDm(str);
}
catch (JMSException ex) {
Logger.getLogger(MServlet.class.getName()).log(Level.SEVERE,
null, ex);
}
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet MServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Check your Server log!! </h1>");
out.println("</body>");
out.println("</html>");
}
}
By Suma M G, Dept. of MCA, RNSIT 22
16MCA46 Advance Java Programming Laboratory

MServlet.java(Servlet) continued

private Message createJMSMessageForjmsDm(Session session,


Object messageData) throws JMSException {
// TODO create and populate message to send
TextMessage tm = session.createTextMessage();
tm.setText(messageData.toString());
return tm;
}

private void sendJMSMessageToDm(Object messageData)


throws JMSException {
Connection connection = null;
Session session = null;
try {
connection = queue1.createConnection();
session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer =
session.createProducer(dm);
messageProducer.send(createJMSMessageForjmsDm(session,
messageData));
} finally {
if (session != null) {
try {
session.close();
}
catch (JMSException e) {
Logger.getLogger(this.getClass().getName()).
log(Level.WARNING, "Cannot close session", e);
}
}
if (connection != null) {
connection.close();
}
}
}
}

By Suma M G, Dept. of MCA, RNSIT 23


16MCA46 Advance Java Programming Laboratory

13. An EJB application that demonstrates persistence (with appropriate business logic).

BookEB java(Entity Bean)

package Book;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class BookEB implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int price;

public Long getId() {


return id;
}
public void setId(Long id) {
this.id = id;
}

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

@Override
public boolean equals(Object object) {
if (!(object instanceof BookEB)) {
return false;
}
BookEB other = (BookEB) 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 "Book.BookEB[ id=" + id + " ]";
}

By Suma M G, Dept. of MCA, RNSIT 24


16MCA46 Advance Java Programming Laboratory

BookEB java(Entity Bean) Continued

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getPrice() {


return price;
}

public void setPrice(int price) {


this.price = price;
}
}

AbstractFacade.java

package Book;
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().persist(entity);
}

public void edit(T entity) {


getEntityManager().merge(entity);
}

public void remove(T entity) {


getEntityManager().remove(getEntityManager().merge(entity));
}

public T find(Object id) {


return getEntityManager().find(entityClass, id);
}

By Suma M G, Dept. of MCA, RNSIT 25


16MCA46 Advance Java Programming Laboratory

AbstractFacade.java(Continued)

public List<T> findAll() {


javax.persistence.criteria.CriteriaQuery cq =
getEntityManager().getCriteriaBuilder().createQuery();

cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}

public List<T> findRange(int[] range) {


javax.persistence.criteria.CriteriaQuery cq =
getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0] + 1);
q.setFirstResult(range[0]);
return q.getResultList();
}

public int count() {


javax.persistence.criteria.CriteriaQuery cq =
getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}

BookEBFacadeLocal.java(Session Bean for Entity)

package Book;
import java.util.List;
import javax.ejb.Local;

@Local
public interface BookEBFacadeLocal {
void create(BookEB bookEB);
void edit(BookEB bookEB);
void remove(BookEB bookEB);
BookEB find(Object id);
List<BookEB> findAll();
List<BookEB> findRange(int[] range);
int count();
}

By Suma M G, Dept. of MCA, RNSIT 26


16MCA46 Advance Java Programming Laboratory

BookEBFacade.java(Session Bean for Entity)

package Book;

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

@Stateless
public class BookEBFacade extends AbstractFacade<BookEB> implements
BookEBFacadeLocal {

@PersistenceContext(unitName = "Lab13-EB-ejbPU")
private EntityManager em;

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

public BookEBFacade() {
super(BookEB.class);
}

index.jsp

<!DOCTYPE html>
<html>
<head><title>JSP Page</title></head>
<body>
<form action="BookServlet">
Enter Text: <input type="text" name="text"/>
Enter Price: <input type="text" name="price"/>
<input type="submit" value="Click Here"/>
</form>
</body>
</html>

By Suma M G, Dept. of MCA, RNSIT 27


16MCA46 Advance Java Programming Laboratory

BookServlet.java(Servlet)

import Book.BookEB;
import Book.BookEBFacadeLocal;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BookServlet extends HttpServlet {


@EJB
private BookEBFacadeLocal bookEBFacade;

protected void doGet(HttpServletRequest request,


HttpServletResponse response)throws
ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {

String tname=request.getParameter("text");
int pr=Integer.parseInt(request.getParameter("price"));

BookEB obj=new BookEB();


obj.setName(tname);
obj.setPrice(pr);

bookEBFacade.create(obj);

out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet BookServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Table Created and Data Inserted</h1>");
out.println("</body>");
out.println("</html>");
}
}
}

Note: Write only highlighted lines from lab-11, lab-12, and lab-13 programs in the lab exam.

By Suma M G, Dept. of MCA, RNSIT 28

You might also like