You are on page 1of 95

Servlets

Client <> Server


HTTP HTML

Web Requests
GET

Server Client
POST

HTTP Methods
GET a simple fetch request. POST can send user data.

You CAN send a little data with GET


The total amount of characters in a GET is limited. The data sent with GET is appended to the URL (/mailer?user=idiot&pass=hehe) Bookmarking is possible with GET request

HTML quickie
<!-- --> Comments <a> anchor for putting a hyperlink <body> defines document boundary <br> line break <form> defines a form <h1> first level header <input type> defines an input widget <p> new paragraph <title> Documents Title

Web Site Structure (IBM HTTP Server)


WebServerHome
IHS Home

htdocs

pens Index.html bookstore

parker Index.html Index.html J2EE

ricoh

Catalog.html

Dynamic content
Web servers serve only static HTML. We need to be able to write programs for dynamic content generation. Choices

Servlets/JSP ASP/COM .Net CGI

Why choose Servlets/JSP over CGI Perl


Performs better than a Perl program needing to launch a separate process for each request. It is part of J2EE and hence can use all the integrated Security, transaction and other services with EJBs.

Servlets

Advantages of Java Servlets


Advantages of Servlets over CGI scripts: Portability due to Java Can directly access the server environment, more efficient

No process creation overhead Multiple threads facilitate scalability Safer, due to the safety guarantees of Java. Extensible and flexible. Efficient Persistent Robust Secure

Features of Servlets
Portability Power Efficiency and Endurance Safety Elegance Integration Extensibility and Flexibility

Portability
Because servlets are written in Java and confirm to a well-defined and widely accepted API, they are highly portable across operating systems and across server implementations.

Power
Servlets can harness the full power of the core Java APIs: networking and URL access, multithreading, image manipulation, database connection, RMI, CORBA connectivity etc. Servlets are also well suited for enabling client/server communication. With a Java-based applet and servlet you can use RMI and object serialization to handle client/server communication.

Efficiency and Enduarance


Servlets in general are naturally enduring objects. Because a servlet stays in the servers memory as a single object instance, it automatically maintains its state and can hold on to external resources, such as database connections.

Integration
Servlets are tightly integrated with the server. A servlet can use the server to translate file paths, perform logging, check authorization and in some cases, even add users to the servers user database.

Basic Architecture
JVM GET

Client

Container

Servlet

Java program listening to HTTP

Java class

Request handling in Servlets


Container gets the HTTP request. It sees that the request is for a servlet and hence creates the request and response objects. Locates the servlet based on the URL, allocates a thread and calls the service method. Service method calls doGet or doPost. doXXX method pushes the generated HTML to the response object Container converts the response to HTTP and sends it back to client and destroys the request and response object.

Basic Servlet Code


import javax.servlet.*; import javax.servlet.http.*; import java.io.*;
Most servlets are HttpServlets. They implement the Servlet Interface and also the service() method.

public class MyServlet extends HttpServlet{


public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException{ PrintWriter out = res.getWriter(); String param = req.getParameter(param); out.println(<html><body>Hello +param +</body></html>); }

How is a Servlet identified


Client known URL name. (bookstore/searchBook) Deployer known internal name.
(SearchServlet)

Actual servlet class name.(com.company.BookSearchServlet)


The deployment descriptor(DD) connects these three. http:// www.myserver.com Context Path Path info /mywebapp /helloServlet /hello Servlet Path

Host

URL Mapping in the DD


<web-app> <servlet> <servlet-name>SearchServlet</servlet-name> <servlet-class>com.company.BookSearchServlet</servlet-class> </servlet> -----------------------------<servlet-mapping> <servlet-name>SearchServlet</servlet-name> <url-pattern>bookstore/searchBook</url-pattern> </servlet-mapping> </web-app>

Servlets of an app listed in this tag

This is what the client uses

Deployment Structure
Booksore.war WEB-INF

Catalog.jsp
Index.html classes lib web.xml com

company

BookSearchServlet.class

The ugly HTML in java code


Does it seem the right thing to do in servlets? If not, what else?

Java in HTML JSP Backend work Look at MVC pattern.

Then what good are Servlets for?

Then what good are EJBs for?

Response object can give us an output stream

Use it to send things other than HTML back to the client.


SetContentType and Write to o/p stream Common mime types

text/html application/pdf image/jpeg application/x-zip

J2EE Application Server


Web Container Servlet DB

EJB Container

JSP

Enterprise javabeans
Services (JMS, JTA, JNDI, etc)

Key Servlet API


<<interface>> javax.servlet.Servlet <<interface>> Javax.servlet. ServletRequest <<interface>> Javax.servlet. ServleResponse

javax.servlet.GenericServlet

<<interface>> Javax.servlet.http. HttpServletRequest

<<interface>> Javax.servlet.http. HttpServletResponse

javax.servlet.http.HttpServlet

Servlet States
does not exist

Constructor init()

destroy()

service()

Initialised

Servlet Lifecycle
container

Dont put anything here. It is not a servlet yet

Servlet Class

Servlet object

Load class constructor init() service() destroy()


Handle client request with doGet and doPost

Servlet Lifecycle Methods


Inherits from javax.servlet.Servlet

service(request, response) init(ServletConfig) destroy() doXXX() methods

Overrides from HttpServlet

init()
Gives us a chance to initialise our servlet before handling client requests. You override this if you have specific initialisation to perform like getting a DB connection

Init parmeters in DD
<init-param> <param-name>coname</param-name> <param-value>IBM</param-value> </init-param> ------------------------------------------------IN SERVLET CODE: getServletConfig().getInitParameter(coname);

Init parameters contd..


Container reads the init parameters from the DD, puts it in the ServletConfig Object and gives it to Init() The init parameters of the servlet are read only once when the servlet is initialised by the container

service()
Called for every clients request The method looks at the request and determines the HTTP method and invokes the correct doXXX() method. We dont override this.

Concept of Context and Config


ServletContext

Servlet A

Servlet B

Servlet C

JSP

Servlet Config

Servlet Config

Servlet Config

Servlet Config

Context Init Params


<context-params> <param-name>coname</param-name> <param-value>IBM</param-value> </context-params> ------------------------------------------------------IN THE SERVLET CODE:

getServletContext().getInitParameter(coname);

Context parameters
They are initialised when the web app is initialised One for the entire app If the app is distributed, there is one ServletContext per JVM

Context listeners
THIS GOES INTO CLASS: Public class MyCTXListener implements ServletContextListener{ public void contextInitialised(ServletContextEvent event){ } public void contextDestroyed(ServletContextEvent event){ } } ------------------------------------------------------------------THIS GOES INTO DD: <listener> <listener-class>com.company.MyCTXListener</listener-class> </listener>

You can store java.lang.Object in ServletContext -ctx.setAttribute(name,obj)

Attributes are different from parameters!

Attribute methods
Methods in ServletContext, ServletRequest and HttpSession:

getAttribute(String) setAttribute(String, Object) removeAttribute(String) getAttribueNames()

Threading
Container
HTTP request

HTTP request

Servlet

Multiple threads, single instance

Thread A

Thread B

req

res

req

res

Thread Safety and Attribute scope


Context scope

Synchronizing service method wont make his thread safe You need a lock on the context not the servlet

Session scope

Request scope thread safe Instance variables not thread safe unless you force
SingleThreadModel safe

Need to synchronise on the HttpSession object

Local variables in service method

thread

Threading in Servlets

public interface SingleThreadModel The servlet API specifies a special marker interface called javax.servlet.SingleThreadModel. During the lifetime of the servlet that does not implement this interface. The container may send multiple service request in different threads to a single instance. This means that the implementation of the service() method should be thread safe. However if the service() method is not thread safe what is the alternative. The servlet should implement the SingleThreadModel Interface

Threading in Servlets

The container then follows the following two Strategies


Instance Pooling

In this approach the container maintains a pool of Servlet Instances. For each incoming request the, the container allocates a single servlet instance from the pool, and upon completion of the service, the container returns the instance to the pool. In this approach, the container maintains a single instance of the servlet. However since the container cannot send multiple request, it serializes the request.This means the requests are kept waiting until the present request is being served

Request Serialization

Threading in Servlets

In reality though a combination of these two strategies are followed. So the container maintains a reasonable number of instances and still serializes the requests if the number of requests exceeds the the number of instances. The SingleThreadModel is resource intensive, particularly if a large number of concurrent request are expected for the servlet. The effect of the SingleThreadModel is that the container executes the service() method in a synchronized block. This equivalent to using synchronized keyword for the service() method.** However if only a few statements of the service() method are not Thread safe then you should consider reducing the scope of synchronization. Always consider redesigning of application, so that you could completely avoid the SingleThreadModel or thread Synchronization and when you cannot avoid it be aware of the performance implications.

ServletRequest interface
getAttribute(String) getContentLength() getInputStream() getLocalPort() getParameter()

HttpServletRequest extends ServletRequest

getContextPath() getCookies() getHeader(String) getQueryString() getSession()

ServletResponse
getBufferSize() setContentType() getOutputStream() getWriter()

HttpServletResponse extends ServletResponse

addCookie() addHeader() sendError()

Other HTTP Methods implementable on Servlets


HEAD - returns only the header of GET TRACE loopback for testing PUT just like FTP PUT DELETE deletes the resource specified by URL OPTIONS query supported methods ----------------------------------------------------------Default method for HTML forms is GET

Idempotent methods in HTTP 1.1


GET HEAD PUT

So we have to ensure that the implementation of doGet() is really Idempotent.

HTTP Redirection
Set status code to 301 Set location header to the redirect URL Alternatively just call sendRedirect(URL) on the response object.

We can use relative URLs with or without /

Request Dispatch
RequestDispatcher rd = request.getRequestDispatcher(catalog/res.jsp); rd.forward(req,res); ---------------------------------------

Redirect involves the client, but request dispatch does not. Redirect can send the client to any thinkable URL, but request dispatcher can transfer it to another servlet/JSP in the same container. You cant dispatch after the response is flushed.

Session Management
Stateful session bean Database HttpSession

url rewriting Cookies

Hidden variables

How sessions work


Identify the request (not Source IP) Exchange this identification during conversation

Cookies URL rewriting

Cookies
Server
HTTP/1.1 200 OK Set-Cookie: JSESSIONID=989ABED8782 Content-Type: text/html

POST /bookstore/catalog HTTP/1.1 Host: www.ibm.com Cookie: JSESSIONID=989ABED8782

Container does all the work with Cookies


START OR GET A SESSION: HttpSession session = request.getSession(); OR request.getSession(false); ----------------------------------------------------------FIND OUT IF THE SESSION IS NEW: session.isNew()

BEWARE! Cookies can be disabled

URL rewriting
out.println(<a href=\/support\>Click here</a>); out.println(<a href=\ + response.encodeURL(/support) + \>Click here</a>); --------------------------------------------------------<html> <body> <a href =http://www.ibm.com/support:jsessionid=077 7ADE873>Click here</a> </body> </html>

URL rewriting contd


response.encodeRedirectURL(/support); Cant use static HTML with URL rewriting all content must be dynamic. Containers try both cookies and url rewriting initially.

HttpSession Methods
getCreationTime() getLastAccessedTime() setMaxInactiveInterval() getMaxInactiveInterval() invalidate() -----------------IN DD-----------------<session-config> <session-timeout>20</session-timeout> </session-config> Minutes

Attributes stored in HttpSession must be serialisable as it can move across JVMs in clustered environments

HttpSessions move across JVMs

Cookie handling
Cookie ck = new Cookie(name,name) Seconds Ck.setMaxAge(300) response.addCookie(ck); Cookie cks[] = request.getCookies()

Session lifecycle
Session creation Create Session destruction HttpSessionListener

HttpSessionAttributeListener

Attr

Add Remove Replace

Passivation Migration Activation

HtpSessionActivationListener

Session related Listener API


HttpSessionListener

sessionCreated sessionDestroyed
HttpSessionEvent

Worker class

HttpSessionActivationListener

sessionDidActivate sessionWillPassivate
HttpSessionEvent

Worker class Attribute class

HttpSessionAttributeListener

attributeAdded attributeRemoved attributeReplaced


HttpSessionBindingEvent

Worker class

Session related Listener API


HttpSessionBindingListener

valueBound valueUnbound
HttpSessionBindingEvent

Attribute class

Other Listeners
ServletContextAttributeListener

attributeAdded attributeRemoved attributeReplaced attributeAdded attributeRemoved attributeReplaced requestInitialized requestDestroyed

ServletRequestAttributeListener

ServletRequestListener

Handling Form Data the doGet Method


Here we will be invoking a servlet from a HTML file.
The ACTION attribute is used to invoke a servlet.
<HTML> <HEAD> <TITLE> Introductions</TITLE> </HEAD> <BODY> <FORM METHOD =GET ACTION =/servlet/Hello> If you dont mind me asking, what is your name? <INPUT TYPE=TEXT NAME=name><P> <INPUT TYPE=SUBMIT> </FORM> </BODY> </HTML>

Handling Form Data the doGet Method


The Hello servlet code is:
public class Hello extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); String name = req.getParameter("name"); out.println("<html>"); out.println("<head><title>Hello," + name + "</title></head>"); out.println("<body><form mothod=post action=/servlet/HelloUser>"); out.println(<h2>Hello + name + Enter your Password); out.println(<input type=text name=password></h2>); out.println(<input type=submit></form>);

Handling Form Data the doPost Method


The HelloUser servlet code is:
public class HelloUser extends HttpServlet { public void doPost(HttpServletRequest req,HttpServletResponse res) throws IOException,ServletException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); String pass = req.getParameter(password"); out.println("<html>"); out.println("<head><title>Your password </title></head>"); out.println(<body><h2>Your Password is" + pass); out.println(</h2></body></html>"); } }

Server-Side Includes
Server-side includes are useful when a page is primarily static but contains a few distinct dynamic portions.

Server-Side Includes
Servlets can also be embedded inside HTML pages with server-side include(SSI) functionality. In many servers that support servlets, a page can be preprocessed by the server to include output from servlets at certain points inside the page. The tags used for a server-side include look similar to those used for applets:
<SERVLET CODE=ServletName CODEBASE=http://server:port/dir <PARAM NAME = param1 VALUE = value1> <PARAM NAME = param2 VALUE = value2> If you see this text, it means that the web server providing this page does not support the SERVLET tag. </SERVLET>

Server-Side Includes
</html> <head> <title>Times!</title> </head> <body> The current time here is: <servlet code=CurrentTime.class codebase=http://localhost:8080/> </servlet> <p>The current time in London is: <servlet code=CurrentTime><param name=zone value=GMT> </servlet> <p>And the current time in NewYork is: <servlet code=CurrentTime> <param name=zone value=EST> </servlet> </body></html>

Server-Side Includes
import java.text.*; public class CurrentTime extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException,ServletException { PrintWriter out = res.getWriter(); Date date = new Date(); DateFormat df = DateFormat.getInstance(); String zone = req.getParameter("zone"); if(zone!=null) { TimeZone tz = TimeZone.getTimeZone(zone); df.setTimeZone(tz); } out.println(df.format(date)); }

A Simple Counter
import java.io.*; public class SimpleCounter extends HttpServlet { int count; public void init(){ count = 0; } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); count++; out.println("Sincle loading, this servlet has been accessed" + count + "times"); }

Error Handling in Servlets


The Exception Handlers can be used to generate custom error pages
try{ }catch(Exception e){ out.println(<html><body><h2>+e.getMessage()+ </h2></body></html>); }

Logging in Servlets
getServletContext().log(String msg) getServletContext().log(Exception e, String msg)

Using SendError
void SendError(int Status) void SendError(int Status, message)

Declarative Error handling


<web-app> <error-page> <error-code>403</error-code> <location>/error.html<location> </error-page> </web-app>

Exception handling
Any exception thrown from a servlet should be wrapped in a Servlet Exception
catch(SQLException){ throw new ServletException(Wrapped SQL Exception,e); }

Set error page for Exception


<web-app> <error-page> <exception-type>java.sql.SQLException</exceptiontype> <location>/errorservlet<location> </error-page> </web-app>

In Error page
Object ex = req.getAttribute(javax.servlet.error.e xception); Throwable actualException = (Throwable) ((ServletException)ex).getRootCause();

Can use the Request Dispatcher to handle Exceptions

Filters

What are filters


They are java classes that intercept a request or a response to or from a server We can declaratively include/exclude filters

Filters are like servlets in some ways


The container knows their API The container manages their life cycle They are declared in the DD

Simple filter
public class RequestTracker implements Filter { private FilterConfig fc; public void doFilter(ServletRequest req,ServletResponse resp, FilterChain chain) throws ServletException, IOException {

HttpServletRequest httpreq = (HttpServletRequest)req;


String name = httpreq.getRemoteUser(); if(name!=null){ fc.getServletContext().log(name + " made a request"); }else fc.getServletContext().log("Request from unknown user");

chain.doFilter(req, resp); }

public void init(FilterConfig config) throws ServletException {


fc = config; }

Filters are like a Stack


The chain.doFilter method takes care of calling the next filter or the servlet After executing the service method of the servlet, the call returns to the first filter.

Declarations in the DD
<filter> <filter-name>RequestTracker</filter-name>

<display-name>RequestTracker</displayname>
<filterclass>package.RequestTracker</filterclass> </filter>

<filter-mapping>
<filter-name>RequestTracker</filter-name>

Response Filter
Just add the chain.doFilter before the processing logic and it becomes a response filter We swap in a custom response object in place of the original one so that we control the output in the Filter

There are wrappers to create custom response


ServletRequestWrapper HttpServletRequestWrapper ServletResponseWrapper HtpServletResponseWrapper All these implement the respective interfaces

Web Security
Declarative Programatic

Declarative
Form based Basic Auth Client Cert Auth

Form Based
<form method="POST" action="j_security_check"> <input type="text" name="j_username"> <input type="password" name="j_password"> </form>

Form Based
<login-config> <auth-method>FORM</auth-method> <realm-name>TestRealm</realm-name> <form-login-config> <form-login-page>LoginForm.jsp</form-login-page> <form-error-page>InvalidLogin.jsp</form-errorpage> </form-login-config> </login-config>

Basic Auth
<login-config> <auth-method>BASIC</auth-method> <realm-name>TestRealm</realm-name> </login-config>

Security Constraint
<security-constraint> <display-name>GeneralUserConstraint</display-name> <web-resource-collection> <web-resource-name>AllUrls</web-resource-name> <description></description> <url-pattern>*.do</url-pattern> <url-pattern>*.jsp</url-pattern> <http-method>GET</http-method> </web-resource-collection> <auth-constraint> <description></description> <role-name>Manager</role-name> </auth-constraint> <user-data-constraint> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint>

You might also like