Escolar Documentos
Profissional Documentos
Cultura Documentos
ADVANCE JAVA-2
QB
UNIT 1.
1.difference between Generic servlet and https servlet.
Generic servlet
https servlet
GenericServlet defines a generic, protocolHttpServlet defines a HTTP protocol specific
independent servlet.
servlet.
GenericServlet is an abstractclass it can handle
all types of protocols
Generic Servlet only supports service()
method.
Servlet is an API that provides many interfaces and classes including documentations.
Sem- 6
ADVANCE JAVA-2
QB
Overriding Method of servlet1)The doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
2)The doPost() Method
A POST request results from an HTML form that specifically lists POST as the METHOD and it
should be handled by doPost() method.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
4. explain how get and post requests are handled using servlets with appropriate examples.
Sem- 6
ADVANCE JAVA-2
QB
-> 1)Handling GET requests-Handling GET requests involves overriding the doGet method. The
following example shows the BookDetailServlet doing this.
examplespublic class BookDetailServlet extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
...
// set content-type header before accessing the Writer
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// then write the response
out.println("<html>" +
"<head><title>Book Description</title></head>" +
...);
//Get the identifier of the book to display
String bookId = request.getParameter("bookId");
if (bookId != null) {
// and the information about the book and print it
...
}
out.println("</body></html>");
out.close();
}
...
}
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.
Sem- 6
ADVANCE JAVA-2
QB
2) Handling POST Requests-Handling POST requests involves overriding the doPost method. The
following example shows the ReceiptServlet doing this
public class ReceiptServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
...
// set content type header before accessing the Writer
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// then write the response
out.println("<html>" +
"<head><title> Receipt </title>" +
...);
out.println("<h3>Thank you for purchasing your books from us " +
request.getParameter("cardname") +
...);
out.close();
}
...
}
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.
Sem- 6
ADVANCE JAVA-2
QB
5.write a short note on Servlet Life Cycle.
-> The web container maintains the life cycle of a servlet instance. Let's see the life
cycle of the servlet:
1.Servlet class is loaded- 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.
2.Servlet instance is created- The web container creates the instance of
servlet class. The servlet instance is created only once in the servlet life cycle.
3.init method is invokedThe web container calls the init method only once after creating the servlet instance. The init
method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet
interface. Syntax of the init method is given below:
public void init(ServletConfig config) throws ServletException
4.service method is invoked- 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:
public void destroy()
Sem- 6
ADVANCE JAVA-2
QB
6.Explain methods used for reading Form Data From Servlets.
-> reading Form Data using Servlet:
Servlets handles form data parsing automatically using the following methods depending on the
situation:
getParameterValues(): Call this method if the parameter appears more than once and
returns multiple values, for example checkbox.
getParameterNames(): Call this method if you want a complete list of all parameters in the
current request.
Sem- 6
ADVANCE JAVA-2
QB
Sem- 6
ADVANCE JAVA-2
QB
Adds the specified cookie to the response. This method can be called multiple times to set more than
one cookie.
ii. public void addDateHeader (String name, long date)
Adds a response header with the given name and date-value.
iii. public void addHeader(String name,String value)
Adds a response header with the given name and value.
iv public void addlntHeader(String name,int value)
Adds a response header with the given name and integer value.
v public boolean containsHeader(String name)
Returns a boolean indicating whether the named response header has already been set.
Sem- 6
ADVANCE JAVA-2
QB
Process the data and generate the results. This process may
require talking to a database, executing an RMI or CORBA call,
invoking a Web service, or computing the response directly.
On client's first request, the Web Container generates a unique session ID and gives it back
to the client with response. This is a temporary session created by web container.
2.
The client sends back the session ID with each request. Making it easier for the web
container to identify where the request is coming from.
3.
The Web Container uses this ID, finds the matching session with the ID and associates the
session with the request.
Sem- 6
ADVANCE JAVA-2
QB
void invalidate()
boolean isNew()
Use of HttpSession class To use the Java servlet API for session tracking,
first create a session object using the getSession method in the HttpServletRequest interface
like this:
HttpSession session = request.getSession(true);
This obtains the session or creates a new session if the client does not have a session on the
server.
The HttpSession class provides the methods for reading and storing data to the session, and
for manipulating the session.
Sem- 6
ADVANCE JAVA-2
QB
b)ServletConfig Interface- An object of ServletConfig is created by the web container for each
servlet. This object can be used to get configuration information from web.xml file.
If the configuration information is modified from the web.xml file, we don't need to change the
servlet. So it is easier to manage the web application if any specific content is modified from time to
time.
Advantage of ServletConfig
The core advantage of ServletConfig is that you don't need to edit the servlet file if
information is modified from the web.xml file.
Methods of ServletConfig
1. public String getServletName():Returns the name of the servlet.
2. public ServletContext getServletContext():Returns an object of ServletContext.
Sem- 6
ADVANCE JAVA-2
QB
Types of Cookie
There are 2 types of cookies in servlets.
1)Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Sem- 6
ADVANCE JAVA-2
QB
2)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.
Constructor of Cookie class
Cookie()
constructs a cookie.
Sem- 6
ADVANCE JAVA-2
QB
logs the IP addresses of the computers from which the requests originate
conversion
data compression
Authentication Filters.
Encryption Filters.
Advantage of Filter
1. Filter is pluggable.
Sem- 6
ADVANCE JAVA-2
QB
2. One filter don't have dependency onto another resource.
3. Less Maintenance
void
forward(ServletRequest
request,ServletResponse
response)throws
void
include(ServletRequest
request,ServletResponse
response)throws
Sem- 6
ADVANCE JAVA-2
QB
UNIT-2
Servlets use println statements for printing an HTML document which is usually very
difficult to use. JSP has no such tedius task to maintain.
In a JSP page visual content and logic are seperated, which is not possible in a servlet.
Usually with JSP, Java Beans and custom tags web application is simplified.
1. Web browser sends an HTTP request to the web server requesting JSP page.
2. Web server recognizes that the HTTP request by web browser is for JSP page by checking
the extension of the file (i.e .jsp)
3. Web server forwards HTTP Request to JSP engine.
4. JSP engine loads the JSP page from disk and converts it into a servlet
5. JSP engine then compiles the servlet into an executable class and forward original request
to a servlet engine.
Sem- 6
ADVANCE JAVA-2
QB
6. Servlet engine loads and executes the Servlet class.
7. Servlet produces an output in HTML format
8. Output produced by servlet engine is then passes to the web server inside an HTTP
response.
9. Web server sends the HTTP response to Web browser in the form of static HTML content.
10. Web browser loads the static page into the browser and thus user can view the
dynamically generated page.
Sem- 6
ADVANCE JAVA-2
QB
In the Model 1 architecture, the incoming request from a web browser is sent directly to the JSP
page, which is responsible for processing it and replying back to the client. There is still separation
of presentation from content, because all data access is performed using beans.
Although the Model 1 architecture is suitable for simple applications, it may not be desirable for
complex implementations. Indiscriminate usage of this architecture usually leads to a significant
amount of scriptlets or Java code embedded within the JSP page, especially if there is a significant
amount of request processing to be performed. While this may not seem to be much of a problem
for Java developers, it is certainly an issue if your JSP pages are created and maintained by
designers--which is usually the norm on large projects. Another downside of this architecture is that
each of the JSP pages must be individually responsible for managing application state and verifying
authentication and security.
Model 2 architecture
Sem- 6
ADVANCE JAVA-2
QB
as deciding, depending on the user's actions, which presentation component to forward the request
to. Front components can be implemented as either a servlet or JSP page.
The advantage of this architecture is that there is no processing logic within the presentation
component itself; it is simply responsible for retrieving any objects or beans that may have been
previously created by the controller, and extracting the dynamic content within for insertion within
its static templates. Consequently, this clean separation of presentation from content leads to a clear
delineation of the roles and responsibilities of the developers and page designers on the
programming team. Another benefit of this approach is that the front components present a single
point of entry into the application, thus making the management of application state, security, and
presentation uniform and easier to maintain.
The include directive is used to include the contents of any resource it may be jsp file, html file or
text file. The include directive includes the original content of the included resource at page
translation time (the jsp page is translated only once so it will be better to include static resource).
Advantage of Include directive
Code Reusability
Syntax of include directive
1.
1.
<html>
2.
<body>
3.
Sem- 6
ADVANCE JAVA-2
QB
4.
5.
6.
7.
8.
</body>
9.
</html>
page
page scope means, the JSP object can be accessed only from within the same page where it
was created. The default scope for JSP objects created using <jsp:useBean> tag is page. JSP
implicit objects out, exception, response, pageContext, config and page have page scope.
request
A JSP object created using the request scope can be accessed from any pages that serves
that request. More than one page can serve a single request. The JSP object will be bound to
the request object. Implicit object request has the request scope.
session
session scope means, the JSP object is accessible from pages that belong to the same
session from where it was created. The JSP object that is created using the session scope is
bound to the session object. Implicit object session has the session scope.
Sem- 6
ADVANCE JAVA-2
QB
application
A JSP object created using the application scope can be accessed from any pages across the
application. The JSP object is bound to the application object. Implicit object application
has the application scope.
Sem- 6
ADVANCE JAVA-2
QB
4)buffer-The buffer attribute sets the buffer size in kilobytes to handle output
generated by the JSP page.The default size of the buffer is 8Kb.
Example of buffer attribute
<%@ page buffer="16kb" %>
Today is: <%= new java.util.Date() %>
5)info-This attribute simply sets the information of the JSP page which is
retrieved later by using getServletInfo() method of Servlet interface.
Example of info attribute
<%@ page info="composed by Sonoo Jaiswal" %>
Today is: <%= new java.util.Date() %>
Sem- 6
ADVANCE JAVA-2
QB
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:
1.
1.
2.
body code
3.
</prefix:tagname>
Sem- 6
ADVANCE JAVA-2
QB
This action lets you insert files into the page being generated. The syntax looks like this:
<jsp:include page="relative URL" flush="true" />
Unlike the include directive, which inserts the file at the time the JSP page is translated into a
servlet, this action inserts the file at the time the page is requested.
Following is the list of attributes associated with include action:
Attribute
Description
page
flush
The boolean attribute determines whether the included resource has its buffer
flushed before it is included.
Description
Sem- 6
ADVANCE JAVA-2
QB
class
type
Specifies the type of the variable that will refer to the object.
Description
page
Sem- 6
ADVANCE JAVA-2
QB
Following is the list of required attributes associated with setProperty action:
Attribute
Description
name
The name of the Bean that has a property to be retrieved. The Bean must have
been previously defined.
property
17.what are implicit objects? Explain any four implicit object of jsp.
-> JSP Implicit Objects are the Java objects that the JSP Container makes available to developers
in each page and developer can call them directly without being explicitly declared. JSP Implicit
Objects are also called pre-defined variables.
Sem- 6
ADVANCE JAVA-2
QB
UNIT-3
Sem- 6
ADVANCE JAVA-2
QB
d. object pooling.
EJB application is deployed on the server, so it is called server side component also.
EJB is like COM (Component Object Model) provided by Microsoft. But, it is different from Java
Bean, RMI and Web Services.
Session BeanSession bean contains business logic that can be invoked by local, remote or webservice client.
Message Driven BeanLike Session Bean, it contains the business logic but it is invoked by passing message.
Entity Bean
It encapsulates the state that can be persisted in the database. It is deprecated. Now, it is replaced
with JPA (Java Persistent API).
Sem- 6
ADVANCE JAVA-2
QB
1.Does Not Exit-The client initiates the life cycle by obtaining a reference to a stateless session
bean.the container performs any dependency injection ,and then invokes the method
@PostConstruct,if any .the client can now invoke the business methods of the bean.
2.Ready to Does Not Exit At the end of session bean like cyckle,the EJB container calls the
method ,the bean instance is then ready for garbage collection.
Callback method @postConstruct-the container invokes this method on newly contructed bean instance
after all dependency injection are completed, and before the first business method is
invoked on the enterprise bean.
@PreDestroy-these
Sem- 6
ADVANCE JAVA-2
QB
Sem- 6
ADVANCE JAVA-2
QB
An inactive stateful session bean that is set up to use the NRU (not recently used) cache-type
algorithm can time out, which moves it to the does not exist state, that is, it is removed. Prior to
removal the EJB container will call the callback method ejbRemove. If a stateful session bean set
up to use the LRU (least recently used) algorithm times out, it always moves to the passivated state,
and is not removed.
There are two states: does not exist and method-ready pool. To transition from the does not exist
state to the method-ready pool state, the following occurs: the newInstance method is invoked,
dependency injection occurs (if any), the MDB method annotated as PostConstruct (if any) or the
ejbCreate method (if present) is invoked. While in the method-ready pool state, the following
methods may be invoked: message listener method or ejbTimeout. To transition from the methodready pool state to the does not exist state, the following occurs: the MDB method annotated as
PreDestroy (if any) or the ejbRemove method (if present) is invoked .
Sem- 6
ADVANCE JAVA-2
QB
They do not represent directly shared data in the database, but they can access and
update this data.
Sem- 6
ADVANCE JAVA-2
QB
Passes a message to the listener.
Parameters:
message - the message passed to the listener
Benefits
Application Server/ EJB container provides most of the system level services like
transaction handling, logging, load balancing, persistence mechanism, exception handling
and so on. Developer has to focus only on business logic of the application.
EJB container manages life cycle of ejb instances thus developer needs not to worry about
when to create/delete ejb objects.
Sem- 6
ADVANCE JAVA-2
QB
Jave bean
1.they can be either visible or
non-visible
2.they are intended to be local to
single process on the client side.
Ejb
1.they are non-visible remote
objects.
2.they are remotely executable
components deployed on the
server.
3.they use the deployment
descriptor to describe themselves
Sem- 6
ADVANCE JAVA-2
QB
javax.ejb.Stateful
Sem- 6
ADVANCE JAVA-2
QB
Attributes
UNIT-4
Sem- 6
ADVANCE JAVA-2
QB