INTRODUCTION TO JAVASERVLET
JSP(JAVA SERVER PAGE) DATA BASE CONNECTION
INTRODUCTION TO JAVA
HISTORY Java is a programming language created by
James Gosling from Sun Microsystems (Sun) in 1991.
Java is a high-level programming language. Its a platform independent.
Java language is called as an Object-Oriented Programming language
WHY JAVA
It’s the current “hot” language It’s almost entirely object-oriented It’s more platform independent It’s more secure
WHERE IT IS USED?Desktop Applications such as acrobat reader,
media player, antivirus etc.Web ApplicationsEnterprise Applications such as banking
applications. Mobile Embedded System Smart Card Robotics Games etc.
JAVA FEATURES
Compiled and Interpreted Platform Independent and portable Object-oriented Robust and secure Distributed Familiar, simple and small Multithreaded and Interactive
PLATFORM INDEPENDENT
OBJECT-ORIENTED PROGRAMMING
DIFFERENT PROGRAMMING PARADIGMS
Functional/procedural programming:• program is a list of instructions to the
computer
Object-oriented programming• program is composed of a collection objects
that communicate with each other
MAIN CONCEPTS
1. Objects.
2. Classes.
3. Data Abstraction.
4. Data Encapsulation.
5. Inheritance.
6. Polymorphism.
JVM
JVM stands for Java Virtual Machine
The Java runtime employs a garbage collection to reclaim the memory occupied by on object.
OS/Hardware
machine codeC source code
myprog.cgcc
myprog.exe
Platform Dependent
JVM
bytecodeJava source code
myprog.javajavac
myprog.class
OS/Hardware
Platform Independent
What is JVM? A specification where working of Java Virtual
Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Sun and other companies.
An implementation Its implementation is known as JRE (Java Runtime Environment).
Runtime Instance Whenever you write java command on the command prompt to run the java class, and instance of JVM is created.
What it does?The JVM performs following operation:
Loads code Verifies code Executes code Provides runtime environment
JVM provides definitions for the: Memory area Class file format Register set Garbage-collected heap Fatal error reporting etc.
Internal Architecture of JVM
JAVA KEYWORDS
Abstract,const,finally,int,public,this,boolean,continue,float
interface,return,throw,break,default,for,long,short,throws
byte,do,goto,native,static,transient,case,double,if,new,strictfp
try,catch,else,implements,package,super,void,char,extends
import,private,switch,volatile,class,final,instanceof,protected
synchronized,while
PRIMITIVE TYPES int 4 bytes short 2 bytes long 8 bytes Byte 1 byte Float 4 bytes double 8 bytes char Unicode encoding (2 bytes) boolean {true, false}
Behaviors is exactly as in C++
Note:Primitive typealways beginwith lower-case
CONTROL STATEMENTSJava control statements cause the flow of
execution to advance and branch based on the changes to the state of the program.
Control statements are divided into three groups: 1) selection statements allow the program to choose different parts of the execution based on the outcome of an expression 2) iteration statements enable program execution to repeat one or more statements 3) jump statements enable your program to execute in a non-linear fashion
FLOW CONTROL
if/else
do/while
for
switch
If(x==4) { // act1} else { // act2}
int i=5;do { // act1 i--;} while(i!=0);
int j;for(int i=0;i<=9;i++) { j+=i;}
char c=IN.getChar();switch(c) { case ‘a’: case ‘b’: // act1 break; default: // act2}
ACCESS CONTROL public member (function/data) • Can be called/modified from outside.
protected• Can be called/modified from derived classes
private• Can be called/modified only from the current
class default ( if no access modifier stated )• Usually referred to as “Friendly”. • Can be called/modified/instantiated from the
same package.
ARRAYS
An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Arrays are:1) declared2) Created
EXAMPLE
Declaration:
double[] myList; Creating Arrays:
double[] myList = new double[10];
↓[Array
Index]
THREAD
Thread is a lightweight process that executes some task.
Java is a multithreaded programming language.Multithreading refers to two or more tasks
executing concurrently within a single program.Every thread in Java is created and controlled by
the java.lang.Thread class.
BENEFITS OF THREADS
Threads are lightweight compared to processes, it takes less time and resource to create a thread.
less expensive.Thread intercommunication is relatively easy
than process communication.
LIFE CYCLE OF A THREAD:
EXCEPTIONS HANDLING
An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following:
• A user has entered invalid data.• A file that needs to be opened
cannot be found.• A network connection has been lost
in the middle of communications or the JVM has run out of memory.
EXCEPTIONS HANDLING (CONT)
Three categories of exceptions:• Checked exceptions• Runtime exceptions• Errors
Exception Handling Keywords• throw• throws• try-catch• finally
Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation.
ABSTRACT WINDOWING TOOLKIT (AWT):
Abstract Windowing Toolkit (AWT) is used for GUI programming in java.
Computer users today expect to interact with their computers using a graphical user interface (GUI).
There are two basic types of GUI program in Java:
• stand-alone applications • applets.
AWT CONTAINER HIERARCHY:
Commonly used Methods of Component class:
1)public void add(Component c)
2)public void setSize(int width , int height)
3)public void setLayout(LayoutManager m)
4)public void setVisible(boolean)
Example:
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout now bydefault BorderLayout
setVisible(true);//now frame willbe visible, bydefault not visible
}
public static void main(String args[]){
First f=new First();
}
}
Output:
SWING COMPONENTS Swing is a collection of libraries that contains
primitive widgets or controls used for designing Graphical User Interfaces (GUIs).
Commonly used classes in javax.swing package:• JButton, JTextBox, JTextArea, JPanel,
JFrame, JMenu, JSlider, JLabel, JIcon, …• There are many, many such classes to do
anything imaginable with GUIs
Each component is a Java class with a fairly extensive inheritency hierarchy:
Using Swing Components Very simple, just create object from appropriate class –
examples:• JButton but = new JButton();• JTextField text = new JTextField();• JTextArea text = new JTextArea();• JLabel lab = new JLabel();
Adding componentsOnce a component is created, it can be added to a container by calling the container’s add method:
• Container cp = getContentPane();
• cp.add(new JButton(“cancel”));
• cp.add(new JButton(“go”));
APPLETApplet is a special type of program that is embedded in
the webpage to generate the dynamic content. It runs inside the browser and works at client side.
Advantage of Applet It works at client side so less response time.Secured It can be executed by browsers running
under many plateforms, including Linux, Windows, Mac Os etc.
Drawback of AppletPlugin is required at client browser to
execute applet.
HIERARCHY OF APPLET
LIFECYCLE OF AN APPLET: Applet is initialized. Applet is started. Applet is painted. Applet is stopped. Applet is destroyed.
public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be used for drawing oval, rectangle, arc etc.
SIMPLE EXAMPLE OF APPLET
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
SERVLET INTRODUCTION
SERVLET Servlet technology is used to create web application.Servlet technology is robust and scalable as it uses the java language. Before Servlet, CGI (Common Gateway Interface) scripting language was used as a server-side programming language. But there were many disadvantages of this technology.
Disadvantages of CGI If number of clients increases, it takes more time for
sending response. For each request, it starts a process and Web server is
limited to start processes. It uses platform dependent language e.g. C, C++, perl.
CGI(Commmon Gateway Interface)
Advantage of Servlet better performance: because it creates a thread for
each request not process. Portability: because it uses java language. Robust: Servlets are managed by JVM so no need
to worry about momory leak, garbage collection etc. Secure: because it uses java language..
Life Cycle of a Servlet (Servlet Life Cycle)The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet:
Servlet class is loaded. Servlet instance is created. init method is invoked. service method is invoked. destroy method is invoked.
Servlet APIThe javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.
Interfaces in javax.servlet package
There are many interfaces in javax.servlet package. They are as follows: Servlet ServletRequest ServletResponse RequestDispatcher ServletConfig ServletContext Filter FilterConfig FilterChain
ServletRequest InterfaceAn object of ServletRequest is used to provide the client request information to a servlet such as content type, content length, parameter names and values, header informations, attributes etc.
Methods of ServletRequest interface: public String getParameter(String name) public String[] getParameterValues(String name) java.util.Enumeration getParameterNames() public int getContentLength() public String getCharacterEncoding() public String getContentType() public ServletInputStream getInputStream() throws
IOException
RequestDispatcher in ServletThe RequestDispacher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp. This interface can also be used to include the content of another resource also. It is one of the way of servlet collaboration.
Methods of RequestDispatcher interface public void forward(ServletRequest request,ServletResponse
response)throws ServletException,java.io.IOException public void include(ServletRequest request,ServletResponse
response)throws ServletException,java.io.IOException
Example of RequestDispatcher interface
Session simply means a particular interval of time. Session Tracking is a way to maintain state (data) of an
user. It is also known as session management in servlet. Http protocol is a stateless so we need to maintain state
using session tracking techniques. Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular user.
SESSION TRACKING IN SERVLETS
Session Tracking TechniquesThere are four techniques used in Session tracking:
Cookies Hidden Form Field URL Rewriting HttpSession
Cookies in ServletA cookie is a small piece of information that is persisted between the multiple client requests.A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.
Advantage of Cookies Simplest technique of maintaining the state. Cookies are maintained at client side.
Disadvantage of Cookies It will not work if cookie is disabled from the
browser. Only textual information can be set in Cookie
object.
Hidden Form FieldIn case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of an user.
<input type="hidden" name="uname" value="Vimal Jaiswal">
Advantage of Hidden Form Field It will always work whether cookie is
disabled or not.Disadvantage of Hidden Form Field:
It is maintained at server side. Extra form submission is required on each pages.
Only textual information can be used.
Example of using Hidden Form Field
URL Rewriting
In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource. We can send parameter
name/value pairs using the following format:url?name1=value1&name2=value2&??
A name and a value is separated using an equal = sign, a parameter name/value pair is separated from another parameter using the ampersand(&).
Advantage of URL Rewriting
It will always work whether cookie is disabled or not (browser independent).
Extra form submission is not required on each pages.
Disadvantage of URL Rewriting
It will work only with links. It can send Only textual
information.
Example of using URL Rewriting
HttpSession interface
In such case, container creates a session id for each user. The container uses this id to identify the particular user. An object of HttpSession can be used to perform two tasks:
bind objects view and manipulate information about a session,
such as the session identifier, creation time, and last accessed time.
The HttpServletRequest interface provides two methods to get the object of HttpSession:
public HttpSession getSession() public HttpSession getSession(boolean create)
Event and Listener in Servlet
Events are basically occurrence of something. Changing the state of an object is known as an event.
Event classes
The event classes are as follows: ServletRequestEvent ServletContextEvent ServletRequestAttributeEvent ServletContextAttributeEvent HttpSessionEvent HttpSessionBindingEvent
JSP(JAVA SERVER PAGE)
JSP technology is used to create web application just like Servlet technology.
A JSP page consists of HTML tags and JSP tags. The jsp pages are easier to maintain than servlet because we
can separate designing and development. It provides some additional features such as Expression
Language, Custom Tag etc.
Advantage of JSP over Servlet Extension to Servlet Easy to maintain Fast Development: No need to recompile and
redeploy Less code than Servlet
Life cycle of a JSP Page
JSP Scriptlet tag (Scripting elements) In JSP, java code can be written inside the jsp page using the
scriptlet tag.
Scripting elementsThe scripting elements provides the ability to insert java code inside the jsp. There are three types of scripting elements:
scriptlet tag expression tag declaration tag
JSP scriptlet tag
A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
<% java source code %>
JSP expression tagThe code placed within expression tag is written to the output stream of the response. So you need not write out.print() to write data. It is mainly used to print the values of variable or method.
Syntax of JSP expression tag
<%= statement %>
JSP Declaration TagThe JSP declaration tag is used to declare fields and methods.The code written inside the jsp declaration tag is placed outside the service() method of auto generated servlet.
Syntax of JSP declaration tag
<%! field or method declaration %>
JSP Implicit ObjectsThese objects are created by the web container that are available to all the jsp pages. A list of the 9 implicit objects is given below:
out request response config application session pageContext page exception
Example of implicit object
Out: <%out.print("Today"+java.util.Calendar.getInstance().getTime()); %>
Request:<% String name=request.getParameter(“xxx"); %>
Response:<% response.sendRedirect("http://www.google.com"); %> Session:<% session.setAttribute("user", xxx); %>
<% String name=(String)session.getAttribute("user"); ); %> Exception:<%@ page errorPage="error.jsp" %> <%@ page isErrorPage="true" %>
JSP directivesThe jsp directives are messages that tells the web container how to translate a JSP page into the corresponding servlet. There are three types of directives:
page directive include directive taglib directive
Syntax of JSP Directive
<%@ directive attribute="value" %>
Attributes of JSP page directive import contentType isELIgnored Session errorPage isErrorPage
Jsp Include DirectiveThe include directive is used to include the contents of any resource it may be jsp file, html file or text file.
Advantage of Include directive Code Reusability
Syntax of include directive
<%@ include file="resourceName" %>
JSP Taglib directiveThe JSP taglib directive is used to define a tag library that defines many tags. We use the TLD (Tag Library Descriptor) file to define the tags.
Syntax JSP Taglib directive
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>
Exception Handling in JSPThe exception is normally an object that is thrown at runtime. Exception Handling is the process to handle the runtime errors. There may occur exception any time in your web application. So handling exceptions is a safer side for the web developer. In JSP, there are two ways to perform exception handling:
By errorPage and isErrorPage attributes of page directive
By <error-page> element in web.xml file
Expression Language (EL) in JSPThe Expression Language (EL) simplifies the accessibility of data stored in the Java Bean component, and other objects like request, session, application etc.There are many implicit objects, operators and reserve words in EL.
Syntax for Expression Language (EL)
${ expression } Implicit Objects in Expression Language (EL)
pageScope requestScope sessionScope param
Simple example of Expression Language<form action="process.jsp">
Enter Name:<input type="text" name="name“ >
<input type="submit" value="go"/>
</form>
process.jsp
Welcome, ${ param.name }
Custom TagFor creating any custom tag, we need to follow following steps:
Create the Tag handler class and perform action at the start or at the end of the tag.
Create the Tag Library Descriptor (TLD) file and define tags
Create the JSP file that uses the Custom tag defined in the TLD file
Understanding flow of custom tag in jsp
Create the Tag handler classTo create the Tag Handler, we are inheriting the TagSupport class and overriding its method doStartTag().To write data for the jsp, we need to use the JspWriter class.The PageContext class provides getOut() method that returns the instance of JspWriter class. TagSupport class provides instance of pageContext bydefault.
public class MyTagHandler extends TagSupport
{
public int doStartTag() throws JspException
{
JspWriter out=pageContext.getOut();
}
}
Create the TLD fileTag Library Descriptor (TLD) file contains information of tag and Tag Hander classes. It must be contained inside the WEB-INF directory.
<taglib>
<tag>
<name>today</name>
<tag-class>com.javatpoint.sonoo.MyTagHandler</tag-class>
</tag>
</taglib>
Create the JSP fileLet's use the tag in our jsp file. Here, we are specifying the path of tld file directly. But it is recommended to use the uri name instead of full path of tld file. We will learn about uri later. It uses taglib directive to use the tags defined in the tld file.
<%@ taglib uri="WEBINF/mytags.tld" prefix="m" %>
<m:today>Current Date and Time is: </m:today>
DATA BASE CONNECTION
INTRODUCTION
Database Management System or DBMS in short, refers to the technology of storing and retrieving users data with utmost efficiency along with safety and security features.
DBMS allows its users to create their own databases which are relevant with the nature of work they want. These databases are highly configurable and offers bunch of options.
DATABASE
A Database is a collection of related data organized in a way that data can be easily accessed, managed and updated.
Any piece of information can be a data.
Ex: Name of a student, age, class and her subjects can be counted as data for recording purposes.
OVERVIEW
A DBMS is a software that allows creation, definition and manipulation of database.
DBMS is actually a tool used to perform any kind of operation on data in database.
DBMS also provides protection and security to database. It maintains data consistency in case of multiple users.
Here are some examples of popular dbms, MySql, Ms sql, Oracle, Sybase, Microsoft Access and IBM DB2 etc.
ARCHITECTURE
Database architecture is logically divided into two types. Logical two-tier Client / Server architecture Logical three-tier Client / Server architecture
LOGICAL TWO-TIER CLIENT / SERVER ARCHITECTURE
The two-tier architecture is like client server application. The direct communication takes place between client and server. There is no intermediate between client and server.
Advantages: Understanding and maintenances
is easier.Disadvantages: Performance will be reduced
when there are more users.
LOGICAL THREE-TIER CLIENT / SERVER ARCHITECTURE
Three tier architecture having three layers.
1. Client layer
2. Business layer
3. Data layer
1. Client layer: Here we design the form using textbox, label etc.
2. Business layer: It is the intermediate layer which has the functions for client layer and it is used to make communication faster between client and data layer. It provides the business processes logic and the data access.
3. Data layer: it has the database.
Advantageso Easy to modify with out affecting other modules o Fast communication o Performance will be good in three tier architecture.
COMPONENTS OF DATABASE SYSTEM
The database system can be divided into four components.
1. Users
2. Database application
3. DBMS
4. Database
COMPONENTS OF DATABASE SYSTEM
USERS: User may be of various types such as
DB administrator, system developer and end user.
DATABASE APPLICATION: It may be personal, Departmental, enterprise and Internal
DBMS: Software that allow user to define, create and manages database access. Ex, MySql, oracle, etc.
DATABASE: Collection of logical data
FUNCTIONS
Provides data Independence. Concurrency Control. Provide Recovery Services. Provides Utility Services. Provides a clear and logical view of the process.
ADVANTAGES
Minimal data duplicity. Easy retrieval of data. Reduced development time and maintenance need. Minimal Data Redundancy. Data Consistency. Data Sharing. Better Controls. Reduced Maintenance
DISADVANTAGES
Complexity Costly Large in size
RDBMS
RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.
DATA DEFINITION LANGUAGE
SQL uses the following set of commands to define database schema:
CREATE DROP ALTER TRUNCATE
CREATE: Creates new databases, tables and views from RDBMS
Create database dbms;
Create table article(id int , name varchar)
Create view for students;
DROP: Drop commands deletes views, tables and databases from RDBMS
Drop object type object name;
Drop database dbms;
Drop table article;
Drop view for_students;
ALTER: Modifies database schema.
Alter object_type object_name parameters;
for example:
Alter table article add subject varchar;
DATA MANIPULATION LANGUAGE
DML modifies the database instance by inserting, updating and deleting its data.
DML is responsible for all data modification in databases.
SQL contains the following set of command in DML section:
INSERT UPDATE DELETE SELECT
INSERT
INSERT: Insert command is used to insert data into a table.
Syntax: INSERT into table_name values(data1,data2,…)
UPDATE
The UPDATE statement is used to update records in a table.
Syntax update table_name set
column1=value1,column2=value2,...where some_column=some_value;
FOR EXAMPLE:update Students set age=18 where s_id=102;
DELETE
Delete command is used to delete data from a table.
Delete command can use to delete a particular row or whole data in the table.
Syntax: DELETE FROM table_name
WHERE some_column=some_value;To delete all row from a table. DELETE FROM table_name;
orDELETE * FROM table_name;
SELECT
This command is used to select data from database.
Syntax SELECT
column_name,column_nameFROM table_name;andSELECT * FROM table_name;
DATA CONTROL LANGUAGE (DCL)
Data Control Language(DCL): Is a Structured query that allows database administrators to configure security access to relational databases.
DCL commands are used to enforce database security in a multiple user database environment.
There are two types of DCL commands. GRANT REVOKE
GRANT
SQL GRANT is a command used to provide access or privileges on the database objects to the users.
The Syntax for the GRANT command is:
grant privilege_name on object_name to {user_name |public|role_name} [WITH GRANT OPTION];
To allow a user to create a session. grant create session to username
REVOKE
The REVOKE command removes user access rights or privileges to the database objects.
The syntax for this command is defined as follows:
REVOKE[GRANT OPTION FOR] [permission] ON [object] FROM [user]
KEY
• Key --> The attribute used to define a required item
Types of keys: * Primary Key: Key used to uniquely identify a record
* Foreign Key: A field in this table which is the Primary key of another table
END
Top Related