java web UNIT 2 servlets
java web UNIT 2 servlets
INTRODUCTION TO SERVLETS
There are many interfaces and classes in the Servlet API such as Servlet,
GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc.
Disadvantages of CGI
There are many problems in CGI technology:
1. If the number of clients increases, it takes more time for sending the
response.
2. For each request, it starts a process, and the web server is limited to start
processes.
3. It uses platform dependent language e.g. C, C++, perl.
HTTP Requests
The request sent by the computer to a web server, contains all sorts of
potentially interesting information; it is known as HTTP requests.
The HTTP client sends the request to the server in the form of request
message which includes following information:
o The Request-line
o The analysis of source IP address, proxy and port
o The analysis of destination IP address, protocol, port and host
o The Requested URI (Uniform Resource Identifier)
o The Request method and Content
o The User-Agent header
o The Connection control header
o The Cache control header
POST Asks the server to accept the body info attached. It is like GET request
with extra info sent with the request.
HEAD Asks for only the header part of whatever a GET would return. Just like
GET but with no body.
TRACE Asks for the loopback of the request message, for testing or
troubleshooting.
PUT Says to put the enclosed info (the body) at the requested URL.
OPTIONS Asks for a list of the HTTP methods to which the thing at the request
URL can respond
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
Cookies in Servlet
A cookie is a small piece of information that is persisted between the
multiple client requests.
1. Non-persistent cookie
2. Persistent cookie
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
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.}
SecondServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doPost(HttpServletRequest request, HttpServletResponse response){
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. Cookie ck[]=request.getCookies();
14. out.print("Hello "+ck[0].getValue());
15.
16. out.close();
17.
18. }catch(Exception e){System.out.println(e);}
19. }
20.
21.
22.}
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</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.<servlet>
14.<servlet-name>s2</servlet-name>
15.<servlet-class>SecondServlet</servlet-class>
16.</servlet>
17.
18.<servlet-mapping>
19.<servlet-name>s2</servlet-name>
20.<url-pattern>/servlet2</url-pattern>
21.</servlet-mapping>
22.
23.</web-app>
Output
2) Hidden Form Field
1. Hidden Form Field
2. Example of Hidden Form Field
In such case, we store the information in the hidden field and get it from
another servlet. This approach is better if we have to submit form in all the
pages and we don't want to depend on the browser.
Here, uname is the hidden field name and Vimal Jaiswal is the hidden field
value.
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.
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.
The HttpServletRequest interface provides two methods to get the object of
HttpSession:
Attribute in Servlet
An attribute in servlet is an object that can be set, get or removed from
one of the following scopes:
1. request scope
2. session scope
3. application scope
The servlet programmer can pass informations from one servlet to another
using attributes. It is just like passing object from one class to another so
that we can reuse the same object again and again.
DemoServlet1.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class DemoServlet1 extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. {
7. try{
8.
9. res.setContentType("text/html");
10.PrintWriter out=res.getWriter();
11.
12.ServletContext context=getServletContext();
13.context.setAttribute("company","IBM");
14.
15.out.println("Welcome to first servlet");
16.out.println("<a href='servlet2'>visit</a>");
17.out.close();
18.
19.}catch(Exception e){out.println(e);}
20.
21.}}
DemoServlet2.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class DemoServlet2 extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. {
7. try{
8.
9. res.setContentType("text/html");
10.PrintWriter out=res.getWriter();
11.
12.ServletContext context=getServletContext();
13.String n=(String)context.getAttribute("company");
14.
15.out.println("Welcome to "+n);
16.out.close();
17.
18.}catch(Exception e){out.println(e);}
19.}}
web.xml
1. <web-app>
2. <servlet>
3. <servlet-name>s1</servlet-name>
4. <servlet-class>DemoServlet1</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>s1</servlet-name>
8. <url-pattern>/servlet1</url-pattern>
9. </servlet-mapping>
10.<servlet>
11.<servlet-name>s2</servlet-name>
12.<servlet-class>DemoServlet2</servlet-class>
13.</servlet>
14.<servlet-mapping>
15.<servlet-name>s2</servlet-name>
16.<url-pattern>/servlet2</url-pattern>
17.</servlet-mapping>
18.</web-app>
SingleThreadModel interface
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.
Example of SingleThreadModel interface
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.ServletException;
4. import javax.servlet.SingleThreadModel;
5. import javax.servlet.http.HttpServlet;
6. import javax.servlet.http.HttpServletRequest;
7. import javax.servlet.http.HttpServletResponse;
8. public class MyServlet extends HttpServlet implements SingleThreadMod
el{
9. public void doGet(HttpServletRequest request, HttpServletResponse respon
se)
10. throws ServletException, IOException {
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13. out.print("welcome");
14. try{Thread.sleep(10000);}catch(Exception e){e.printStackTrace();}
ServletOutputStream class
ServletOutputStream class provides a stream to write binary data into the
response. It is an abstract class.
1. ServletOutputStream out=response.getOutputStream();
Methods of ServletOutputStream class
The ServletOutputStream class provides print() and println() methods that
are overloaded.
Example
1. package com.javatpoint;
2. import java.io.*;
3. import javax.servlet.*;
4. import javax.servlet.http.*;
5. public class DisplayImage extends HttpServlet {
6. public void doGet(HttpServletRequest request,HttpServletResponse resp
onse)
7. throws IOException
8. {
9. response.setContentType("image/jpeg");
10. ServletOutputStream out;
11. out = response.getOutputStream();
12. FileInputStream fin = new FileInputStream("c:\\test\\java.jpg");
13. BufferedInputStream bin = new BufferedInputStream(fin);
14. BufferedOutputStream bout = new BufferedOutputStream(out);
15. int ch =0; ;
16. while((ch=bin.read())!=-1)
17. {
18. bout.write(ch);
19. }
20. bin.close();
21. fin.close();
22. bout.close();
23. out.close();
24. }
25. }