servlets

24
SERVLETS

Upload: geethu-mohan

Post on 11-May-2015

389 views

Category:

Education


0 download

TRANSCRIPT

Page 1: Servlets

SERVLETS

Page 2: Servlets

What are Servlets ? Servlets are part of the Java2EE specification. Servlets are modules that run on the server,

enabling you to extend the server’s functionality. Servlets work within a Web server environment,

and they are a key component of server side Java development. Servlets are an effective

replacement for CGI scripts.

Page 3: Servlets

Benefits of Servlets Can be deployed into distributed server

environments. Servlets are platform- and server-independent. Servlets are easy to develop and follow a

standard API. Servlets are extensible. Java Server Pages (JSP)

build on top of the Servlet API. A servlet is a server resource, providing access to

other server resources, such as other servlets, EJBs, JSPs, JDBC, and so on.

Page 4: Servlets

HTTP MethodsMethod Description

GET

HEAD

POST

PUT

DELETE

The client requests information from the given URL.

Similar to GET, except the body is not retrieved.

Client adds info to URI (HTML forms)

Used to place documents on the Server.

Client deletes resource of URI.

Page 5: Servlets

Status Codes in HTTP

Status Code Category

100s Informational

200s Successful

300s Redirection

400s Request Error

500s Server Error

Page 6: Servlets

Servlet API The Servlet API defines a standard interface for

handling request and response between the browser and the Web server.

The Servlet API is composed of two packages: javax.servlet - javax.servlet.GenericServlet javax.servlet.http - javax.servlet.HttpServlet

Page 7: Servlets

Service Method (Request Response Method)

A generic servlet handling a request

Page 8: Servlets

HTTP Request - Response Flow

An HTTP servlet handling GET and POST requests

Page 9: Servlets

Embedding HTML within ServletCan use ServletOutputStream or PrintWriter to send data

back to the client.

1. reference the stream from the Response parameter:

ServletOutputStream out =response.getOutputStream();

2. get a reference to the writer from the Response parameter:

PrintWriter out = response.getWriter();

3. Then write the output to the stream:

out.println(“<HTML>Inside HTML</HTML>”);

4. Finally, close the writer:

out.close();

Page 10: Servlets

Setting MIME Type MIME – Multiple Internet Mail Extension Identifies extension of each file in the

HTTPResponse

response.setContentType(“text/html”);

PrintWriter out = response.getWriter();

Page 11: Servlets

Sample Program

import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

public class srvltJust extends HttpServlet {

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

res.setContentType(“text/html”);

PrintWriter out = res.getWriter();

out.println(“<HTML>”);

out.println(“<HEAD><TITLE>Servlet</TITLE></HEAD>”);

out.println(“<BODY>”);

out.println(“<H1>This is a just a Servlet!</H1>”);

out.println(“</BODY></HTML>”);

out.close();

Page 12: Servlets

HTTP Request Header

Page 13: Servlets

HTTP Response Message

Page 14: Servlets

HTTP Request Header

Parameters public String getParameter(String name) public Enumeration getParameterNames() public String[] getParameterValues(String name)

Content public int getContentLength() - returns the length,

in bytes. -1 is returned if the length is not known. getContentType() - returns the request’s MIME

type of the content (null if it’s not known). getCharacterEncoding() - returns the name

character encoding style of the request.

Page 15: Servlets

HTTP Response Header

Header Methods setDateHeader() setIntHeader() setContentType() setContentLength() addCookie() sendError()

Page 16: Servlets

Session Management

Ways to manage session, Hidden form fields URL rewriting Persistent cookies Session tracking API

Page 17: Servlets

Hidden Form Fields

<input type=”hidden” name=”pageid” value=”5”>

public String getParameter(String name) public Enumeration getParameterNames() public String[] getParameterValues(String name)

Page 18: Servlets

URL Rewriting

http://myServer/servlets/srvltEmp?EMPID=1009&DEPID=200

Page 19: Servlets

Persistent Cookies

API for persistent cookie is,

javax.servlet.http.Cookie

To create a new cookie, Cookie cookie(String name, String value) Eg: Cookie cookie = new Cookie("ID", "123");

To get all available cookies, req.getCookies()

To send back the cookie name response.addCookie(cookie_name)

Page 20: Servlets

Session Tracking API

A servlet with getSession( ) method retrieves the current HttpSession object

Eg: public HttpSession HttpServletRequest.getSession(boolean )

Set properties by,

public void HttpSession.setAttribute(String name, Object value)

Eg: session.setAttribute(“name”, id);

Get properties by,

public void HttpSession.setMaxInactiveInterval(int secs)

Page 21: Servlets

Session Tracking API

Get current session id by,

public String getId() Whether it is a new cookie or referenced,

public boolean isNew Start of a session

public long getCreationTime() Last session activity

public long getLastAccessedTime Session invalidating by,

public void invalidate() Removing attribute by,

public void removeAttribute(String name)

Page 22: Servlets

Session Managementimport java.io.*; import java.net.*; import java.util.*; import javax.servlet.*;

import javax.servlet.http.*;

public class srvltHoldAppID extends HttpServlet

{public void service(HttpServletRequest req, HttpServletResponse res)

throws IOException, ServletException {

resp.setContentType(“text/html”);

PrintWriter out = res.getWriter();

String sAPPID` = “undefined”;

String[] sAPPID = req.getParameter(“APPID”);

if(sAPPID != null && sAPPID.length > 0) {

// Create session:

HttpSession session = req.getSession();

session.setAttribute(“APPID”, sAPPID);

}}}

Page 23: Servlets

Dispatching Requests

ServletContext sc = this.getServletContext();

RequestDispatcher rd = sc.getRequestDispatcher(“/srvltComplete”);

if (rd !=null) {

try {

rd.forward(req, res);

}

catch (Exception e) {

// Handle Exception

}

}

Page 24: Servlets

JDBC ConnectionConnection conn = null;

Statement stmt = null;

ResultSet rs = null;

String sSQL = “……….”

InitialContext ic = new InitialContext()

//Get a reference to the datasource

String dsName = “java:comp/env/jdbc/emplphone”

DataSource ds = (DataSource) ic.lookup(dsName)

conn = ds.getConnection() // Get a Connection

stmt = conn.createStatement()

rs = stmt.executeQuery(sSQL)

while( rs.next())

{out.println(rs.getString(1))}