Friday, June 21, 2019

Request Dispatcher Servlet example in creating simple Login Form


Use Request Dispatcher Servlet in creating simple Login Form


We are going to create a Login Form Here. At the end of this section, you will be able to use Request Dispatcher Servlet to forward the request to another webpage based on your inputs.


Let us Start Step by Step:

Step 1: 


Create a Dynamic Web Project in IDE. For Example, here I am using eclipse to create a Dynamic Web Project.

If you do not have eclipse use below link to download the eclipse for Enterprise Edition.:
https://www.eclipse.org/downloads/packages/release/kepler/sr2/eclipse-ide-java-ee-developers






Give Proper Name to your project according to you.

Here in the Target runtime (Picture below), you can see Apache Tomcat v8.5. It is Server which is required to run Dynamic Web Applications or Enterprise Applications.


If it is not present or shown Empty then you have to Download the Server
i.e Apache Tomcat or Weblogic or any other server and have to link in the New RunTime Button Link.





Next Click on Next and Finish.


Below is the Final Structure of the project.





You need to create below files:


1. Login and Success Servlet Class.


2. home and success.jsp for the login page and if credentials are correct then forward it to the success page.



Step 2:


Create home.jsp file under webContent.








Content of home.jsp file.

It contains the code for Simple Login Form.

<form action="Login" method="post">

Here action means when user submit this form then Login Servlet will be invoked and it find the post method in the Login Servlet


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
      pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

      <h1>Login form</h1>
      <div>
            <form action="Login" method="post">
                  <table>
                        <tr>
                              <td>Name :</td>
                 <td><input type="text" name="userName" />                                  </td>
                        </tr>
                        <tr>
                              <td>Password :</td>
                <td><input type="password" name="userPass"/></td>
                        </tr>
                        <tr>
                 <td><input type="submit" value="login" /></td>
                        </tr>
                  </table>
            </form>
      </div>

</body>

</html>

home.jsp file snapshot





Step 3:


Create Login.java Servlet











Login Servlet:


package com.studyskymate.dinesh.servlet.login;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
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("/Login")
public class Login extends HttpServlet {
      private static final long serialVersionUID = 1L;
      
    public Login() {
        super();
    }

      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           
             response.setContentType("text/html"); 
             PrintWriter out = response.getWriter(); 
             String name=request.getParameter("userName"); 
             String password=request.getParameter("userPass"); 
             
       if(name.equals("dinesh") && password.contentEquals("1234") )               {
        RequestDispatcher rd  =request.getRequestDispatcher("success");

    //To handle it you need to create success servlet which we will create in next step
         rd.forward(request, response);
        }else {
       out.print("Sorry Invalid UserName or Password !");
       RequestDispatcher rd=request.getRequestDispatcher("/home.jsp");
           rd.include(request, response);
             }
             
      }


}


----------------------------------------------------------------------------------------------------------

Step 4
Create Success.java Servlet Similarly:

It will Invoke Login Servlet and if username and password are correct then it will forward the request to Success.jsp

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
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("/success")
public class Success extends HttpServlet {
      private static final long serialVersionUID = 1L;

    public Success() {
        super();
    }


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

          response.setContentType("text/html");
          PrintWriter out= response.getWriter();
      RequestDispatcher rd=request.getRequestDispatcher("/success.jsp");
          rd.forward(request, response);
      }


}

-----------------------------------------------------------------------------------------------------------------


Step 5.

Create success.jsp to capture the response from Success Servlet.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<div>
<h1>Welcome   <font color="red"><%=request.getParameter("userName") %> </font> </h1>
<h2>You are Valid User</h2>
<a href="/WebProject/home.jsp"><button type="button">Home Page</button></a>
</div>

</body>
</html>


----------------------------------------------------------------------


Step 6

web.xml file.

6.1 create web.xml file under WEB-INF folder if not present.
6.2 Add welcome file home.jsp or your index file statement in the web.xml
as below:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>WebProject</display-name>
  <welcome-file-list>
    <welcome-file>home.jsp</welcome-file>
  </welcome-file-list>
</web-app>


--------------------------------------------------------------------


Step 7: 
Run your project on Server.










Below Login Form will open after running the server at your browser.






Enter the correct Username and password.
In my case, it is dinesh and 1234 because I have provided these validations in Login Servet.
Now It will Invoke Login Servlet and if username and password is correct then it will forward the request to Successjsp






In the case of Wrong credentials, it will include the output of login servlet and forward the request to home.jsp




Thanks



Tuesday, June 18, 2019

What is RMI? Remote Method Invocation

Remote Method Invocation (RMI):

RMI allows a developer to abstract away where objects physically reside from his application.


Object-oriented applications can be transparently spread across multiple machines. Objects that do heavy processing or provide server-side functionality, such as mail services, transactional database services, or file. serving services can be located on server-class machines.


Typical desktop client applications can then access these objects as if they were local and part of the same object-oriented application.

Location independent objects are powerful because they can be dynamically moved around from machine to machine.

If mail services’ objects on a server become too bogged down, they can be spread across multiple machines, all transparently to the client applications using them.


Java’s platform independence adds even more value to its location-independent objects.
Server objects could reside on a Unix-based operating system for example and client objects on a Microsoft Windows platform.



RMI -- Remote Method Invocation


The Remote Method Invocation (RMI) is an API that provides a mechanism to create a distributed application in java.


RMI is the Java platform for remote procedure calls.

RMI calls can happen over a network, and b/w two separate processes.

There is a client and a server program running on a separate machine ( or two separate processes on the same machine).
The client program calls a  procedure(method) on the server and waits until the server returns the method result. Thus the RMI allows an object to invoke methods on an object running in another JVM.



Core RMI principles


In order to call methods on a remote object, three main steps occur:


1. A reference to the remote object must be obtained. 


The remote object must be looked up on the remote server.

2. Marshalling and unmarshalling of parameters.

When a method is invoked on the remote reference, the parameters must be marshaled into a byte stream that can be sent over the network. On the server side, these parameters must be unmarshaled from the byte stream into their original values and then passed to the appropriate method.


3. Transmission of data through a common protocol.

There must be a protocol defined for the transport and delivery of these method calls and returns. A standard format for parameters is necessary, along with standards to tell the server which method on which object is to be invoked.







Understanding Stub and Skelton


RMI uses stub and skeleton object for communication with the remote object.

 Remote Object

A remote object is an object whose method can be invoked from another JVM.


Let's understand the stub and skeleton objects:


To make the remote call appear like a local call, a local implementation exists with the same interface (all RMI objects must be defined as Java interfaces). This local implementation is called a stub and is essentially a proxy to the real implementation. Whenever a method is called on this local implementation or stub, the local implementation performs the operations necessary to send the method call to a remote implementation of the same interface on another server.
The stub marshals the parameters and sends them over the network using a common RMI protocol.

In turn, a stub on the server side implementing the same interface unmarshals the parameters and then passes them on to the actual remote object in a normal method call. This process is reversed for the return value; the stub on the server side marshals and sends it, and the stub on the client unmarshals and returns it to the original caller.


Stub


The stub is an object, acts as a proxy to the real implementation for the client side. All the outgoing requests are routed through it. It resides at the client side and represents the remote object. When the caller invokes a method on the stub object, it does the following tasks:


  1. It initiates a connection with remote Virtual Machine (JVM),
  2. It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
  3. It waits for the result
  4. It reads (unmarshals) the return value or exception, and
  5. It finally, returns the value to the caller.


Skeleton


The skeleton is an object, acts as a gateway for the server side object. All the incoming requests are routed through it. When the skeleton receives the incoming request, it does the following tasks:


  • It reads the parameter for the remote method
  • It invokes the method on the actual remote object, and
  • It writes and transmits (marshals) the result to the caller.


Note:  In the Java 2 SDK, a stub protocol was introduced that eliminates the need for skeletons.



Marshaling and Unmarshalling



The parameters and method call must be flattened into a byte stream before they can be sent over the network. This process is called marshaling.


The reverse is called unmarshalling when the byte stream is decoded into the original parameters and method call information.


 After unmarshalling the parameters and method call, the server dispatches the method call to the appropriate object that actually implements the remote method and then marshals the return value back to the client. 
By serializing the parameters and method into a byte stream,


RMI parameter passing


It can work on top of network protocols that provide a reliable byte stream, such as TCP/IP.


In RMI, two types of objects besides primitives can be passed as parameters:


  1. objects that implement the java.rmi.Remote interface or
  2. objects that implement the java.io.Serializable interface.


These two interfaces do not contain any methods, instead, they mark objects with a particular property.


Java’s RMI mechanism knows that Remote objects could be on another virtual machine, and will have stubs.

Objects that implement Serializable, on the other hand, can be transformed into a byte stream (to save to disk, or in RMI’s case, to send over a network). 


In RMI, objects that implement Remote are passed by reference, whereas objects that implement Serializable (and not Remote) are passed by value.
 When parameters are marshaled over the network and transformed into a byte stream, any object that must be passed via an RMI call must be Serializable. So now for the first time, objects in Java can
be passed by value.

Remote objects are passed by reference and Serializable objects are passed by value.


This helps reduce the number of network calls that must occur. 

If an object being passed contains a large number of properties that must be accessed through getXXX methods, there would be a large number of network calls taking place.

By serializing the object, all these calls become local calls on the remote server and use up far less network bandwidth.

Method calls on Remote objects passed in, on the other hand, will go over the network and must be taken into consideration.


Protocols


RMI is implemented such that it can support more than one underlying transport protocol (though obviously only one protocol can be used between any two objects).


There are two main choices as the transport  protocol for RMI:


  • Java Remote Method Protocol (JRMP)

  • JRMP is the default protocol for RMI.

  • Internet InterORB Protocol (IIOP)

  • IIOP offers compatibility with CORBA,

IIOP, because it was not designed specifically for Java remote procedure calls, does not support some of the features JRMP supports, such as security and distributed garbage collection.


Using IIOP as the underlying protocol for RMI makes it easy to integrate legacy objects written in other languages,   IIOP stubs differ from JRMP stubs and must be generated separately.



RMI Registry



Object instances must be made available in a registry on the server before they can be used by remote clients.


Clients obtain an instance by looking up a particular name —for example, the string “EmployeeData” might refer to a class containing the data for the employees of a particular company.


When a server is starting up, it creates instances of the objects it wishes to be available, and registers them in a registry. Because these objects are globally available, they must be thread-safe (because their methods can be called at the same time by
different threads).


The code to look up a particular instance of a class is not very difficult, and uses the Java Naming and Directory Interface (JNDI) API (found in javax.naming). Asmall snippet of code to look up an object on a remote server follows:

import javax.naming.InitialContext;
...
InitialContext ctx = new InitialContext();
EmployeeData data = (EmployeeData) ctx.lookup(“CompanyX\\MyEmployeeDataInstance”);



JNDI is configured by setting certain Java system properties to tell it the location and protocol of the registry.



This is how objects can be transparently remote or local. If the registry is configured locally, in the same JVM, then all calls to data will be local.


If data is an instance on a remote server, all calls will go through RMI, using whatever protocol was specified.



Binding and lookup -- API



Now rmi services need to be hosted in a server process.
The Naming class provides methods to get and store the remote object.
The Naming class provides 5 methods.


public static java.rmi.Remote lookup(java.lang.String) throws java.rmi.NotBoundException, java.net.MalformedURLException, java.rmi.RemoteException; it returns the reference of the remote object.

public static void bind(java.lang.String, java.rmi.Remote) throws java.rmi.AlreadyBoundException, java.net.MalformedURLException, java.rmi.RemoteException; it binds the remote object with the given name.

public static void unbind(java.lang.String) throws java.rmi.RemoteException, java.rmi.NotBoundException, java.net.MalformedURLException; it destroys the remote object which is bound with the given name.

public static void rebind(java.lang.String, java.rmi.Remote) throws java.rmi.RemoteException, java.net.MalformedURLException; it binds the remote object to the new name.

public static java.lang.String[] list(java.lang.String) throws java.rmi.RemoteException, java.net.MalformedURLException; it returns an array of the names of the remote objects bound in the registry.





Steps to writing the RMI program





The is given the 6 steps to write the RMI program.


1. Create the remote interface

2. Provide the implementation of the remote interface

3. Compile the implementation class and create the stub and skeleton objects using the rmic tool

4. Start the registry service by rmiregistry tool

5. Create and start the remote application

6. Create and start the client application



Example


Step - 1: create a remote interface "CalRemote"



import java.rmi.*;

public interface CalRemote extends Remote
{
public int sum(int a,int b) throws RemoteException;
}


It contains the method provided for the clients.
Clients will have a copy of this interface to interact with RemoteObject


Step - 2 : create a RemoteObject class - CalRemoteImpl.java



import java.rmi.*;
import java.rmi.server.*;
public class  CalRemoteImpl extends UnicastRemoteObject implements CalRemote
{
public CalRemoteImpl()throws RemoteException
{}

public int sum(int a,int b) throws RemoteException
{
return (a+b);
}
}
}



Step - 3 : create a Server class -- ServerDemo.java



import java.rmi.*;

class ServerDemo
{
public static void main(String s[])
{
try
{
CalRemoteImpl server=new CalRemoteImpl();

Naming.rebind("calculator",server);

System.out.println("Server is up....");
}
catch(Exception e)
{
System.out.println("error in running Server "+e);
}


}
}


Step - 4 : create a client class -- RmiClient.java


 import java.rmi.*;

public class  RmiClient
{

public static void main(String s[])
{
try
{
CalRemote rm = (CalRemote)Naming.lookup("rmi://127.0.0.1/calculator");


int rs=rm.sum(4,5);
System.out.println("result : "+rs);
}
catch(Exception e)
{
System.out.println("error in looking Server"+e);
}

}



}


For running this rmi example,


1) compile all the java files


javac *.java

2)create stub and skeleton object by rmic tool


rmic CalRemoteImpl

3) start rmi registry in one command prompt


start rmiregistry 5000
it will bind the port number 5000 for rmi services.


4)start the server in another command prompt


java  ServerDemo

5)start the client application in another command prompt


java RmiClient

Saturday, June 15, 2019

What is Java

Welcome to the world of Java Programming

What is Java?

Java is programming language and platform first released in 1995.


Java is one of the most widely used and robust programmings language. You can find it everywhere. Let us start our journey with JAVA.


This section describes Java. There is an interesting History behind the evolution of Java language. Be with us. You are entering in a beautiful world of programming.




   This is the First Example of Java. Just to show you the Simple class structure of Java.
    This class is just printing Hello World.


 These are the different application of Java.
 You can see here that Java is in every area. 
 So You can understand its importance better.



    Below are different applications of java. Java is used to build different kinds of applications.
    Each of the below applications described in the subsequent sections.


     Have you seen some Java Desktop Applications?.
     For Example, you make some simple calculator in java and run in your desktop.
     Desktop applications do not require browser help.


  Web Applications running on the server. For Example the HSBC, HDFC bank site.
 


 



  These are different Java platforms according to the users need.
For Example below link will take you to download the Java Standard Edition JDK 8.
https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html



   Now Each one of the editions Described with the help of examples.

Here Java SE contains the core java libraries.You can say these are the core Java libraries.



    After the core Java, you need to build Web Applications. For this you need Java EE which includes JSP,Servlet etc. By using these you can create best applications.



   Thank you for being with us. Visit for other sections of Java also.





Tuesday, June 11, 2019

JDK,JRE AND JVM

 JDK, JRE and JVM.


JRE and JDK

Oracle provides two principal software products in the Java™ Platform, Standard Edition (Java™ SE) family:

Java SE Runtime Environment (JRE)

The JRE provides the libraries, Java virtual machine, and other components necessary for you to run applets and applications written in the Java programming language. This runtime environment can be redistributed with applications to make them free-standing.

Java SE Development Kit (JDK)

The JDK includes the JRE plus command-line development tools such as compilers and debuggers that are necessary or useful for developing applets and applications.

Java Programming Language

The Java Programming Language is a general-purpose, concurrent, strongly typed, class-based object-oriented language. It is normally compiled to the bytecode instruction set and binary format defined in the Java Virtual Machine Specification. For more information see Language Features.

Java Virtual Machines


The Java virtual machine is an abstract computing machine that has an instruction set and manipulates memory at run time. The Java virtual machine is ported to different platforms to provide hardware- and operating system-independence.
The Java Platform, Standard Edition provides two implementations of the Java virtual machine (VM):

Java HotSpot Client VM

The client VM is an implementation for platforms typically used for client applications. The client VM is tuned for reducing start-up time and memory footprint. It can be invoked by using the -clientcommand-line option when launching an application.

Java HotSpot Server VM

The server VM is an implementation designed for maximum program execution speed, trading off launch time and memory. It can be invoked by using the -server command-line option when launching an application.
For more information, see the VM documentation.

 JDK, JRE and JVM Presentation

Monday, June 10, 2019

Java Program explained each keyword

In this Presentation, we have explained the Java programs each keyword.


How to Set Environment Variables in Java

Set Environment Variables in Java



Windows 10 and Windows 8

  1. In Search, search for and then select: System (Control Panel)
  2. Click the Advanced system settings link.
  3. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New.
  4. In the Edit System Variable (or New System Variable) window, specify the value of the PATHenvironment variable. Click OK. Close all remaining windows by clicking OK.
  5. Reopen Command prompt window, and run your java code.

Presentation:


Java History

History of Java.

Welcome to know about the History of Java.

In this section, you will know about the main faces behind the evolution of Java and Why they named it Java.


Java was started as a project called "Oak" by James Gosling in June 1991.

Gosling's goals were to implement a virtual machine and a language that had a familiar C-like
notation but with greater uniformity and simplicity than C/C++. 
The first public implementation was Java 1.0 in 1995. 
It made the promise of "Write Once, Run Anywhere", with free runtimes on popular platforms. It was fairly secure and its security was configurable, allowing for network and file access to be limited. 


Friday, May 31, 2019

operators in java

Java Operators

Operators

Now that you've learned how to declare and initialize variables, you probably want to know how to do something with them. Learning the operators of the Java programming language is a good place to start. Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result.

As we explore the operators of the Java programming language, it may be helpful for you to know ahead of time which operators have the highest precedence. The operators in the following table are listed according to precedence order. The closer to the top of the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with relatively lower precedence. Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.


Operator Precedence
OperatorsPrecedence
postfixexpr++ expr--
unary++expr --expr +expr -expr ~ !
multiplicative* / %
additive+ -
shift<< >> >>>
relational< > <= >= instanceof
equality== !=
bitwise AND&
bitwise exclusive OR^
bitwise inclusive OR|
logical AND&&
logical OR||
ternary? :
assignment= += -= *= /= %= &= ^= |= <<= >>= >>>=


The Arithmetic Operators

The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. The only symbol that might look new to you is "%", which divides one operand by another and returns the remainder as its result.
OperatorDescription
+Additive operator (also used for String concatenation)
-Subtraction operator
*Multiplication operator
/Division operator
%Remainder operator


The Unary Operators

The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.
OperatorDescription
+Unary plus operator; indicates positive value (numbers are positive without this, however)
-Unary minus operator; negates an expression
++Increment operator; increments a value by 1
--Decrement operator; decrements a value by 1
!Logical complement operator; inverts the value of a boolean



The Equality and Relational Operators

The equality and relational operators determine if one operand is greater than, less than, equal to, or not equal to another operand. The majority of these operators will probably look familiar to you as well. Keep in mind that you must use "==", not "=", when testing if two primitive values are equal.
==      equal to
!=      not equal to
>       greater than
>=      greater than or equal to
<       less than
<=      less than or equal to


The Conditional Operators

The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.
&& Conditional-AND
|| Conditional-OR
The following program, ConditionalDemo1, tests these operators:
class ConditionalDemo1 {

    public static void main(String[] args){
        int value1 = 1;
        int value2 = 2;
        if((value1 == 1) && (value2 == 2))
            System.out.println("value1 is 1 AND value2 is 2");
        if((value1 == 1) || (value2 == 1))
            System.out.println("value1 is 1 OR value2 is 1");
    }
}

Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement (discussed in the Control Flow Statements section of this lesson). This operator is also known as the ternary operator because it uses three operands. In the following example, this operator should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."
The following program, ConditionalDemo2, tests the ?: operator:
class ConditionalDemo2 {

    public static void main(String[] args){
        int value1 = 1;
        int value2 = 2;
        int result;
        boolean someCondition = true;
        result = someCondition ? value1 : value2;

        System.out.println(result);
    }
}

Because someCondition is true, this program prints "1" to the screen. Use the ?: operator instead of an if-then-else statement if it makes your code more readable; for example, when the expressions are compact and without side-effects (such as assignments).












Create a Digital Clock using HTML and JavaScript

Create a Digital Clock using HTML and JavaScript  <! DOCTYPE html> < html > < head > ...

Followers

Search This Blog

Popular Posts