Technology Overview JAVA Servlets CS-611 S. Witherspoon
JAVA Servlets What are servlets Why use them Anatomy of a servlet Sample servlets Servlets & J2EE
Servlet paradigm
Description Servlets are the Java platform technology of choice for extending and enhancing web servers Servlets are programs that run on a Web server and build Web pages based on data: Submitted by user Data that changes frequently Data from corporate databases or other sources
HTTP servlet
Advantage of Servlets Over CGI Efficient Runs in the Java Virtual Machine Each request is handled by lightweight thread Only 1 copy of servlet class in memory Optimization alternative ( caching previous computations, keeping database connections open)
Advantage of Servlets Over CGI Convenient Extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions Servlets receive all the benefits of the JAVA language (portability, performance, reusability and crash protection)
Advantage of Servlets Over CGI Powerful Servlets have access to the entire family of JAVA APIs, including JDBC TM API to access enterprise databases Servlets can talk directly to Web servers Servlets can talk and share data with each other
Advantage of Servlets Over CGI Inexpensive Adding server support to your web server is inexpensive of free (Apache Tomcat) Disadvantage?? You must learn Java!!
Anatomy of a Servlet Server Servlet code Load Client Handle Client Requests Unload
Anatomy of a Servlet init() destroy() service() doGet() doPost()
Anatomy of a Servlet HTTPServletRequest object Information about an HTTP request Headers Query String Session Cookies HTTPServletResponse object Used for formatting an HTTP response Headers Status codes Cookies
Sample Servlets Servlet ExamplesServlet Examples (localhost) or CSDateTime DemoCSDateTime Demo (remote host)
Sample Servlet (source code) Sue Example CSDateTime
Software Setup Directory Structure /webapps/ROOT/WEB-INF/classes Environment Variables JAVA_HOME J2EE_HOME CLASSPATH=$JAVA_HOME/jre/lib/ Path Settings PATH=$JAVA_HOME/bin:$J2EE_HOME/bin:$PATH
Compiling the Servlet Sun ONE Studio Open.java Select Compile under Build menu Copy resultant.class file to : /webapps/ROOT/WEB-INF/classes w/o JAVA ToolKit cd /webapps/ROOT/WEB-INF/classes javac.java
Running the Servlet Make sure Web Server (Tomcat) is running Bring up Web Browser Bring up Servlet /servlet/
Enterprise Servlets and J2EE
Distributed Environment (rules of thumb) Instance variables and static variables should not be used to store state The context should not be used to store application state Any object placed into an HttpSession should be capable being moved to a different machine Avoid using java.io package for file access, use getServletContext().getResource() Syncrhonization is not global and works only for the local JVM