unit 4,5 web tech
unit 4,5 web tech
unit 4,5 web tech
EJB Architecture:
Disadvantages of EJB:
Java Bean: JavaBeans are classes that encapsulate many objects into a single object (the
bean). It is a java class that should follow following conventions:
package geeks;
public Student()
this.id = id;
return id;
this.name = name;
}
return name;
package geeks;
System.out.println(s.getName());
JavaBean Properties
A JavaBean property is a named feature that can be accessed by the user of the object. The
feature can be of any Java data type, containing the classes that you define.
A JavaBean property may be read, write, read-only, or write-only. JavaBean features are
accessed through two methods in the JavaBean's implementation class:
1. getPropertyName ()
For example, if the property name is firstName, the method name would be getFirstName() to
read that property. This method is called the accessor.
2. setPropertyName ()
For example, if the property name is firstName, the method name would be setFirstName() to
write that property. This method is called the mutator.
Advantages of JavaBean
Disadvantages of JavaBean
Then verify that the content is correct by the command "jar tf SimpleBean.jar".
Step 5:
CD to c:\Program Files\BDK1.1\beanbox\.
Then type "run".
2. Load JAR into Bean Box by selecting "LoadJar..." under the File menu.
Step 6:
1. After the file selection dialog box is closed, change focus to the "ToolBox"
window. You'll see "SimpleBean" appear at the bottom of the toolbox window.
2. Select SimpleBean.jar.
3. Cursor will change to a plus. In the middle BeanBox window, you can now click to
drop in what will appear to be a colored rectangle.
Step 7:
Try changing the red box's color with the Properties windows.
Step 8:
Chose "Events" under the "Edit" menu in the middle window to see what events SimpleBean
can send. These events are inherited from java.awt.Canvas.
1. Session bean
i) stateless
ii) statefull
2. Entity bean
3. Message driven bean
Session Bean:
• A session bean is an EJB 3.0 or EJB 2.1 enterprise bean component created by a client
for the duration of a single client/server session.
• A session bean performs operations for the client. Although a session bean can be
transactional, it is not recoverable if failure occurs.
• For example, in an on-line store application, you can use a session bean to implement
a Shopping Cart Bean that provides a Cart interface that the client uses to invoke such
methods as purchase Item and checkout.
Entity Bean:
• An entity bean is an enterprise bean component that manages persistent data, performs
complex business logic, potentially uses several dependent Java objects, and can be
uniquely identified by a primary key.
• Entity beans are persistent because their data is stored persistently in some form of data
storage, such as a database
• Entity beans survive a server failure, failover, or a network failure.
• When an entity bean is reinstantiated, the state of the previous instance is automatically
restored.
• A message-driven bean (MDB) is an EJB 3.0 or EJB 2.1 enterprise bean component
that functions as an asynchronous message consumer.
• An MDB has no client-specific state but may contain message-handling state such as
an open database connection or object references to another EJB.
• A client uses an MDB to send messages to the destination for which the bean is a
message listener.
• The purpose of an MDB is to exist within a pool and to receive and process incoming
messages from a message provider.
• The container invokes a bean from the queue to handle each incoming message from
the queue.
• No object invokes an MDB directly: all invocation for an MDB comes from the
container.
• After the container invokes the MDB, it can invoke other enterprise beans or Java
objects to continue the request.
JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of
databases.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.
• Making a connection to a database.
• Creating SQL or MySQL statements.
• Executing SQL or MySQL queries in the database.
• Viewing & modifying the resulting records.
We can use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.
We can use JDBC API to handle database using Java program and can perform the following
activities:
The JDBC API supports both two-tier and three-tier processing models for database access but
in general, JDBC Architecture consists of two layers −
• JDBC API − This provides the application-to-JDBC Manager connection.
• JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data source.
The driver manager is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application −
• The Java application calls JDBC classes and interfaces to submit SQL statements and
retrieve results.
• The JDBC API is implemented through the JDBC driver.
• The JDBC Driver is a set of classes that implement the JDBC interfaces to process
JDBC calls and return result sets to a Java application.
• The database (or data store) stores the data retrieved by the application using the
JDBC Driver.
JDBC Driver:
JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
1) JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge
driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin
driver.
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you
use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.
Advantages:
o easy to use.
o can be easily connected to any database.
Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC function
calls.
o The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls
into native calls of the database API. It is not written entirely in java.
Advantage:
o performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
o The Native driver needs to be installed on each client machine.
o The Vendor client library needs to be installed on client machine.
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
o No client-side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is
known as thin driver. It is fully written in Java language.
Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.
Disadvantage:
o Drivers depend on the Database.
Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
Syntax:
1. import java.sql.*;
2. class InsertPrepared{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe
","system","oracle");
8.
9. PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
10. stmt.setInt(1,101);//1 specifies the first parameter in the query
11. stmt.setString(2,"Ratan");
12.
13. int i=stmt.executeUpdate();
14. System.out.println(i+" records inserted");
15.
16. con.close();
17.
18. }catch(Exception e){ System.out.println(e);}
19.
20. }
21. }
Example of PreparedStatement interface that updates the record
1. PreparedStatement stmt=con.prepareStatement("update emp set name=? where id=?")
;
2. stmt.setString(1,"Sonoo");//1 specifies the first parameter in the query i.e. name
3. stmt.setInt(2,101);
4.
5. int i=stmt.executeUpdate();
6. System.out.println(i+" records updated");
Example of PreparedStatement interface that deletes the record
1. PreparedStatement stmt=con.prepareStatement("delete from emp where id=?");
2. stmt.setInt(1,101);
3.
4. int i=stmt.executeUpdate();
5. System.out.println(i+" records deleted");
Example of PreparedStatement interface that retrieve the records of a table
1. PreparedStatement stmt=con.prepareStatement("select * from emp");
2. ResultSet rs=stmt.executeQuery();
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }
Transaction Management in JDBC:
The ACID properties describe the transaction management well. ACID stands for Atomicity,
Consistency, isolation and durability.
Consistency ensures bringing the database from one consistent state to another consistent state.
fast performance It makes the performance fast because database is hit at the time of commit.
Method Description
void setAutoCommit(boolean status) It is true bydefault means each transaction is committed bydefault.
Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side programming
language.
Step 1: Client i.e., web browser sends the request to the web server.
Step 2: Web server receives the request and sends it to the servlet container. Servlet container
is also called web container or servlet engine. It is responsible for handling the life of a
servlet.
Step 3: Servlet container understands the request’s URL and calls the particular servlet.
Actually, it creates a thread for execution of that servlet. If there are multiple requests for the
same servlet, then for each request, one thread will be created.
Step 4: Servlet processes the request object and prepares response object after interacting
with the database or performing any other operations and sends the response object back to
the web server.
Step 5: Then web server sends the response back to the client.
Advantages:
• Prime functionality of a servlet is that they are independent of server
configuration and they are pretty much compatible with any of the web servers
• Servlets are also protocol-independent supporting FTP, HTTP, SMTP, etc.
protocols to the fullest.
• Until destroyed manually, servlets can be retained in the memory helping
process several requests over time. Also, once a database connection is
established, it can facilitate process several requests for a database in the very
same database session.
• Servlets inherit Java’s property of portability and hence are compatible with
nearly any web server.
• Servlets are first converted into byte codes and then executed, which helps in
increasing the processing time.
Disadvantages:
• Designing a servlet can be pretty laborious.
• Exceptions need to be handled while designing a servlet since they are not
thread-safe.
• Developers may need additional skills to program a servlet.
Life-Cycle of Servlets: The web container maintains the life cycle of a servlet instance. Let's
see the life cycle of the servlet:
The classloader is responsible to load the servlet class. The servlet class is loaded when the
first request for the servlet is received by the web container.
The web container creates the instance of a servlet after loading the servlet class. The servlet
instance is created only once in the servlet life cycle.
The web container calls the service method each time when request for the servlet is received.
If servlet is not initialized, it follows the first three steps as described above then calls the
service method. If servlet is initialized, it calls the service method. Notice that servlet is
initialized only once. The syntax of the service method of the Servlet interface is given below:
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
5) destroy method is invoked
The web container calls the destroy method before removing the servlet instance from the
service. It gives the servlet an opportunity to clean up any resource for example memory, thread
etc. The syntax of the destroy method of the Servlet interface is given below:
Working of Servlets:
Characteristics of Servlet:
Servlet Interface:
Servlet interface provides common behaviour to all the servlets. Servlet interface defines
methods that all servlets must implement.
Servlet interface needs to be implemented for creating any servlet (either directly or indirectly).
It provides 3 life cycle methods that are used to initialize the servlet, to service the requests,
and to destroy the servlet and 2 non-life cycle methods.
There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods
of servlet. These are invoked by the web container.
Method Description
public void init(ServletConfig config) initializes the servlet. It is the life cycle method of
servlet and invoked by the web container only once.
public void destroy() is invoked only once and indicates that servlet is being
destroyed.
Handling GET requests involves overriding the doGet method. The following example shows
the BookDetailServlet doing this. The methods discussed in the Requests and
Responses section are shown in bold.
The servlet extends the HttpServlet class and overrides the doGet method.
Within the doGet method, the getParameter method gets the servlet's expected argument.
To respond to the client, the example doGet method uses a Writer from
the HttpServletResponse object to return text data to the client. Before accessing the writer,
the example sets the content-type header. At the end of the doGet method, after the response
has been sent, the Writer is closed.
Handling POST requests involves overriding the doPost method. The following example
shows the ReceiptServlet doing this. Again, the methods discussed in the Requests and
Responses section are shown in bold.
The servlet extends the HttpServlet class and overrides the doPost method.
Within the doPost method, the getParameter method gets the servlet's expected argument.
To respond to the client, the example doPost method uses a Writer from
the HttpServletResponse object to return text data to the client. Before accessing the writer
the example sets the content-type header. At the end of the doPost method, after the response
has been set, the Writer is closed.
Session Tracking:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
Cookies in Servlet
A 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.
By default, each request is considered as a new request. In cookies technique, we add cookie
with response from the servlet. So cookie is stored in the cache of the browser. After that if
request is sent by the user, cookie is added with request by default. Thus, we recognize the user
as the old user.
Types of Cookies
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session. It is not removed each time when user closes the browser. It is
removed only if user logout or signout.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Session Tracking with HTTPSession:
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:
1. bind objects
2. 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:
Cookie Session
Cookies end on the lifetime set by When the user quits the browser or logs out of the
the user. programmed, the session is over.
1. index.html
2. link.html
3. login.html
4. LoginServlet.java
5. LogoutServlet.java
6. ProfileServlet.java
7. web.xml
File: index.html
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
5. <title>Servlet Login Example</title>
6. </head>
7. <body>
8.
9. <h1>Welcome to Login App by Cookie</h1>
10. <a href="login.html">Login</a>|
11. <a href="LogoutServlet">Logout</a>|
12. <a href="ProfileServlet">Profile</a>
13.
14. </body>
15. </html>
File: link.html
1. <a href="login.html">Login</a> |
2. <a href="LogoutServlet">Logout</a> |
3. <a href="ProfileServlet">Profile</a>
4. <hr>
File: login.html
File: LoginServlet.java
1. package com.javatpoint;
2.
3. import java.io.IOException;
4. import java.io.PrintWriter;
5. import javax.servlet.ServletException;
6. import javax.servlet.http.Cookie;
7. import javax.servlet.http.HttpServlet;
8. import javax.servlet.http.HttpServletRequest;
9. import javax.servlet.http.HttpServletResponse;
10. public class LoginServlet extends HttpServlet {
11. protected void doPost(HttpServletRequest request, HttpServletResponse response)
File: LogoutServlet.java
1. package com.javatpoint;
2.
3. import java.io.IOException;
4. import java.io.PrintWriter;
5. import javax.servlet.ServletException;
6. import javax.servlet.http.Cookie;
7. import javax.servlet.http.HttpServlet;
8. import javax.servlet.http.HttpServletRequest;
9. import javax.servlet.http.HttpServletResponse;
10. public class LogoutServlet extends HttpServlet {
11. protected void doGet(HttpServletRequest request, HttpServletResponse response)
File: ProfileServlet.java
1. package com.javatpoint;
2.
3. import java.io.IOException;
4. import java.io.PrintWriter;
5. import javax.servlet.ServletException;
6. import javax.servlet.http.Cookie;
7. import javax.servlet.http.HttpServlet;
8. import javax.servlet.http.HttpServletRequest;
9. import javax.servlet.http.HttpServletResponse;
10. public class ProfileServlet extends HttpServlet {
11. protected void doGet(HttpServletRequest request, HttpServletResponse response)
File: web.xml
To create the first JSP page, write some HTML code as given below, and save it by .jsp
extension. We have saved this file as index.jsp. Put it in a folder and paste the folder in the
web-apps directory in apache tomcat to run the JSP page.
index.jsp
Let's see the simple example of JSP where we are using the scriptlet tag to put Java code in the
JSP page. We will learn scriptlet tag later.
1. <html>
2. <body>
3. <% out.print(2*5); %>
4. </body>
5. </html>
JSP Architecture:
JSP Processing:
Step 1: The client navigates to a file ending with the .jsp extension and the browser
initiates an HTTP request to the webserver. For example, the user enters the login details
and submits the button. The browser requests a status.jsp page from the webserver.
Step 2: If the compiled version of JSP exists in the web server, it returns the file.
Otherwise, the request is forwarded to the JSP Engine. This is done by recognizing the
URL ending with .jsp extension.
Step 3: The JSP Engine loads the JSP file and translates the JSP to Servlet(Java code). This
is done by converting all the template text into println() statements and JSP elements to
Java code. This process is called translation.
Step 4: The JSP engine compiles the Servlet to an executable .class file. It is forwarded to
the Servlet engine. This process is called compilation or request processing phase.
Step 5: The .class file is executed by the Servlet engine which is a part of the Web Server.
The output is an HTML file. The Servlet engine passes the output as an HTTP response to
the webserver.
Step 6: The web server forwards the HTML file to the client’s browser.
The scripting elements provides the ability to insert java code inside the jsp. There are three
types of scripting elements:
o scriptlet tag
o expression tag
o declaration tag
A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
<% java source code %>
Example of JSP scriptlet tag
1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>
JSP expression tag
The code placed within JSP 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.
The code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.
There are 9 jsp implicit objects. These objects are created by the web container that are
available to all the jsp pages.
The available implicit objects are out, request, config, session, application etc.
Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
1) JSP out implicit object
For writing any data to the buffer, JSP provides an implicit object named out. It is the object
of JspWriter. In case of servlet you need to write:
PrintWriter out=response.getWriter();
Example of out implicit object
index.jsp
1. <html>
2. <body>
3. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
4. </body>
5. </html>
Output
The JSP request is an implicit object of type HttpServletRequest i.e. created for each jsp
request by the web container. It can be used to get request information such as parameter,
header information, remote address, server name, server port, content type, character encoding
etc.
Let's see the example of response implicit object where we are redirecting the response to the
Google.
1. <form action="welcome.jsp">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
welcome.jsp
1. <%
2. response.sendRedirect("http://www.google.com");
3. %>
Output
4) JSP config implicit object
In JSP, config is an implicit object of type ServletConfig. This object can be used to get
initialization parameter for a particular JSP page. The config object is created by the web
container for each jsp page.
1. <form action="welcome">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
web.xml file
1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <jsp-file>/welcome.jsp</jsp-file>
6.
7. <init-param>
8. <param-name>dname</param-name>
9. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
10. </init-param>
11.
12. </servlet>
13.
14. <servlet-mapping>
15. <servlet-name>sonoojaiswal</servlet-name>
16. <url-pattern>/welcome</url-pattern>
17. </servlet-mapping>
18.
19. </web-app>
welcome.jsp
1. <%
2. out.print("Welcome "+request.getParameter("uname"));
3.
4. String driver=config.getInitParameter("dname");
5. out.print("driver name is="+driver);
6. %>
Output
The instance of ServletContext is created only once by the web container when application or
project is deployed on the server.
1. <form action="welcome">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
web.xml file
1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <jsp-file>/welcome.jsp</jsp-file>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>sonoojaiswal</servlet-name>
10. <url-pattern>/welcome</url-pattern>
11. </servlet-mapping>
12.
13. <context-param>
14. <param-name>dname</param-name>
15. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
16. </context-param>
17.
18. </web-app>
welcome.jsp
1. <%
2.
3. out.print("Welcome "+request.getParameter("uname"));
4.
5. String driver=application.getInitParameter("dname");
6. out.print("driver name is="+driver);
7.
8. %>
Output
o page
o request
o session
o application
Object page=this;
Since, it is of type Object it is less used because you can use this object directly in jsp.For example:
The jsp directives are messages that tells the web container how to translate a JSP page into
the corresponding servlet.
o page directive
o include directive
o taglib directive
The page directive defines attributes that apply to an entire JSP page.
Code Reusability
In this example, we are including the content of the header.html file. To run this example you
must create an header.html file.
1. <html>
2. <body>
3.
4. <%@ include file="header.html" %>
5.
6. Today is: <%= java.util.Calendar.getInstance().getTime() %>
7.
8. </body>
9. </html>
JSP Taglib directive
The 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. In the custom tag section we will use
this tag so it will be better to learn it in custom tag.
Syntax JSP Taglib directive
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>
Example of JSP Taglib directive
1. <html>
2. <body>
3.
4. <%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
5.
6. <mytag:currentDate/>
7.
8. </body>
9. </html>
JSP Action Tags
There are many JSP action tags or elements. Each JSP action tag is used to perform some
specific tasks.
The action tags are used to control the flow between pages and to use Java Bean. The Jsp action
tags are given below.
jsp:param sets the parameter value. It is used in forward and include mostly.
jsp:fallback can be used to print the message if plugin is working. It is used in jsp:plugin.
The jsp:forward action tag is used to forward the request to another resource it may be jsp, html
or another resource.
The jsp:include action tag is used to include the content of another resource it may be jsp,
html or servlet.
The jsp include action tag includes the resource at request time so it is better for dynamic
pages because there might be changes in future.
The jsp:include tag can be used to include static as well as dynamic pages.
Advantage of jsp:include action tag
Code reusability : We can use a page many times such as including header and footer pages
in all pages. So it saves a lot of time.
includes the original content in the generated servlet. calls the include method.
The jsp:useBean action tag is used to locate or instantiate a bean class. If bean object of the
Bean class is already created, it doesn't create the bean depending on the scope. But if object
of bean is not created, it instantiates the bean.
The setProperty and getProperty action tags are used for developing web application with Java
Bean. In web devlopment, bean class is mostly used because it is a reusable software
component that represents data.
The jsp:setProperty action tag sets a property value or values in a bean using the setter method.
Custom tags are user-defined tags. They eliminates the possibility of scriptlet tag and separates
the business logic from the JSP page.
The same business logic can be used many times by the use of custom tag.
1. Eliminates the need of scriptlet tag The custom tags eliminates the need of scriptlet
tag which is considered bad programming approach in JSP.
2. Separation of business logic from JSP The custom tags separate the the business logic
from the JSP page so that it may be easy to maintain.
3. Re-usability The custom tags makes the possibility to reuse the same business logic
again and again.
There are two ways to use the custom tag. They are given below: