Toronto CSC 309H - Web Programming - Servlets

Unformatted text preview:

CSC309: Web ProgrammingGreg Wilson 1           Use Javascript to create richer browser-based GUIsMove data back and forth using HTTPHave a web server handle:Fetching pagesInvoking users’ programs to create dynamic contentDeclare victory and move on?Not quite…  !"!Each time a CGI is run, the server must:Create a new processRe-run the Python interpreterEstablish a new database connection Or re-read the data fileThen close them all downThis takes time……which limits how many requests the server can handle#$ % &$ ' &$ ( Why not just keep Python running?It’s just another lump of CEach time a request comes in, wipe the interpreter’s memory, and start execution Or wipe most of it, but leave the database connections alonemod_python (and similar for other languages)This doesn’t work (safely) with C/C++!If a program can access arbitrary memory, there’s no sure way to re-set itCSC309: Web ProgrammingGreg Wilson 2) *Java was originally designed for building downloadable GUIsActually designed to run web TV, but that’s another storyIn the late 1990s, it offered the best of two worlds:Compilation and type checking, which means higher performance and more safetyInterpreted, which means arbitrary code can be run safely At least, more safely than C+++  A servlet is a mini-application designed to be run on a user’s behalf by a serverNo main()Instead, it implements one or more lifecycle methods that the server calls at specific times Just like GUI buttons implement OnClicked()Servlets are run by a containerDynamically loads the servlet’s class(es)Finds and calls methods using reflection,- %. Writing servlets is relatively straightforwardNext lecture will introduce Java Server Pages (JSPs), which make it even easierConfiguring a servlet container is complicatedEverything has to be in exactly the right placeXML configuration files have to be exactly rightThere are open source Eclipse plugins to helpWe’ll use Tomcat as our servlet containerFrom the same folks that brought you ApacheThe reference implementation of the standard/0 &  1Create directory "hello", with three sub-directories:src: for source files like HelloServlet.javaclass: for compiled class filesetc: for other files (like deployment descriptors)Like what?A deployment descriptor is an XML file that tells the container what your servlet is called, what class implements it, and what URL maps to itCSC309: Web ProgrammingGreg Wilson 3230 &  1import javax.servlet.*;import javax.servlet.http.*;import java.io.*;public class HelloServlet extends HttpServlet {public void doGet(HttpServletRequest req,HttpServletResponse resp)throws IOException {PrintWriter out = resp.getWriter();out.println("<html><body><p>Hello, servlet!</p>" +"</body></html>");}}30 &  1<web-app xmlns="http://java.sun.com/xml/ns/jsee" …><!-- Define symbolic name for servlet --><servlet><servlet-name>Hello</servlet-name><servlet-class>HelloServlet</servlet-class></servlet><!-- Connect servlet and URL --><servlet-mapping><servlet-name>Hello</servlet-name><url-pattern>/hello</url-pattern></servlet-mapping></web-app>30 &  1To deploy:Under Tomcat's root directory, create webapps/hello/WEB-INF/classes directoryPut web.xml file in hello/WEB-INFPut HelloServlet.class in hello/WEB-INF/classesDon't panic: it's just another interfaceRe-start Tomcat, and go to http://localhost:8080/hello/HelloPort 8080 because we're running Tomcat on its own !  4Communication supportLike BaseHTTPServer.HTTPServerLifecycle managementContainer loads classes, calls constructors, etc.MultithreadingThough you still have lots of work to doStandard configuration machineryBelieve it or not, it's simpler than the alternativesJSPsSee these in the next lectureCSC309: Web ProgrammingGreg Wilson 4  40  ! Your servlet must extend HttpServlet"The real benefit of object-oriented programming is that it allows old code to use new code."Python's reliance on "duck typing" doesn't scale to large projects nearly as wellYour servlet must implement doGet(), doPost(), or bothThere are other HTTP methods, but only 0.1% of applications ever use themThe method service() figures out what to invoke#$ 5 HttpServletRequest defines:getContentLength()getCookies()getHeader()getQueryString()Everything you remember from CGI is thereAlong with a lot moreE.g., session managementNote: it's an interface, not a base class$ 6 HttpServletResponse is what your servlet writes togetParameter() and getParameterValues()setContentType()getWriter()addCookie()addHeader()setStatus()Also an interface (rather than a base class)+- %A given servlet is only ever instantiated onceEach request is handled by a separate threadContainer maintains a thread poolIf a thread is idle when a request arrives, the container gives it the servlet and a new pair of request and response objectsOtherwise, request blocks until thread availableServlets must be thread-safe!Shared data must be protectedStack data is intrinsically safeCSC309: Web ProgrammingGreg Wilson 5,7.   89 ( The first time a request arrives for a servlet, the container:Finds and loads the classCalls its default constructorCalls its init() methodThe container then repeatedly calls service(), which in turn calls doGet(), doPost(), etc.When the container wants (or needs) to unload the servlet, it first calls the servlet'sdestroy() method/7. )-%:-Been talking as if GET and POST were basically the


View Full Document

Toronto CSC 309H - Web Programming - Servlets

Download Web Programming - Servlets
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Web Programming - Servlets and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Web Programming - Servlets 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?