C# lectures
C# lectures
on
Advanced
JAVA
UNIT-1
PREPARED BY
URVASHI SANGWAN
DEPARTMENT OF COMPUTER SCIENCE AND
ENGINEERING, VCE,ROHTAK
UNIT 1
Servlet: Servlet introduction, web terminology,
servlet API, servlet Interface, generic servlet,
Http servlet, servlet lifecycle, servlet with IDE
(eclipse, My eclipse, Net beans),servlet request,
servlet collaboration, servlet configuration,
context, attribute in servlet, session technique in
servlet, event and listener, servlet filter, CRUD,
pagination, input output stream, annotation,
single thread model, SSI;
◉ A servlet is a Java programming language class that is
used to extend the capabilities of servers that host
applications accessed by means of a request-response
programming model. Although servlets can respond to
any type of request, they are commonly used to
extend the applications hosted by web servers.
Servlet can be described as follows:
Website: static vs It is a collection of related web pages that may contain text,
dynamic images, audio and video.
HTTP Requests It is the request send by the computer to a web server that contains
all sorts of potentially interesting information.
Get vs Post It gives the difference between GET and POST request.
Container It is used in java for dynamically generating the web pages on the
server side.
Server: Web vs It is used to manage the network resources and for running the
Application program or software that provides services.
Content Type It is HTTP header that provides the description about what are you
sending to the browser.
◉ The javax.servlet and javax.servlet.http packages represent
interfaces and classes for servlet api.
◉ The javax.servlet package contains many interfaces and classes
that are used by the servlet or web container. These are not
specific to any protocol.
◉ The javax.servlet.http package contains interfaces and classes
that are responsible for http requests only.
◉ Interfaces in javax.servlet package
1) Servlet
2) ServletRequest 8) Filter
3) ServletResponse 9) FilterConfig
10) FilterChain
4) RequestDispatcher 11) ServletRequestListener
5) ServletConfig 12)ServletRequestAttributeListener
13) ServletContextListener
6) ServletContext
14) ServletContextAttributeListener
7) SingleThreadModel
◉ Servlet interface provides common behavior 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.
Methods of Servlet interface
Method Description
public void initializes the servlet. It is the life cycle method of servlet and
init(ServletConfig config) invoked by the web container only once.
public void destroy() is invoked only once and indicates that servlet is being
destroyed.
public abstract String getServerName() Returns the host name of the server that received
the request.
public int getServerPort() Returns the port number on which this request was
received.
Example of ServletRequest to display the name of the user
DemoServ.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServ extends HttpServlet{
index.html public void doGet(HttpServletRequest req,Htt
pServletResponse res)
<form action="welcome" method="ge throws ServletException,IOException
t"> {
Enter your name<input type="text" n res.setContentType("text/html");
ame="name"><br> PrintWriter pw=res.getWriter();
<input type="submit" value="login">
</form> String name=req.getParameter("name");
//will return value
pw.println("Welcome "+name);
pw.close();
}}
◉ RequestDispatcher in Servlet:
The RequestDispatcher 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
:F
ServletException,java.io.IOException:Forwards a request
from a servlet to another resource (servlet, JSP file, or
HTML file) on the server.
2. public void include(ServletRequest request,ServletResponse
response)throws ServletException,java.io.IOException:Includes the
content of a resource (servlet, JSP page, or HTML file) in the response.
SendRedirect in servlet:
The sendRedirect() method of HttpServletResponse interface can be used
to redirect response to another resource, it may be servlet, jsp or html file.
It accepts relative as well as absolute URL.
It works at client side because it uses the url bar of the browser to make
another request. So, it can work inside and outside the server
Difference between forward() and sendRedirect() method
There are many differences between the forward() method of
RequestDispatcher and sendRedirect() method of HttpServletResponse
interface. They are given below:
forward() method sendRedirect() method
response.sendRedirect("http://www.javatpoint.com");
◉ 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 interface
1. public String getInitParameter(String
name):Returns the parameter value for the
specified parameter name.
2. public Enumeration
getInitParameterNames():Returns an
enumeration of all the initialization parameter
names.
3. public String getServletName():Returns the
name of the servlet.
4. public ServletContext
getServletContext():Returns an object of
ServletContext.
◉ How to get the object of ServletConfig
getServletConfig() method of Servlet interface
returns the object of ServletConfig.
◉ Syntax of getServletConfig() method
public ServletConfig getServletConfig();
◉ Example of getServletConfig() method
ServletConfig config=getServletConfig();
//Now we can call the methods of ServletConfig inte
rface
Syntax to provide the initialization parameter for a servlet
<init-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</init-param>
......
</servlet>
</web-app>
◉ An object of ServletContext is created by the web
container at time of deploying the project. This object
can be used to get configuration information from
web.xml file. There is only one ServletContext object
per web application.
◉ If any information is shared to many servlet, it is better
to provide it from the web.xml file using the <context-
param> element.
◉ Advantage of ServletContext:
ServletContext application=getServletConfig().getServletContext();
◉ request scope
◉ session scope
◉ application scope
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
1. Cookies in Servlet :
Types of Cookie:
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.
Cookie class:
javax.servlet.http.Cookie class provides the functionality of using cookies. It
provides a lot of useful methods for cookies.
Constructor Description
public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.
public String getName() Returns the name of the cookie. The name cannot be changed after creation.
3. 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(&). When the user clicks the hyperlink, the parameter
name/value pairs will be passed to the server. From a Servlet, we can use
getParameter() method to obtain a parameter value.
Advantage of URL Rewriting
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 to initialize
the filter.
public void doFilter(HttpServletRequest doFilter() method is invoked every time when user request
request,HttpServletResponse response, FilterChain to any resource, to which the filter is mapped.It is used to
chain) perform filtering tasks.
public void destroy() This is invoked only once when filter is taken out of the
service.
2) FilterChain interface
ServletInputStream sin=request.getInputStream();
ServletOutputStream class:
ServletOutputStream out=response.getOutputStream();
The ServletOutputStream class provides print() and println() methods that are
overloaded.
1. void print(boolean b){}
2. void print(char c){}
3. void print(int i){}
4. void print(long l){}
5. void print(float f){}
6. void print(double d){}
7. void print(String s){}
8. void println{}
9. void println(boolean b){}
10. void println(char c){}
◉ Annotation represents the metadata. If you use
annotation, deployment descriptor (web.xml file)
is not required. But you should have tomcat7 as it
will not run in the previous versions of tomcat.
@WebServlet annotation is used to map the servlet
with the specified name.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServ
throws ServletExceptio
let;
n, IOException {
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletReq
uest;
response.setContentType("text/html
import javax.servlet.http.HttpServletRes
");
ponse;
PrintWriter out=response.getWriter(
);
@WebServlet("/Simple")
public class Simple extends HttpServlet {
out.print("<html><body>");
out.print("<h3>Hello Servlet</h3>");
private static final long serialVersionU
ID = 1L;
out.print("</body></html>");
}
protected void doGet(HttpServletReques
}
t request, HttpServletResponse response)
◉ The servlet programmer should implement
SingleThreadModel interface to ensure that servlet can
handle only one request at a time. It is a marker
interface, means have no methods.
◉
This interface is currently deprecated since Servlet API
2.4 because it doesn't solves all the thread-safety issues
such as static variable and session attributes can be
accessed by multiple threads at the same time even if
we have implemented the SingleThreadModel interface.
So it is recommended to use other means to resolve
these thread safety issues such as synchronized block
etc.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.SingleThreadModel;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;