JAVA (QuestionBank)
JAVA (QuestionBank)
The web container maintains the life cycle of a servlet instance. Let's see the life cycle of
the servlet:
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 a servlet after loading the servlet class.
The servlet instance is created only once in the servlet life cycle.
public void init(ServletConfig config) throws ServletException
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
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()
Different between Servlet and jsp
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.
index.html
1. <form action="servlet1" method="post">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>
FirstServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doPost(HttpServletRequest request, HttpServletResponse response){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. Cookie ck=new Cookie("uname",n);//creating cookie object
18. response.addCookie(ck);//adding cookie in the response
19.
20. //creating submit button
21. out.print("<form action='servlet2'>");
22. out.print("<input type='submit' value='go'>");
23. out.print("</form>");
24.
25. out.close();
26.
27. }catch(Exception e){System.out.println(e);}
28. }
29. }
GenericServlet class
1. GenericServlet class
2. Methods of GenericServlet class
3. Example of GenericServlet class
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It
provides the implementation of all the methods of these interfaces except the service
method.
Servlet Filter
1. Filter
2. Usage of Filter
3. Advantage of Filter
4. Filter API
1. Filter interface
2. FilterChain interface
3. FilterConfig interface
5. Simple Example of Filter
Usage of Filter
Advantage of Filter
1. Filter is pluggable.
2. One filter don't have dependency onto another resource.
3. Less Maintenance
Filter API
Like servlet filter have its own API. The javax.servlet package contains the three
interfaces of Filter API.
1. Filter
2. FilterChain
3. FilterConfig
1) Filter interface
For creating any filter, you must implement the Filter interface. Filter interface provides
the life cycle methods for a filter.
Method Description
public void init(FilterConfig config) init() method is invoked only once. It is used t
initialize the filter.
public void doFilter(HttpServletRequest doFilter() method is invoked every time when use
request,HttpServletResponse response, request to any resource, to which the filter i
FilterChain chain) mapped.It is used to perform filtering tasks.
public void destroy() This is invoked only once when filter is taken out o
the service.
2) FilterChain interface
The object of FilterChain is responsible to invoke the next filter or resource in the
chain.This object is passed in the doFilter method of Filter interface.The FilterChain
interface contains only one method:
1. <web-app>
2.
3. <filter>
4. <filter-name>...</filter-name>
5. <filter-class>...</filter-class>
6. </filter>
7.
8. <filter-mapping>
9. <filter-name>...</filter-name>
10. <url-pattern>...</url-pattern>
11. </filter-mapping>
12.
13. </web-app>
For mapping filter we can use, either url-pattern or servlet-name. The url-pattern
elements has an advantage over servlet-name element i.e. it can be applied on servlet,
JSP or HTML.
index.html
1. <a href="servlet1">click here</a>
MyFilter.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3.
4. import javax.servlet.*;
5.
6. public class MyFilter implements Filter{
7.
8. public void init(FilterConfig arg0) throws ServletException {}
9.
10. public void doFilter(ServletRequest req, ServletResponse resp,
11. FilterChain chain) throws IOException, ServletException {
12.
13. PrintWriter out=resp.getWriter();
14. out.print("filter is invoked before");
15.
16. chain.doFilter(req, resp);//sends request to next resource
17.
18. out.print("filter is invoked after");
19. }
20. public void destroy() {}
21. }
HelloServlet.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3.
4. import javax.servlet.ServletException;
5. import javax.servlet.http.*;
6.
7. public class HelloServlet extends HttpServlet {
8. public void doGet(HttpServletRequest request, HttpServletResponse response)
9. throws ServletException, IOException {
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. out.print("<br>welcome to servlet<br>");
15.
16. }
17.
18. }
web.xml
For defining the filter, filter element of web-app must be defined just like servlet.
1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>HelloServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <filter>
14. <filter-name>f1</filter-name>
15. <filter-class>MyFilter</filter-class>
16. </filter>
17.
18. <filter-mapping>
19. <filter-name>f1</filter-name>
20. <url-pattern>/servlet1</url-pattern>
21. </filter-mapping>
22.
23.
24. </web-app>
Assignment 2
Q1. What is Servlet
63.7M
1.3K
OOPs Concepts in Java
o Servlet is a technology which is used to create a web application.
o Servlet is an API that provides many interfaces and classes including
documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic
web page.
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database. There are four types of JDBC drivers:
o Native Driver,
o Thin Driver
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.
The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is based
on the X/Open SQL Call Level Interface. The java.sql package contains classes and interfaces
for JDBC API.
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.
In Java 8, the JDBC-ODBC Bridge has been removed.
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.
Q8. What are the uses of Connection, Statement and Result set?
JSP Predefined Variables
To simplify code in JSP expressions and scriptlets, you are supplied with eight
automatically defined variables, sometimes called implicit objects. The available
variables are request, response, out, session, application, config, pageContext,
and page. Details for each are given below.
request
This is the HttpServletRequest associated with the request, and lets you look at the
request parameters (via getParameter), the request type (GET, POST, HEAD, etc.), and
the incoming HTTP headers (cookies, Referer, etc.). Strictly speaking, request is
allowed to be a subclass of ServletRequest other than HttpServletRequest, if the
protocol in the request is something other than HTTP. This is almost never done in
practice.
response
This is the HttpServletResponse associated with the response to the client. Note that,
since the output stream (see out below) is buffered, it is legal to set HTTP status codes
and response headers, even though this is not permitted in regular servlets once any
output has been sent to the client.
out
This is the PrintWriter used to send output to the client. However, in order to make
the response object (see the previous section) useful, this is a buffered version
of PrintWriter called JspWriter. Note that you can adjust the buffer size, or even turn
buffering off, through use of the buffer attribute of the page directive. This was
discussed in Section 5. Also note that out is used almost exclusively in scriptlets, since
JSP expressions automatically get placed in the output stream, and thus rarely need to
refer to out explicitly.
session
This is the HttpSession object associated with the request. Recall that sessions are
created automatically, so this variable is bound even if there was no incoming session
reference. The one exception is if you use the session attribute of the page directive
(see Section 5) to turn sessions off, in which case attempts to reference the session
variable cause errors at the time the JSP page is translated into a servlet.
application
This is the ServletContext as obtained via getServletConfig().getContext().
config
This is the ServletConfig object for this page.
pageContext
page
This is simply a synonym for this, and is not very useful in Java. It was created as a
placeholder for the time when the scripting language could be something other than
Java.
o page directive
o include directive
o taglib directive
<%@ directive attribute="value" %>
The page directive defines attributes that apply to an entire JSP page.
<%@ page attribute="value" %>
Attributes of JSP page directive
o import
o contentType
o extends
o info
o buffer
o language
o isELIgnored
o isThreadSafe
o autoFlush
o session
o pageEncoding
o errorPage
o isErrorPage
1)import
The import attribute is used to import
class,interface or all the members of a
package.It is similar to import keyword in
java class or interface.
2)contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type
of the HTTP response.The default value is "text/html;charset=ISO-8859-1".
3)extends
The extends attribute defines the parent class that will be inherited by the generated
servlet.It is rarely used.
4)info
This attribute simply sets the information of the JSP page which is retrieved later by
using getServletInfo() method of Servlet interface.
1. <html>
2. <body>
3.
4. <%@ page info="composed by Sonoo Jaiswal" %>
5. Today is: <%= new java.util.Date() %>
6.
7. </body>
8. </html>
The web container will create a method getServletInfo() in the resulting servlet.For
example:
1. public String getServletInfo() {
2. return "composed by Sonoo Jaiswal";
3. }
5)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
1. <html>
2. <body>
3.
4. <%@ page buffer="16kb" %>
5. Today is: <%= new java.util.Date() %>
6.
7. </body>
8. </html>
6)language
The language attribute specifies the scripting language used in the JSP page. The
default value is "java".
7)isELIgnored
We can ignore the Expression Language
(EL) in jsp by the isELIgnored attribute.
By default its value is false i.e.
Expression Language is enabled by
default. We see Expression Language
later.
<%@ page isELIgnored="true" %>//Now EL will be ignored
8)isThreadSafe
Servlet and JSP both are
multithreaded.If you want to control this
behaviour of JSP page, you can use
isThreadSafe attribute of page
directive.The value of isThreadSafe
value is true.If you make it false, the web
container will serialize the multiple
requests, i.e. it will wait until the JSP
finishes responding to a request before
passing another request to it.If you make
the value of isThreadSafe attribute like:
<%@ page isThreadSafe="false" %>
The web container in such a case, will generate the servlet as:
1. public class SimplePage_jsp extends HttpJspBase
2. implements SingleThreadModel{
3. .......
4. }
9)errorPage
The errorPage attribute is used to define the error page, if exception occurs in the
current page, it will be redirected to the error page.
1. //index.jsp
2. <html>
3. <body>
4.
5. <%@ page errorPage="myerrorpage.jsp" %>
6.
7. <%= 100/0 %>
8.
9. </body>
10. </html>
10)isErrorPage
The isErrorPage attribute is used to declare that the current page is the error page.
Note: The exception object can only be used in the error page.