Wednesday, 28 March 2018

JSP to print Fibonacci Series


Write a jsp program to print range of  Fibonacci Series


i)index.html

<%@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>
        <h1>Enter the Limit of Fibonacci Series</h1>
        <form action="fibo.jsp">
            Enter the Number:<input type="text" name="n1"/><br/>
            <input type="submit" value="Enter"/>         
        </form>
    </body>
</html>

ii) fibo.jsp

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>The Value of Fibonacci Series</h1>
        <h1>
        <%
            String s=request.getParameter("n1");
            int n=Integer.parseInt(s);
            int i=1,f1=0,f2=1,f3;
            while(i<=n)
            {
              out.println(f1);
              f3=f1+f2;
              f1=f2;
              f2=f3;
              i=i+1; 
            }
        %>
        </h1>
    </body>
</html>

JDBC to Demonstrate PreparedStatement


package javaapplication34;
import java.sql.*;
import java.io.*;

public class JavaApplication34 {

 
public static void main(String args[])throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/empdb12","root","");

PreparedStatement ps=con.prepareStatement("insert into emp values(?,?,?)");

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

do{
System.out.println("enter id:");
int id=Integer.parseInt(br.readLine());
System.out.println("enter name:");
String name=br.readLine();
System.out.println("enter salary:");
float salary=Float.parseFloat(br.readLine());

ps.setInt(1,id);
ps.setString(2,name);
ps.setFloat(3,salary);
int i=ps.executeUpdate();
System.out.println(i+" records affected");

System.out.println("Do you want to continue: y/n");
String s=br.readLine();
if(s.startsWith("n")){
break;
}
}while(true);

con.close();
}}



Monday, 26 March 2018

JSP to Demonstrate atrribute of page directive tag


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


Note: create 3 diffrent jsp file and execute the project

//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>Page Attributes </title>
</head>
<body>
<form action="Directive.jsp">
<h1>Enter the value of n1 and n2: </h1>
           Number1: <input type="number" name="n1"/><br/>
           Number:2<input type="number" name="n2"/><br/>
<input type="submit"/>
</form>
</body>
</html>

//Directive.jsp

<%@ page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.util.*" %>
<%@ page info="composed by CITECH" %>
<%@ page language="java"%>
<%@ page buffer="16kb" %>
<%@ page autoFlush="true" %>
<%@ page isThreadSafe="true" %>
<%@ page errorPage="error.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Page Attributes</title>
</head>
<body bgcolor="orange">
<h2> Usage of Import Attributes </h2>
<h2>Todays Date is: <%=new Date() %></h2>

<h2>To See the use of Error page enter n2 value  zero and click submit  </h2>

<% 
int n1=Integer.parseInt(request.getParameter("n1"));
int n2=Integer.parseInt(request.getParameter("n2"));      
   %>

<h2>Value of n1/n2 ==><%=n1/n2 %></h2>
</body>
</html>

//error.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page isErrorPage="true" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Page Attributes</title>
</head>
<body>
<h2>Value of n2 variable of zero (n/0 is infinity)</h2>
<h3> Sorry an exception occured!</h3><br/>
<h3> The exception is:   <%= exception%></h3>
</body>
</html>

Screen Shot




Sunday, 25 March 2018

jsp program to demonstrate include and farward


Write a JAVA JSP Program which uses jsp: include and jsp: forward action to display a Web page.
jsp:forward action tag with parameter

// index.jsp

<html> 
<body> 
<h2>this is index page</h2> 
 
<jsp:forward page="printdate.jsp " > 
<jsp:param name="name" value="javatpoint.com" /> 
</jsp:forward> 
 
</body> 
</html> 

Printdatejsp
<html> 
<body> 
 
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %> 

<%= request.getParameter("name") %> 
 
</body> 
</html>

jsp:include action tag without parameter

// index.jsp
<h2>this is index page</h2> 
 
<jsp:include page="printdate.jsp" /> 
 
<h2>end section of index page</h2> 

printdate.jsp

<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>



jsp to demonstrate import attribute

Write a JSP Program to demonstrate the import attributes..



//index.jsp
<%@ taglib uri="WEB-INF/tlds/mytags.tld" prefix="m" %> 
Cube of 4 is: <m:cube number="4"></m:cube> 

//CubeNumber.java
package reva; 
import javax.servlet.jsp.JspException; 
import javax.servlet.jsp.JspWriter; 
import javax.servlet.jsp.tagext.TagSupport; 
 
public class CubeNumber extends TagSupport{ 
private int number; 
     
public void setNumber(int number) { 
    this.number = number; 
} 
 
public int doStartTag() throws JspException { 
    JspWriter out=pageContext.getOut(); 
    try{ 
        out.print(number*number*number); 
    }catch(Exception e){e.printStackTrace();} 
      
    return SKIP_BODY;  } 
} 

//mytags.tld

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd">
  <tlib-version>1.0</tlib-version>
  <short-name>mytags</short-name>
  <uri>/WEB-INF/tlds/mytags</uri>
   <description>A simple tab library for the examples</description> 
 
  <tag> 

    <name>cube</name> 
    <tag-class>reva.CubeNumber</tag-class> 
    <attribute> 
    <name>number</name> 
    <required>true</required> 
    </attribute> 
  </tag> 
</taglib>

output


jsp program to display login page


 Write a JAVA JSP Program to implement verification of a particular user login and display a welcome page.

Index.html
<html>
   <head>
        <title>JSP Page</title>
    </head>
    <body>
    <form method="post" action="lab5a.jsp" >
        <h1>
       User name <input type="text" name="uname" />
       <br>
       Password  <input type="password" name="pwd" />
       <input type="submit" value="Login"  />
        </h1>
    </form>
    </body>
</html>

lab5a

<html>
    <head>
        <title>JSP Page</title>
    </head>
    <body>
        <%
            String u=request.getParameter("uname");
            String p=request.getParameter("pwd");
            if ((u.equals("admin"))&& (p.equals("rose")))
                      out.println("Welcome "+u+" you are authenticated");
              else
                      out.println("Failed Login Attempt");
        %>
        </body>
</html>



Servlet Program to demonstrate get and post



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

// index.html

<html>
 <body>
    <form method="post" action="servlet3" >
     User name <input type="text" name="uname" />
     Password  <input type="password" name="pwd" />
     <input type="submit" value="Login" />
    </form>
 </body>
</html>

-------------------------------------------------------------------------
// servlet3

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

public class servlet3 extends HttpServlet
{
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
                response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String u=request.getParameter("uname");
            String p=request.getParameter("pwd");
        String valid=null;
        if((u.equals("admin")) && (p.equals("rose")))
           valid="Successful";
        else
               valid="Unsuccessful";
            out.println("<html>");
            out.println("<body>");
            out.println("<h1> Your authentication is "+valid+"</h1>");
            out.println("</body></html>");
    }



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


Servlet program to Auto Web Page Refresh


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

Index.html
<%@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 method="post" action="Refresh" >
        <input type="submit" value="Login" />
    </body>
</html>

Refresh.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
 // Extend HttpServlet class public class Refresh extends HttpServlet
{
   // Method to handle GET method request.
  public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
  {
      // Set refresh, autoload time as 5 seconds
      response.setIntHeader("Refresh", 5);

      // Set response content type
      response.setContentType("text/html");

      // Get current time
      Calendar calendar = new GregorianCalendar();
      String am_pm;
      int hour = calendar.get(Calendar.HOUR);
      int minute = calendar.get(Calendar.MINUTE);
      int second = calendar.get(Calendar.SECOND);
      if(calendar.get(Calendar.AM_PM) == 0)
        am_pm = "AM";
      else
        am_pm = "PM";
       String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
          PrintWriter out = response.getWriter();
      String title = "Auto Page Refresh using Servlet";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
        "<html>\n" +
        "<head><title>" + title + "</title></head>\n"+
        "<body bgcolor=\"#f0f0f0\">\n" +
        "<h1 align=\"center\">" + title + "</h1>\n" +
        "<p>Current Time is: " + CT + "</p>\n");
  }
  // Method to handle POST method request.
  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
     doGet(request, response);
  }
}
OUTPUT:



Entity bean Demonstration


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

Step 1: Creation of Project Application
1.      File -> New Project -> Java EE -> Enterprise Application -> click next -> Give name for project (ex: employee -> set Java EE version as Java EE 5 -> Finish.
2.      At the end of creation you can see three modules generated.
Step 2: Creation of Entity Bean
1.      Right click on projects ejb module -> new -> Entity class -> Give class name and package -> click next -> Select data source with your database -> Finish.
2.      Change AUTO to IDENTITY and add the following code
String name;
int salary;
3.      Select the variables -> right click over the selection -> insert code -> Getter and Setter… -> select all -> Generate. You can see getter and setter method generated.
Step 3: Creation of Session bean for Entity Class
1.      Right click on projects ejb module -> new -> Other -> Enterprise Java beans -> Session bean for entity classes -> click Add all -> click next -> select local.
Step 4: Creating Servlet file
1.      Right click on project war module -> new -> servlet -> Give name for servlet and package -> next -> finish.
2.      Inside the class definition -> Right click -> Insert code -> call enterprise bean -> select your entity class( ex: EmployeeFacade) -> click ok.
3.      Inside processRequest method add the following code,
employee dan=new employee();
dan.setName(request.getParameter("name"));
dan.setSalary(Integer.parseInt(request.getParameter("salary")));
empFacade.create(dan);
4.      Left click on the error of first line code -> Add import (for your entity class).
Step 5: Creating jsp file
1.      Change the code in index.jsp with your code.
2.      Your code should produce two label and 2 text boxes and make sure that mapping servlet with jsp file done correctly.
Step 6: Executing the project
1.      Right click on Application module -> Clean and bulid -> Right click on Application module -> Deploy.
2.      Under services window -> right click on glassfish server -> start the server ->  right click on glassfish server ->  view admin console   -> Applications -> click on entity bean class name -> Launch -> click on first link -> Enter data and submit->
3.      You can see the data on database by -> right click on your database -> refresh -> expand your table -> view data.


//prog13:An EJB application that demonstrates Entity Bean (persistence).
//employee.java in prog13-ejb
package eb;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class employee implements Serializable {
private static final long serialVersionUID = 1L;
    @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
    String name;
int salary;

public String getName() {
return name;
    }
public void setName(String name) {
        this.name = name;
    }
public int getSalary() {
return salary;
    }
public void setSalary(int salary) {
        this.salary = salary;
    }
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) {
        // TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof employee)) {
return false;
        }
employee other = (employee) 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 "eb.employee[ id=" + id + " ]";
    }   
}

//AbstractFacade.java in prog13-ejb
package eb;
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);
    }
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuerycq = 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]);
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();
    }   
}


//employeeFacade.java in prog13-ejb
package eb;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Stateless
public class employeeFacade extends AbstractFacade<employee> implements employeeFacadeLocal {
@PersistenceContext(unitName = "prog13-ejbPU")
private EntityManager em;
protected EntityManager getEntityManager() {
return em;
    }

public employeeFacade() {
super(employee.class);
    }   
}
//employeeFacadeLocal.java in prog13-ejb
package eb;
import java.util.List;
import javax.ejb.Local;
@Local
public interface employeeFacadeLocal {
void create(employee employee);
void edit(employee employee);
void remove(employee employee);
employee find(Object id);
    List<employee>findAll();
    List<employee>findRange(int[] range);
int count();   
}

//index.jsp in prog13-war
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Employee Detail</title>
</head>
<body bgcolor="orange">
<form action="emp" method="get">
<h1> Servlet EJB Session Entity Bean </h1>
Employee Name: <input type="textbox" size="12" name="name"/><br/>
Employee Salary: <input type="textbox" size="5" name="salary"/><br/>
<input type="submit" name="submit" value="submit"/>
<input type="reset" name="clear" value="clear">
</form>
</body>
</html>
//emp.java in prog13-war
package p13;
import eb.employee;
import eb.employeeFacadeLocal;
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 emp extends HttpServlet {
    @EJB
private employeeFacadeLocal employeeFacade;    
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
employee dan=new employee();
dan.setName(request.getParameter("name"));
dan.setSalary(Integer.parseInt(request.getParameter("salary")));
employeeFacade.create(dan);
response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
try {           
        } finally {           
out.close();
        }
    }   
    @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
    }



    @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
    }
    @Override
public String getServletInfo() {
return "Short description";
    }

}

PUBLISHER & SUBSCRIBER PATTERN

Using the UML Drawing Tool by implementing the code in Java demonstrate the Observer  Design Pattern. The Publisher-Subscriber desig...