68
Presented by: Aarti Dadheech ADVANCE JAVA

Advance Java Topics (J2EE)

  • Upload
    slire

  • View
    218

  • Download
    2

Embed Size (px)

DESCRIPTION

Overview of Advance Java Topics

Citation preview

Page 1: Advance Java Topics (J2EE)

Presented by:Aarti Dadheech

ADVANCE JAVA

Page 2: Advance Java Topics (J2EE)

INDEX1.Brief Overview of Java2.Advance java3.Servlets4.Session Handling 5.Database Handling6.JSP7.Struts8.MVC9.Tiles10Hibernate

Page 3: Advance Java Topics (J2EE)

Brief Overview:

JAVA

Page 4: Advance Java Topics (J2EE)

What is java?

Java is a computer programming language that is concurrent, class-based, object-oriented.

It is intended to let application developers "write once, run anywhere" (WORA).

Java applications are typically compiled to bytecode (class file) that can run on any Java virtual machine (JVM) regardless of computer architecture.

Java is, as of 2014, one of the most popular programming languages in use, particularly for client-server web applications.

Java is the Internet programming language

Page 5: Advance Java Topics (J2EE)

Java's History

• Java was originally developed by James Gosling at Sun Microsystems (which has since merged into Oracle Corporation).

• Originally named OAK in 1991• First non commercial version in 1994• Renamed and modified to Java in 1995 and released as a

core component of Sun Microsystems' Java platform. • First Commercial version in late 1995

• Hot Java -The first Java-enabled Web browser

Page 6: Advance Java Topics (J2EE)

Java Technology

• What is Java?

Java technology is both a programming language and a platform.

Page 7: Advance Java Topics (J2EE)

-Simple-Object oriented-Distributed -Multithreaded -DynamicArchitecture neutral-Portable-High performance -Robust-Secure

--The Java Programming Language The Java programming language is a high-level language that can be characterized by all of the following buzzwords:

Page 8: Advance Java Topics (J2EE)

--The Java PlatformA platform is the hardware or software environment in which a program runs. Some of the most popular platforms are Microsoft Windows, Linux, Solaris OS, and Mac OS. Most platforms can be described as a combination of the operating system and underlying hardware. The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms.

The Java platform has two components:

The Java Virtual Machine

The Java Application

Programming Interface (API)

Page 9: Advance Java Topics (J2EE)

Different Editions of Java

• Java Standard Edition (J2SE)– J2SE can be used to develop client-side

standalone applications or applets.

• Java Enterprise Edition (J2EE)– J2EE can be used to develop server-side

applications such as Java servlets, Java ServerPages, and Java ServerFaces.

• Java Micro Edition (J2ME). – J2ME can be used to develop applications for

mobile devices such as cell phones.

Page 10: Advance Java Topics (J2EE)

Starti ng J2EE

JAVA ENTERPRISE EDITION(J2EE)

Page 11: Advance Java Topics (J2EE)

J2EE

• J2EE is a platform-independent, Java-centric environment from Sun for developing, building and deploying Web-based enterprise applications online.

Page 12: Advance Java Topics (J2EE)

Why J2EE?

• Simplifies the complexity of a building n-tier application

• Standardizes an API between components and application server container

• J2EE Application Server and Containers provide the framework services

Page 13: Advance Java Topics (J2EE)

J2EE Tiers• Client Presentation

HTML or Java applets deployed in Browser

XML documentations transmitted through HTTP

Java clients running in Client Java Virtual Machine (JVM)

• Presentation Logic Servlets or JavaServer

Pages running in web server

• Application Logic Enterprise JavaBeans

running in Server

Page 14: Advance Java Topics (J2EE)

Servlets

Page 15: Advance Java Topics (J2EE)

What are Servlets?

• The Servlet is a server-side programming language class used for making dynamic web pages. They reside within a servlet engine.

• Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol.

• They provide concurrency ,portability and Efficiency.

Page 16: Advance Java Topics (J2EE)

Tasks of a Servlet

• Read the explicit data sent by the clients (browsers).

• Read the implicit HTTP request data sent by the clients (browsers).

• Process the data and generate results.• Send the explicit data (i.e., the document) to

the clients (browsers). • Send the implicit HTTP response to the clients

(browsers

Page 17: Advance Java Topics (J2EE)

Servlet life cycle

All methods are performed by Container Initialize using init() method when requested. Service() method handles requests/clients.

The requests are forwarded to the appropriate method (ie. doGet() or doPost())

Server removes the servlet using destroy() method

Page 18: Advance Java Topics (J2EE)

Basic Servlet exampleimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;

public class Test extends HttpServlet{ public void doGet(HttpServletRequest in,

HttpServletResponse out) throws ServletException, IOException {

out.setContentType(“text/html”); PrintWriter p = res.getWriter(); p.println(“<H1>HELLO, WORLD!</H1>”); }}

Page 19: Advance Java Topics (J2EE)

Working with Servlets All servlets must extend the HttpServlet or Servlet

class public class MyServlet extends HttpServlet

HttpServlet Class overrides service() method. Two most common HTTP request types. Under HTTP, there

are two methods available for sending parameters from the browser to the web server.

doPost(HttpServletRequest,HttpServletResponse);Invoked whenever an HTTP POST request is issued through an

HTML form.Unlimited data can b send. doGet(HttpServletRequest,HttpServletResponse); Invoked whenever an HTTP GET method from a URL request is

issued, or an HTML form. Limited data sending.

Page 20: Advance Java Topics (J2EE)

Transfer Of Control

• sendRedirect(filename); sends control.• RequestDispatcher(); sends Control+data

using : Requestdispatcher rd= request.Getrequestdispatcher(“abc.Jsp”);Rd.Forward(req,res): // to see o/p of only requesting servlet.Rd.Include(req,res); //o/p of all previous servlets are shown.

HTML Servlet

abc.jsp

Abc.html

Abc(java file)

Page 21: Advance Java Topics (J2EE)

Servlet Context & Servlet Configuration

Servlet Context is some information which has global scope. It works as static data.ServletContext sc=getServletContext();sc.setAttribute("user", “abc");sc.getAttribute(“user”);

Servlet Configuration is the information specific to a servlet. ServletConfig sc = getServletConfig();

Page 22: Advance Java Topics (J2EE)

Session Handling

Session handling is used for tracking client’s session .Types of session handling:-

URL re-writingHidden form fieldCookiesHttp session

Page 23: Advance Java Topics (J2EE)

URL re-writingYou can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session.

ex:-username and password will be appended to the URL.

Hidden Form Field

HTML forms have an entry that looks like the following:

<input type=“hidden” value=“username”>

This can be used to store information about the session.

Page 24: Advance Java Topics (J2EE)

Cookies we can use HTTP cookies to store information about session and each subsequent connection can look up the current session and then extract information about that session from some location on the server machine.

• Cookies are normal files• Contains info of users• Resides on the browser

Page 25: Advance Java Topics (J2EE)

Http Session

The info of users are stored in server -side. User have no authority to modify the info.

Initialization of http session:

HttpSession hs= request.getSession();

By default session is TRUE . If false then previous session is picked up.

How to add info in hs:-

hs.setAttribute(“name", "value”);

Page 26: Advance Java Topics (J2EE)

how to get info:-HttpSession hs= request.getSession(false);

hs.getAttribute(“name”);

How to delete info:-

hs.invalidate();

HttpSession handling done as shown in following program:-

Page 27: Advance Java Topics (J2EE)
Page 28: Advance Java Topics (J2EE)
Page 29: Advance Java Topics (J2EE)
Page 30: Advance Java Topics (J2EE)
Page 31: Advance Java Topics (J2EE)
Page 32: Advance Java Topics (J2EE)
Page 33: Advance Java Topics (J2EE)
Page 34: Advance Java Topics (J2EE)
Page 35: Advance Java Topics (J2EE)
Page 36: Advance Java Topics (J2EE)

Database HandlingJava database connectivity (JDBC) is a standard application programming interface (API) specification that is implemented by different database vendors to allow Java programs to access their database management systems. The JDBC API consists of a set of interfaces and classes written in the Java programming language. 

Basic steps to use database in Java• Establish a connection• Create statements• Execute SQL statements• Get results

Page 37: Advance Java Topics (J2EE)

Loading driversClass.forName("oracle.jdbc.driver.OracleDriver");– Dynamically loads a driver class, for Oracle database.

Making connections Connection con=

DriverManager.getConnection(“Oracle:jdbc:oracle:thin:@localhost:1521:xc”,”username”,”password”);

– Establishes connection to database by obtaining a Connection object .

Page 38: Advance Java Topics (J2EE)

Specifying SQL queriesUsing prepared statements:-

Syntax- PreparedStatement ps= con.preparestatement(“SQL QUERY”);

Execute QueryThere are two operations to execute queries:-• Select – ps.executeQuery();• update – ps.executeUpdate();

To store data:-

ResultSet rs= ps.executeQuery();

Page 39: Advance Java Topics (J2EE)

To get the data from rs:-• Row by row data is fetched.

Syntax:-While( rs.next())

{

String s1= rs.getString(“name”);

Date d= rs.getDate(“date”);

}

The following program show the working:-

Page 40: Advance Java Topics (J2EE)
Page 41: Advance Java Topics (J2EE)
Page 42: Advance Java Topics (J2EE)
Page 43: Advance Java Topics (J2EE)

Java Server Pages• Server-side programming technology that enables the creation

of dynamic. Released in 1999 by Sun Microsystems.• Platform-independent method for building Web-based

applications. • Uses static data usually HTML. • To deploy and run JavaServer Pages, a compatible web server

with a servlet container, such as Apache Tomcat is required.• Entire JSP page gets translated into a servlet (once), and servlet

gets invoked (for each request)

• JavaServer Pages (JSP) lets you separate the dynamic part of your pages from the static HTML.

HTML tags and text <% some JSP code here %> HTML tags and text

Page 44: Advance Java Topics (J2EE)

Working of JSP…

Client

Server with JSP Container

HTTP Request

loads the JSP page from disk and converts it into a servlet content.

server send the .JSP

file to JSP

servlet engineJava Engine

loads the Servlet class and executes

it. Server produces an o/p in HTTP

format during exc.

Servlet Engine

.class

dynamically

generated HTML

page inside the

HTTP response

Static HTML content

Page 45: Advance Java Topics (J2EE)

Intro to Predefined variables-(Implicit Objects)

• request: Object of HttpServletRequest (1st arg to doGet)• response: : Object of HttpServletResponse (2nd arg to doGet)• session

– The HttpSession associated with the request (unless disabled with the session attribute of the page directive)

• out– The stream (of type JspWriter) used to send output to the client

• application– The ServletContext (for sharing data) as obtained via getServletConfig().getContext().

• config - Object of ServletConfig

• pageContext - Object of PageContext in JSP for a single point of access

• page – variable synonym for this object

created automatically when a web server processes a JSP page

Page 46: Advance Java Topics (J2EE)

JSP Directives

Directives provide directions and instructions over translation of JSP into servlet.

Page-defines attributes affecting structure of servlet.<%@ page contentType="text/html“ errorPage="error.jsp"import="java.util.*" %>

Include-contents of other files are included statically in JSP

<%@ include file=”header.html” %>

Taglib-include external tag library in web page.<%@ taglib uri="URIToTagLibrary" prefix="tagPrefix" %>

Page 47: Advance Java Topics (J2EE)

JSP Elements• Expression:- It contains a scripting language expression that is evaluated,

converted to a String, and inserted where the expression appears in the JSP file.Syntax=> <%= expression %>Eg: Current time: <%=new.java.util.Date() %>• Declarations:- May contain one or more Java declarations to be inserted into

the class body of the generated servletSyntax=> <%! Java declarations %>Eg:<%! Int i; %>• Scriplets:-Consists of one or more Java statements to be inserted into the

generated servlet’s _jspService method (called by service).Syntax=> <% java code %>Eg: <%

String var1 = request.getParameter("name"); out.println(var1);%>

Page 48: Advance Java Topics (J2EE)

JSP v/s Servlets

Servlets are strictly written in Java .Servlets must be given both a servlet definition and one or more mappings within the web deployment descriptor (web.xml).Servlets are for generic handling of an HTTP request.Executed as a servlet itself

JSPs contain mixed dynamic content.JSPs do not require either, allowing much quicker and less brittle page creation.JSPs are specifically targeted and optimized to render a response to the request in the output language of choice (typically HTML).Code is compiled into a servlet

Page 49: Advance Java Topics (J2EE)

Apache Struts Technology

A MVC Framework for Java Web Applications

Page 50: Advance Java Topics (J2EE)

Agenda

• What is and Why Struts?• How to install Struts in your WebApp ?• Struts architecture

–Model– Controller– View

Page 51: Advance Java Topics (J2EE)

What is Struts ?

• Frameworks(Front-Ends) for Developing Java web based applications

• free open-source• Current Version: 1.1• Based on architecture of MVC(Model-View-

Controller) Design Pattern

Page 52: Advance Java Topics (J2EE)

Why Struts?

• Flexible, extensible and structured front-ends• Large user community• Stable Framework • Open source• Easy to learn and use• Feature-rich( like error handling and MVC )• Works with existing web apps

Page 53: Advance Java Topics (J2EE)

Struts Installation

• Download the zip file from the Apache website• Copy the zar files from the lib directory of the

zip file in WEB-INF/lib• Editing web.xml file

Struts Servlet and Mapping code• Create an empty struts-config.xml

Servlet Configuration code• Start your server

Page 54: Advance Java Topics (J2EE)

Web Xml File

• web.xml includes:– Configure ActionServlet instance and mapping– Resource file as <init-param>– servlet-config.xml file as <init-param>– Define the Struts tag libraries• web.xml is stored in WEB-INF/web.xml

Page 55: Advance Java Topics (J2EE)

Example: web.xml

<servlet><servlet-name>action</servlet-name>

<servlet-class> org.apache.struts.action.ActionServlet </servlet-class>

<init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param value>

</init-param> </servlet>

Page 56: Advance Java Topics (J2EE)

Struts Config File(struts-config.xml)

• struts-config.xml contains three important elements used to describe actions:

– <form-beans> contains FormBean definitions including name and type (classname)

– <action-mapping> contains action definitions Use an <action> element for each action defined

– <global-forwards> contains your global forward definitions

Page 57: Advance Java Topics (J2EE)

Struts Architecture• Struts is an open-source framework for building more flexible, maintainable and structured front-ends in Java web applications•There are two key components in a web application:

–the data and business logic performed on this data–the presentation of data

• Struts–helps structuring these components in a Java web app. –controls the flow of the web application, strictly separating these components–unifies the interaction between them

• This separation between presentation, business logic and control is achieved by implementing the Model-View-Controller (MVC) Design Pattern

Page 58: Advance Java Topics (J2EE)

Model-View-Controller(MVC)

• A famous design pattern• Breaks an application into three parts Model = Domain/Business Logic

The problem domain is represented by the Model. View = Presentation/the pieces the user sees and

interacts withThe output to the user is represented by the View. Controller = The part(s) that know how to use the model

to get something doneThe input from the user is represented by Controller.

Page 59: Advance Java Topics (J2EE)

(Controller) Servlet

BROW

SER

(View) Response JSP

Request

(Model)Java Bean

Servlet Container

Redirect

Instantiate

Model-View-ControlMVC Design Pattern

Page 60: Advance Java Topics (J2EE)

How Struts Works

Page 61: Advance Java Topics (J2EE)

Hibernate: An Introduction

• It is an object-relational mapping (ORM) solution for Java

• We make our data persistent by storing it in a database

• Hibernate takes care of this for us

Page 62: Advance Java Topics (J2EE)

Object-Relational Mapping

• It is a programming technique for converting object-type data of an object oriented programming language into database tables.

• Hibernate is used convert object data in JAVA to relational database tables.

Page 63: Advance Java Topics (J2EE)

Why Hibernate and not JDBC? • JDBC maps Java classes to database tables (and

from Java data types to SQL data types)

• Hibernate automatically generates the SQL queries.

• Hibernate provides data query and retrieval facilities and can significantly reduce development time otherwise spent with manual data handling in SQL and JDBC.

• Makes an application portable to all SQL databases.

Page 64: Advance Java Topics (J2EE)

Hibernate vs. JDBC (an example)

• JDBC tuple insertion –st.executeUpdate(“INSERT INTO book VALUES(“Harry Potter”,”J.K.Rowling”));

• Hibernate tuple insertion – session.save(book1);

Page 65: Advance Java Topics (J2EE)

Architecture

Hibernate sits between your code and the database

Maps persistent objects to tables in the database

Page 66: Advance Java Topics (J2EE)

Tiles

• Tiles are like individual visual component,• And using Tiles Framework, you can develop a

web page by including different tiles or component.

• Tile layout is a JSP page which defines the layout or defines the look and feel and where each tile (for example header, body, footer ) are placed.

Page 67: Advance Java Topics (J2EE)

Instead of writing header , and footer on each and every JSP page, how good will it be having common tile for those components and include in all the pages.

Page 68: Advance Java Topics (J2EE)

THANK YOU