Web Application:-A Web Application Is Nothing But A Web Site. A Web Application Can Be Thought of As A Collection of Two Types of Resources 1
Web Application:-A Web Application Is Nothing But A Web Site. A Web Application Can Be Thought of As A Collection of Two Types of Resources 1
A web application can be thought of as a collection of two types of resources 1. Static Resources: - Normally non-executable resources.
A web client can ask for any static resources by just specifying the URL. Web server simply returns the specified resources to the client without doing any processing. It May be:I. HTML II. Images/Audio and video files III. Applets IV. Documents / spreadsheet /text files etc.
Problems in CGI:
There are many problems in CGI technology: 1. If number of client increased, response time very less. 2. For each request, it starts a process. Web server is limited to start process. 3. It uses plateform dependent language e.g. C,C++,perl.
Now let us take a close look how HTTP helps to communicate between a web server and a web browser. There are generally four stages of a simple web transaction: 1. The client opens a connection to the server: First, the client opens a TCP/IP connection to the server. By default, the connection on the server is made to port 80, unless or otherwise specified. 2. The client makes a request to the server: Let us assume that the web browser makes a request to retrieve an HTML file. For this, the user enters the Required URL into the web browser. This request is broken into three parts: the request method, the source Name and the protocol. 3. The server responds to the request: The server gets the request from the browser. The server responds with a status code, various header files and If possible, contents of the request. 4. Connection is closed Either the server or the client may close the connection. The server generally terminates the connection after The response has been sent. Similarly, a browser often closes the connection once the complete response has Been received.
HTTP Request Method GET POST HEAD TRACE PUT DELETE OPTIONS
Description Asks to get the resource at the requested URL. Asks the server to accept the body info attached. It like a GET with extra info sent with the request. Asks for only the header part of whatever a GET would return. Just like GET but with no body. Asks for the loopback of the request message, for testing or troubleshooting. Says to put the enclosed info (the body) at the requested URL. Says to delete the resource at the requested URL. Asks for a list of the HTTP methods to which the thing at the request URL can respond
Content Type:
Content Type is also known as MIME (Multipurpose internet Mail Extension) Type.It is a HTTP header that provides the description about what are you sending to the browser.There are many content types: text/html text/plain application/msword application/vnd.ms-excel application/jar application/pdf application/octet-stream application/x-zip images/jpeg vedio/quicktime etc.
What is a Servlet :1. A servlet is simply a java program that runs on the server. 2. Servlets are designed to accept a response from a client (usually a web browser), process that request,
3. 4.
5.
6. 7.
and return a response to the client. A good analogy for a servlet is a non-visual applet that runs on a server. A Servlet can be thought of as a server side applet. Servlets are loaded and executed by a web server in the same manner in which applets are loaded and executed by a web browser. Thus, we can say that Servlet is a server side software component, written in Java that dynamically extends the functionality of a server. With Servlet, Web developers can create fast and efficient server-side applications in Java instead of using CGI and Perl. A servlets work is done behind the scene on the server. The results of the Servlet are returned to the client usually in the form of HTML.
Advantage of Servlet:
Servlet Overview:A Java Servlet is a Java object that responds to HTTP requests. It runs inside a Servlet container. Here is an illustration of that:
Web applications with multiple servlets inside a Java Servlet container A Java web application can contain other components than servlets. It can also contain Java Server Pages (JSP), Java Server Faces (JSF) and Web Services. This tutorial is about Java Servlets only, though.
HTTP Request and Response:The browser sends an HTTP request to the Java web server. The web server checks if the request is for a servlet. If it is, the servlet container is passed the request. The servlet container will then find out which servlet the request is for, and activate that servlet. The servlet is activated by calling the Servlet.service() method.
Once the servlet has been activated via the service () method, the servlet processes the request, and generates a response. The response is then sent back to the browser.
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 a servlet after loading the servlet class. The servlet instance is created only once in the servlet life cycle. 3) init method is invoked: The init method is called by the servlet container after the servlet class has been instantiated. The servlet container calls this method exactly once to indicate to the servlet that the servlet is being placed into service. The init method must complete successfully before the servlet can receive any requests. You can override this method to write initialization code that needs to run only once, such as loading a database driver, initializing values, and so on. In other cases, you normally leave this method blank. The signature of this method is as follows: public void init(ServletConfig config) throws ServletException The init method is important also because the servlet container passes a ServletConfig object, which contains the configuration values stated in the web.xml file for this application. 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
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()
2)Create a Servlet:
//DemoServlet.java
import import import public public throws javax.servlet.http.*; javax.servlet.*; java.io.*; class DemoServlet extends HttpServlet{ void doGet(HttpServletRequest req,HttpServletResponse res) ServletException,IOException{ res.setContentType("text/html"); PrintWriter pw=res.getWriter(); pw.println("<html><body>"); pw.println("Welcome to servlet"); pw.println("</body></html>");
} }
<servlet-name> is sub element of <servlet> represents the name of the servlet. <servlet-class> is sub element of <servlet> represents the class of the servlet. <servlet-mapping> is sub element of <web-app>. It is used to map the servlet. <url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the servlet.
5)Start Server:
To start Apache Tomcat server JAVA_HOME and JRE_HOME must be set in Environment variables. Go to My Computer properties Click on advanced tab then environment variables Click on the new tab of user variable Write JAVA_HOME in variable name and paste the path of jdk folder in variable value Ok Ok Ok
2.
javax.servlet.http :-
Servlet Interface:-
Servlet interface is the central abstraction of the java servlet technology. Every servlet you write must implements this interface either directly or indirectly (By subclassing the GenericServlet ot HttpServlet class). It is collection of empty method signatures.
There are two main implementation of this interface. - GenericServlet :- used to create protocol independent servlet - HttpServlet :- used to create Http protocol specific servlet Servlet
|
GenericServlet HttpServlet
|
(Protocol independent) MyServlet
Examples:package ServletBasic; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.*; public class ServletDemo implements Servlet { public void destroy() {
|
MyServlet (Http Specific)
} public ServletConfig getServletConfig() { return null; } public String getServletInfo() { return null; } public void init(ServletConfig arg0) throws ServletException { } public void service(ServletRequest req, ServletResponse res)throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("Hello, world!"); out.close(); } } <web-app > <servlet> <servlet-name>ServletDemo</servlet-name> <servlet-class>ServletBasic.ServletDemo</servlet-class> </servlet> <servlet-mapping> <servlet-name>ServletDemo</servlet-name> <url-pattern>/ServletDemo</url-pattern> </servlet-mapping> </web-app>
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. 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.
Preserving The ServletConfig :You may want to have access to the ServletConfig object from the service() method, when you are servicing the user. In this case you need to preserve the ServletConfig object to a class level variable. This is not difficult. You need to create a ServletConfig object variable and set it to the ServletConfig object returned by the servlet container in init() method.
package ServletBasic; import import import public java.io.IOException; java.io.PrintWriter; javax.servlet.*; class PreserveServletConfigInfo implements Servlet { ServletConfig config; public void destroy() { } public ServletConfig getServletConfig() { return null;} public String getServletInfo() {return null; } public void init(ServletConfig arg0) throws ServletException { config = arg0; } public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException { PrintWriter out = arg1.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>hiiiiiiiii</title>"); out.println("</head>"); out.println("<body>"); out.println("Servlet Name :-" + config.getServletName()); out.println("<body>"); out.println("</html>"); } } <web-app > <servlet> <servlet-name>PreserveServletConfigInfo</servlet-name> <servlet-class> ServletBasic.PreserveServletConfigInfo</servlet-class> </servlet> <servlet-mapping> <servlet-name>PreserveServletConfigInfo</servlet-name> <url-pattern>/PreserveServletConfigInfo</url-pattern> </servlet-mapping> </web-app>
Obtaining Configuration Information:<web-app > <servlet> <servlet-name>ObtainConfInfo</servlet-name> <servlet-class> ServletBasic.ObtainConfInfo</servlet-class> <init-param> <param-name> Email</param-name> <param-value>[email protected]</param-value> </init-param> <init-param> <param-name> Contact Number </param-name> <param-value>9660242550</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>ObtainConfInfo</servlet-name> <url-pattern>/ObtainConfInfo</url-pattern> </servlet-mapping> </web-app> package ServletBasic; import import import import java.io.IOException; java.io.PrintWriter; java.util.Enumeration; javax.servlet.*;
public class ObtainConfInfo implements Servlet { ServletConfig config; public void destroy() { } public ServletConfig getServletConfig() { return null; } public String getServletInfo() { return null; } public void service(ServletRequest req,ServletResponse res) throws ServletException, IOException { Enumeration att = config.getInitParameterNames(); response.setContentType("html/text"); PrintWriter printWriter=response.getWriter(); while (att.hasMoreElements()) { String par = (String) att.nextElement(); printWriter.println("Param Name :-"+ par+"<BR>"); printWriter.println("Param value:-"+ config.getInitParameter(par)+"<BR>"); } } public void init(ServletConfig servletConfig) throws ServletException { config=servletConfig; Enumeration att = servletConfig.getInitParameterNames(); while (att.hasMoreElements()) { String par = (String) att.nextElement(); System.out.println("Param Name :-" + par); System.out.println("Param value :-"+ servletConfig.getInitParameter(par)); } } } Output:Param Name: - Email Param Value: - [email protected] Param Name: - contact Number`
All servlets belong to one servlet context. It can only be called at context initialization time. 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. A servlet can also bind an object attribute into context by name
ServletContext context= config.getServletContext(); context.setAttribute("password", "121212");
Any object bound into context is available to any other servlet that is the part of the same application
For Example: ServletContext context=getServletConfig().getServletContext(); 2. getServletContext() method of GenericServlet class returns the object of ServletContext. For Example: ServletContext context=getServletContext();
Retrieving Servlet Context Information:package ServletBasic; import javax.servlet.*; import java.util.Enumeration; import java.io.IOException; public class ContextDemoServlet implements Servlet { ServletConfig servletConfig; public void init(ServletConfig config) throws ServletException { servletConfig = config; } public void destroy() { } public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { ServletContext servletContext = servletConfig.getServletContext(); Enumeration attributes = servletContext.getAttributeNames(); while (attributes.hasMoreElements()) { String attribute = (String) attributes.nextElement(); System.out.println("Attribute name : " + attribute); System.out.println("Attribute value : " + servletContext.getAttribute(attribute)); } System.out.println("Major version : " + servletContext.getMajorVersion()); System.out.println("Minor version : " + servletContext.getMinorVersion()); System.out.println("Server info : " + servletContext.getServerInfo()); } public String getServletInfo() { return null; } public ServletConfig getServletConfig() { return null; } } <servlet> <servlet-name>ContextDemoServlet</servlet-name> <servlet-class> ServletBasic.ContextDemoServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ContextDemoServlet</servlet-name> <url-pattern>/ContextDemoServlet</url-pattern> </servlet-mapping>
DisplayAttributesServlet
package ServletBasic; import javax.servlet.*; import java.io.IOException; import java.util.Enumeration; public class ResponseDemoServlet implements Servlet { ServletConfig servletConfig; public void init(ServletConfig config) throws ServletException { servletConfig = config; } public void destroy() {
} public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { ServletContext servletContext = servletConfig.getServletContext(); Enumeration attributes = servletContext.getAttributeNames(); while (attributes.hasMoreElements()) { String attribute = (String) attributes.nextElement(); System.out.println("Attribute name : " + attribute); System.out.println("Attribute value : "+ servletContext.getAttribute(attribute)); } } public String getServletInfo() { return null; } public ServletConfig getServletConfig() { return null; }
Output :Attribute Attribute Attribute Attribute Attribute Attribute name value name value name value : : : : : : javax.servlet.context.tempdir C:\123data\JavaProjects\JavaWebBook\work\localhost_8080 password dingdong sun.servlet.workdir C:\123data\JavaProjects\JavaWebBook\work\localhost_8080
ServletRequest Interface: Whenever the web container receives a request from the web browser, it creates a servlet request and
identifies which servlet needs to be invoked based on the URL mapping, calls the service method of the servlet and passes the servlet request object as parameter. ServletRequest interface encapsulates the communication from the client to the server.
ServletResponse Interface:
This interface represents the response from the servlet to a web client.
Methods of ServletRequest Interface:
void flushBuffer() int getBufferSize() String getCharacterEncoding() String getContentType() java.util.Locale getLocale()
ServletOutputStream getOutputStream()
Forces any content in the buffer to be written to the client. Returns the actual buffer size used for the response. Returns the name of the character encoding (MIME charset) used for the body sent in this response. Returns the content type used for the MIME body sent in this response. Returns the locale specified for this response using the setLocale(java.util.Locale) method. Returns a ServletOutputStream suitable for writing binary data in the response.
Returns a PrintWriter object that can send character text to the client. Returns a boolean indicating if the response has been committed.
java.io.PrintWriter getWriter() Boolean isCommitted() void reset() void resetBuffer() void setBufferSize(int size) void
Clears any data that exists in the buffer as well as the status code and headers. Clears the content of the underlying buffer in the response without clearing headers or status code. Sets the preferred buffer size for the body of the response. Sets the character encoding (MIME charset) of the response being sent to
setCharacterEncoding(String charset) the client, for example, to UTF-8. void setContentLength(int len) void setContentType(String type)
Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length header. Sets the content type of the response being sent to the client, if the response has not been committed yet.
void setLocale(java.util.Locale loc) Sets the locale of the response, if the response has not been committed yet.
SingleThreadModel:Servlet in java application can be accessed by multiple users at a same time. SingleThreadModel is deprecated. Although it is not good thing to use SingleThreadModel in servlet, we can use it to restrict access of more than one user at a same time. SingleThreadModel is useful in case you required to process one request at one time, no other can access that process when servlet is in use. To make servlet interface. a Single thread, need to implement SingleThreadModel
The example is given of SingleThreadModel in Servlet. import javax.servlet.SingleThreadModel; import javax.servlet.http.HttpServlet; public class TestServlet extends HttpServlet implements SingleThreadModel { }
GenericServlet : It is an abstract class and implements Servlet interface, ServletConfig interface and Serializable interface. Writing servlet by extending GenericServlet is easy comparison to creating a servlet by implementing the Servlet interface. Because in the case of Servlet Interface we have to provide all the methods implementation. Even if we use or not. In GenericServlet service method is abstract . so when we extend this class to create a servlet then we must provide the implementation of this method. We write our code in this method. Example :import javax.servlet.*; import java.io.IOException; import java.io.PrintWriter; public class SimpleServlet extends GenericServlet { public void service(ServletRequest req,ServletResponse res)throws ServletException, IOException { PrintWriter out = res.getWriter(); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>"); out.println("Extending GenericServlet"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("Extending GenericServlet makes your code simpler."); out.println("</BODY>"); out.println("</HTML>"); } }
javax.servlet.http : This package is used to develop servlet that supports the HTTP protocol.
This package is much rich and more convenient to use rather than javax.servlet package. The classes and interfaces of this package are derived from the javax.servlet package. This package supports the cookie, session concepts. HttpServlet Class : This class extends the GenericServlet. It is specific to the http protocol. It is the most used class in the servlet. It is present in the javax.servlet.http package. It contains the methods such as doGet(),doPost(),doDelete(),doHeader() etc. Methods are: doGet() doPost() doDelete() doHeader() doPut() service() It has two overridden version of service() method protected void service(HttpServletRequest req, HttpServletResponse resp) public void service(ServletRequest req, ServletResponse res)
First client request comes to the public void service() method It then dispatches client requests to the protected service method. protected service() method receives HTTP requests from the public service method and dispatches them to the do...() methods defined in this class.
So the calling functions flow is like this Client public service() protected service doXXX() doGet()
o o o o o
This method is used for handling the get request. It is called by the service methods. This supports the HTTP HEAD request. HEAD request is a GET request. It returns no body. It returns the request header fields.
o o
In these methods values passing from form to the server get added to the URL. It allows limited data to be passed
doPost ()
o o o o o
This method is used for handling the post request. It is called by the service methods. In this method values passing from to the server get added to the body instead of the URL. Using the HTTP post method the user can send data of unlimited length to the Web server. It is used mostly as the information sending is more secure such as credit card, debit card information.
Sends an HTTP request to the server using the POST method:When the user clicks the Submit button to submit the form, the browser sends an HTTP request to the server using the POST method. The web server then passes this request to the servlet and the doPost method of the servlet is invoked. Using the POST method in a form, the parameter name/value pairs of the form are sent in the request body. For example, if you use the below form as an example and enter Ankit as the value for firstName and Jain as the value for lastName, you will get the following result in the request body:
<html> <head> <title> Ankit First HTTP Servlet DEMO </title> </head> <body> <FORM ACTION="Register" METHOD="POST"> <INPUT TYPE=TEXT Name="firstName"> <INPUT TYPE=TEXT Name="lastName"> <INPUT TYPE=SUBMIT> </FORM> </body> </html>
sendRedirect() method:
The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource,
it may be servlet, jsp or html file. It can accept relative URL. This method can work inside and outside the server as it uses the URL bar of the browser.
RequestDispatcher Interface:
The RequestDispacher 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.
Methods of RequestDispatcher:
1. public void forward(ServletRequest request,ServletResponse response)throws
ServletException,java.io.IOException:Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP page, or HTML file) in the response.
Program of RequestDispatcher:
index.html
<form action="servlet1" method="post"> Name:<input type="text" name="userName" /><br/> Password:<input type="password" name="userPass" /><br/> <input type="submit" value="login" /> </form>
public class Login extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); String n=req.getParameter("userName"); String p=req.getParameter("userPass"); if(p.equals("servlet")){ RequestDispatcher rd=req.getRequestDispatcher("servlet2"); rd.forward(req, res); } else{ out.print("Sorry UserName or Password Error!"); RequestDispatcher rd=req.getRequestDispatcher("/index.html"); rd.include(req, res); } } }
WelcomeServlet.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class WelcomeServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n = request.getParameter("userName"); out.print("Welcome " + n); } }
web.xml
<web-app> <servlet> <servlet-name>Login</servlet-name> <servlet-class>Login</servlet-class> </servlet> <servlet> <servlet-name>WelcomeServlet</servlet-name> <servlet-class>WelcomeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Login</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>WelcomeServlet</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
Attribute in Servlet:
An attribute is an object that can be set,get or removed from one of the following scopes: 1. request scope
context.
public class DemoServlet1 extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse res) { try{ res.setContentType("text/html"); PrintWriter out=res.getWriter(); ServletContext context=getServletContext(); context.setAttribute("company","IBM"); out.println("Welcome to first servlet"); out.println("<a href='servlet2'>visit</a>"); out.close(); }catch(Exception e){out.println(e);} }}
DemoServlet2.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
public class DemoServlet2 extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse res) { try{ res.setContentType("text/html"); PrintWriter out=res.getWriter(); ServletContext context=getServletContext(); String n=(String)context.getAttribute("company"); out.println("Welcome to "+n); out.close(); }catch(Exception e){out.println(e);} }}
web.xml
<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>DemoServlet1</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet> <servlet-name>s2</servlet-name> <servlet-class>DemoServlet2</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> </web-app>
1) Cookies:
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.
javax.servlet.http.Cookie class:
javax.servlet.http.Cookie class provides the functionality of using cookies.
Constructor:
Cookie(String name, String value): Constructs a cookie with a specified name and value.
response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies
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
<form action="servlet1" method="post"> Name:<input type="text" name="userName"/><br/> <input type="submit" value="go"/> </form>
FirstServlet.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
public class FirstServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); Cookie ck=new Cookie("uname",n); response.addCookie(ck); out.print("<form action='servlet2'>"); out.print("<input type='submit' value='go'>"); out.print("</form>"); out.close();
}catch(Exception e){System.out.println(e);} } }
SecondServlet.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); Cookie ck[]=request.getCookies(); out.print("Hello "+ck[0].getName()); out.close(); }catch(Exception e){System.out.println(e);} }
web.xml
<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet> <servlet-name>s2</servlet-name> <servlet-class>SecondServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>/servlet2</url-pattern>
</servlet-mapping> </web-app>
FirstServlet.java
public class FirstServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); out.print("<form action='servlet2'>"); out.print("<input type='hidden' name="uname" value='"+n+"'>"); out.print("<input type='submit' value='go'>"); out.print("</form>"); out.close(); }catch(Exception e){System.out.println(e);} } }
SecondServlet.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("uname"); out.print("Hello "+n); out.close(); }catch(Exception e){System.out.println(e);}
web.xml
<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet> <servlet-name>s2</servlet-name> <servlet-class>SecondServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> </web-app>
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.
FirstServlet.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
public class FirstServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ try{
response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); out.print("<a href='servlet2?uname="+n+"'>visit</a>"); out.close(); }catch(Exception e){System.out.println(e);} } }
SecondServlet.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("uname"); out.print("Hello "+n); out.close(); }catch(Exception e){System.out.println(e);} }
web.xml
<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping>
4)HttpSession interface:
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.
request or, if there is no current session and create is true, returns a new session.
since midnight January 1, 1970 GMT. 3. public long getLastAccessedTime():Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any objects bound to it.
FirstServlet.java
import java.io.*;
public class FirstServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); HttpSession session=request.getSession(); session.setAttribute("uname",n); out.print("<a href='servlet2'>visit</a>"); out.close(); }catch(Exception e){System.out.println(e);} } }
SecondServlet.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session=request.getSession(false); String n=(String)session.getAttribute("uname"); out.print("Hello "+n); out.close(); }catch(Exception e){System.out.println(e);} }
web.xml
<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet> <servlet-name>s2</servlet-name> <servlet-class>SecondServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> </web-app>
Filter:
A filter is an object that is used to performed filtering tasks such as conversion,log maintain,compression,encryption and decryption,input validation etc.A filter is invoked at the preprocessing and postprocessing of a request.
Uses of Filter:
recording all incoming requests logs the IP addresses of the computers from which the requests originate conversion data compression encryption and decryption input validation etc.
Advantage of Filter:
1. Filter is pluggable. 2. One filter don't have dependency onto another resource.
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.
1. public void init(FilterConfig config): init() method is invoked only once it is used to initialize the filter. 2. public void doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain):
doFilter() method is invoked every time when user request to any resource, to which the filter is mapped.It is used to perform filtering tasks.
3. public void destroy():This is invoked only once when filter is taken out of 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. public void doFilter(HttpServletRequest request, HttpServletResponse response): it passes the control
3) FilterConfig interface
For creating any filter, you must implement the Filter interface.Filter interface provides the life cycle methods for a filter.
1. public void init(FilterConfig config): init() method is invoked only once it is used to initialize the filter. 2. public String getInitParameter(String parameterName): Returns the parameter value for the specified
parameter name. 3. public java.util.Enumeration getInitParameterNames(): Returns an enumeration containing all the parameter names.
4. public ServletContext getServletContext(): Returns the ServletContext object.
MyFilter.java
import java.io.*; import javax.servlet.*; public class MyFilter implements Filter{ public void init(FilterConfig arg0) throws ServletException {} public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { PrintWriter out=res.getWriter(); chain.doFilter(req, res); out.print("<br/>filter invoked.."); } public void destroy() {} }
FirstServlet.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
public void doGet(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.print("Welcome servlet"); out.close(); }catch(Exception e){System.out.println(e);} } }
web.xml
<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <filter> <filter-name>f1</filter-name> <filter-class>MyFilter</filter-class> </filter> <filter-mapping> <filter-name>f1</filter-name> <url-pattern>/servlet1</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
import java.io.*; import javax.servlet.*; public class MyFilter implements Filter{ static int count=0; public void init(FilterConfig arg0) throws ServletException {} public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { PrintWriter out=res.getWriter(); long before=System.currentTimeMillis(); chain.doFilter(request,response); long after=System.currentTimeMillis(); out.print("<br/>Total response time "+(after-before)+" miliseconds"); out.close(); } public void destroy() {} }
@WebServlet("/Simple") public class Simple extends HttpServlet { private static final long serialVersionUID = 1L;