Servlets

Post on 11-May-2015

389 views 0 download

transcript

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.

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.

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.

Status Codes in HTTP

Status Code Category

100s Informational

200s Successful

300s Redirection

400s Request Error

500s Server Error

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

Service Method (Request Response Method)

A generic servlet handling a request

HTTP Request - Response Flow

An HTTP servlet handling GET and POST requests

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();

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

HTTPResponse

response.setContentType(“text/html”);

PrintWriter out = response.getWriter();

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();

HTTP Request Header

HTTP Response Message

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.

HTTP Response Header

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

Session Management

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

Hidden Form Fields

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

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

URL Rewriting

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

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)

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)

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)

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);

}}}

Dispatching Requests

ServletContext sc = this.getServletContext();

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

if (rd !=null) {

try {

rd.forward(req, res);

}

catch (Exception e) {

// Handle Exception

}

}

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))}