UNIT-3-Java Servlet Programming-AJP-6TH-SEM-SUMMER-2024
UNIT-3-Java Servlet Programming-AJP-6TH-SEM-SUMMER-2024
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL
Javax.servlet
Javax.servlet.http
Advantages of Servlet:
1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage
collection, etc.
4. Secure: because it uses java language.
5. Servlet is faster than CGI as it doesn’t involve the creation of a new process for every
new request received.
6. Servlets, as written in Java, are platform independent.
Servlets can directly communicate with the CGI cannot directly communicate with the
webserver. webserver.
Servlets are less expensive than CGI. CGI is more expensive than Servlets.
Servlets can handle the cookies. CGI cannot handle the cookies.
GenericServlet HttpServlet
javax.servlet.GenericServlet javax.servlet.http.HttpServlet
public abstract
This method will return
java.util.Enumeration<java.lang.String>
Enumeration having names of all
getInitParameterNames()
init parameter names.
Example:
File: Web.xml
<web-app>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>Trupti</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>
File: MyServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class MyServlet extends HttpServlet
{ String msg;
PrintWriter out;
public void init(ServletConfig config)throws ServletException
{
msg = config.getInitParameter("name");
}
public void doGet(HttpServletRequest request , HttpServletResponse response) throws
ServletException,IOException
{ response.setContentType("text/html");
out = response.getWriter();
out.println("<h1>"+ msg +"</h1>");
}
public void destroy()
{ out.close();
}
}
<web-app>
<servlet>
<servlet-name>ServletContextDemo</servlet-name>
<servlet-class>ServletContextDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletContextDemo</servlet-name>
<url-pattern>/ServletContextDemo</url-pattern>
</servlet-mapping>
<context-param>
<param-name>name</param-name>
<param-value>DIET</param-value>
</context-param>
</web-app>
File:MyServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletContextDemo extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{ res.setContentType("text/html");
PrintWriter out=res.getWriter();
//creating ServletContext object
ServletContext context=getServletContext();
//Getting the value of the initialization parameter and printing it
String college=context.getInitParameter("name");
out.println("College name is="+college);
out.close();
}
}
ServletConfig ServletContext
Each servlet has got its own ServletContext object is only one and used by
ServletConfig object. different servlets of the application.
Get Request sends the request parameter as query Post request send the request parameters as
string appended at the end of the request. part of the http request body.
Get method is visible to every one (It will be Post method variables are not displayed in
displayed in the address bar of browser ). the URL.
Restriction on form data, only ASCII characters No Restriction on form data, Binary data is
allowed. also allowed.
String getContextPath() Returns the portion of the request URI that indicates the
context of the request.
Returns the part of this request's URL that calls the servlet.
String getServletPath()
This path starts with a "/" character and includes either the
servlet name or a path to the servlet.
String getMethod() Returns the name of the HTTP method with which this
request was made, for example GET or POST.
Returns the portion of the request URI that indicates the context of the request.
Example:
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
out.println("<p>request.getContextPath():"+request.getContextPath()+"</p>");
}
Example: we store page id or page name in the hidden field so that each
page can be uniquely identified
Advantages:
Easy to implement
It will always work whether cookie is disabled or not
Disadvantages:
Maintained at server side
Extra form submission is required on each pages
Only textual information can be used
It does not support hyperlink submission
Hidden field will be visible with GET method
User might view page source and can view hidden field
Example:
Login.html
<html>
<head>
<title>login</title>
</head>
<body>
<form action="/Session/Valid" method="POST">
<p>Login ID:<input type="text" name="login"></p>
<p>Password:<input type="text" name="pwd"></p>
<p><input type="hidden" name="session_id" value="054"> </p>
<p><input type="submit" value="Sign In"></p>
</form>
</body>
</html>
Valid.java
public class Valid extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
RequestDispatcher rd;
String login=request.getParameter("login");
String pwd=request.getParameter("pwd");
String session=request.getParameter("session_id");
if(login.equals("java") && pwd.equals("servlet"))
{
rd=request.getRequestDispatcher("Welcome");
rd.forward(request, response);
}
else
{
out.println("<p><h1>Incorrect LoginId/Password </h1></p>");
rd=request.getRequestDispatcher("/login.html");
rd.include(request, response);
}
}
}
(2) URL Rewriting in Session Managemnet
• In URL rewriting, a token or identifier is appended 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 &…
o A name and a value is separated using an equal (=) sign
o 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:
• It will always work whether cookie is disabled or not (browser independent).
• Extra form submission is not required on each pages.
Disadvantage:
• It will work only with links.
• It can send only textual information.
• URL header size constraint.
• Not Securite because name/value field will be visible with URL followed by ‘?’.
Example:
Form1.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Form1 extends HttpServlet
{
o Non-Persistent cookie
It is valid for single session only.
It is removed each time when user closes the browser.
• Cookie class
javax.servlet.http.Cookie
o This class provides the functionality of using cookies.
o It provides a lots of useful methods for cookies.
• Constructor
Cookie(String name, String value)
o constructs a cookie with a specified name and value.
• Coookie Example
Cookie c= new Cookie("id","054");
Methods of Cookies
Cookie Methods Description
void setMaxAge(int expiry) Sets the maximum age in seconds for this Cookie
void setValue(String
Assigns a new value to this Cookie.
newValue)
Advantages of Cookie
o It is a simplest technique of maintaining the state.
o Cookies are maintained at client side.
Disadvantages of Cookie
o It will not work if cookie is disabled from the browser.
o Only textual information can be set in Cookie object.
long Returns the last time the client sent a request associated with
getLastAccessedTime() this session, as the number of milliseconds.
void invalidate() Invalidates this session then unbinds any objects bound to it.
void doFilter
doFilter() method is invoked every time when
(HttpServletRequest request,
user request to any resource, to which the filter is
HttpServletResponse response,
mapped.It is used to perform filtering tasks.
FilterChain chain)
void doFilter
It passes the control to the next filter
(HttpServletRequest request,
or resource.
HttpServletResponse response)
Example:
FilterChain chain;
chain.doFilter(req, resp);//send request to next resource