Professional Documents
Culture Documents
Web Requests
GET
Server Client
POST
HTTP Methods
GET a simple fetch request. POST can send user data.
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
htdocs
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
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.
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 class
Host
Deployment Structure
Booksore.war WEB-INF
Catalog.jsp
Index.html classes lib web.xml com
company
BookSearchServlet.class
EJB Container
JSP
Enterprise javabeans
Services (JMS, JTA, JNDI, etc)
javax.servlet.GenericServlet
javax.servlet.http.HttpServlet
Servlet States
does not exist
Constructor init()
destroy()
service()
Initialised
Servlet Lifecycle
container
Servlet Class
Servlet object
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);
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.
Servlet A
Servlet B
Servlet C
JSP
Servlet Config
Servlet Config
Servlet Config
Servlet Config
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>
Attribute methods
Methods in ServletContext, ServletRequest and HttpSession:
Threading
Container
HTTP request
HTTP request
Servlet
Thread A
Thread B
req
res
req
res
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
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
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()
ServletResponse
getBufferSize() setContentType() getOutputStream() getWriter()
HTTP Redirection
Set status code to 301 Set location header to the redirect URL Alternatively just call sendRedirect(URL) on the response object.
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
Hidden variables
Cookies
Server
HTTP/1.1 200 OK Set-Cookie: JSESSIONID=989ABED8782 Content-Type: text/html
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>
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
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
HtpSessionActivationListener
sessionCreated sessionDestroyed
HttpSessionEvent
Worker class
HttpSessionActivationListener
sessionDidActivate sessionWillPassivate
HttpSessionEvent
HttpSessionAttributeListener
Worker class
valueBound valueUnbound
HttpSessionBindingEvent
Attribute class
Other Listeners
ServletContextAttributeListener
ServletRequestAttributeListener
ServletRequestListener
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"); }
Logging in Servlets
getServletContext().log(String msg) getServletContext().log(Exception e, String msg)
Using SendError
void SendError(int Status) void SendError(int Status, message)
Exception handling
Any exception thrown from a servlet should be wrapped in a Servlet Exception
catch(SQLException){ throw new ServletException(Wrapped SQL Exception,e); }
In Error page
Object ex = req.getAttribute(javax.servlet.error.e xception); Throwable actualException = (Throwable) ((ServletException)ex).getRootCause();
Filters
Simple filter
public class RequestTracker implements Filter { private FilterConfig fc; public void doFilter(ServletRequest req,ServletResponse resp, FilterChain chain) throws ServletException, IOException {
chain.doFilter(req, resp); }
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
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>