Intro to Servlets and Servlet Basics.pdf
Document Details
Uploaded by JawDroppingNarwhal879
University of Santo Tomas
Tags
Full Transcript
Introduction to Servlets and JSP Web browser sends and HTTP Request and then return the The Web Client and the Web Server requested source in an HTTP...
Introduction to Servlets and JSP Web browser sends and HTTP Request and then return the The Web Client and the Web Server requested source in an HTTP Response. Web Client A web browser lets a user request a HTTP Request and Response resource (HTML page, image, PDF document etc). HTTP Request contains the following Knows how to communicate with the elements: web server HTTP method (action to be Interprets the resource returned by performed) the web server and displays it to the The page to access (a URL) user Form parameters Web Server HTTP Response contains the following Gets the resource requested by the elements: client and returns it to the user A status code (request was Server can be the physical machine successful or not) (hardware) or the server application Content-type (text, picture, HTML, (software). etc.) The content (the actual HTML, Relationship: image, etc.) User clicks a link in the web browser then the server finds the HTTP Request Method requested page. Server formats the response and GET and POST sends it to the browser and browser Request a resource from the server gets the HTML and displays it to the Send form data to the server, if there user. are any HTML and HTTP There are other HTTP methods PUT and DELETE are used in HTML RESTful applications HyperText Markup Language HEAD, TRACE, OPTIONS, Servers often return HTML content CONNECT are rarely used Tells the browser how to present the content to the user GET vs. POST All browsers know how to render HTML Get Limited length (depends on the os) HTTP Form data is appended to the URL HyperText Transfer Protocol ○ User can bookmark the Protocol used by a web server and a resulting URL from a form browser submission ○ May not be secure since the http://localhost/app/Registration?firstname= user can see the form data in Jose&lastname=Rizal the URL “http://localhost” Post The web server to process the Unlimited length request Form data is in the request ○ User can’t bookmark the “/app/Registration” resulting URL from a form Name and location of the server submission resource ○ Considered more secure since form data is not part of “?” the URL Separates the location from the data Anatomy of an HTTP GET Request “key=value” Field names and associated data GET /app/Registration?firstname=Jose&lastname “&” =Rizal HTTP/1.1 Separates key=value pairs Host: localhost … “+” … Replaces the space character Note that all other special characters “GET” are hex-coded The HTTP method Anatomy of an HTTP POST Request “/app/Registration” The path to the resource on the POST /app/Registration HTTP/1.1 server. Host: localhost … “?firstname=Jose&lastname=Rizal” … Parameters, if there are any, are firstname=Jose&lastname=Rizal appended to the first part of the URL, starting with a “?”. “POST” Parameters are separated with an The HTTP method “&”. “/app/Registration” “HTTP/1.1” The path to the resource on the The protocol version server “Host: localhost…” “HTTP/1.1” Request headers The protocol version “Host: localhost…” Request headers “:80” Port: a server application is identified “firstname=Jose&lastname=Rizal” by a port. In this case, 80 is optional Message body since this is already the default port used by the HTTP The HTTP Response “/info/contact/” HTTP/1.1 200 OK Path: the path to the location of the Content-Type: text/html resource being requested … … “Index.html” Resource: the name of the content being requested.... … Web Server Limitations … Web servers can only return static content “HTTP/1.1” Finds the file requested by the client, HTTP protocol and hands it back to the client as-is Cannot do computations “200” Status code Web servers require a “helper” application to: “OK” Generate just-in-time pages A text version of the status code Save data on the server “Content-Type: text/html…” Why Build Web Pages Dynamically Headers The Web page is based on data submitted “...” by the user Body Example: results page from search engines and order-confirmation Uniform Resource Locator (URL) pages at online stores http://www.acme.com:80/info/contact/index. The Web page uses information from html databases or other server-side sources Example: an e-commerce site could “http://” use a servlet to build a web page Protocol: tells the server which that lists the current price and protocol to use availability of each item that is for sale “www.acme.com” Server: the unique name of the physical server you’re looking for Server Setup and Configuration ii. A DD can declare 1. Download and install Java many servlets Development Kit (JDK) iii. The DD should be 2. Download an application server placed in the web 3. Install your application server app’s WEB-INF 4. Test your setup directory 5. Setup your development iv. Should be named environment web.xml b. Don’t write from scratch Creating Your First Web Application i. Copy a template DD 1. Create your deployment directory ii. Place the copy in a. A web application needs to your application’s follow a standard directory WEB-INF directory structure as specified in the c. Edit the file and declare your servlet specification servlet b. In tomcat, a web application 5. Test the servlet must have its own directory a. If you haven’t started Tomcat in the webapps directory of yet, start it again the tomcat installation b. Launch your browser 2. Write the servlet a. We will create a servlet that Using Development Tools will display the current date and time Developing java web applications by hand is 3. Compile the servlet tedious a. Use javac to compile the However, we need this in case we servlet: javac have no other choice. DateTimeServlet.java You can automate building and deploying b. If you encounter errors, through development tools such as chances are servlet-api.jar NetBeans was not include in your For the rest of the course, we will classpath use NetBeans to develop our web c. The resulting applications. DateTimeServlet.class and other java classes in the right The Problem with Servlets directory. Servlets and other Printing out HTML in a servlet is java classes must be placed tedious, error-prone, and confusing in a web application’s ○ If you want to output , you have 4. Write the deployment descriptor to escape the double quotes, (DD) out.println(“”); application You can’t just copy and past the i. Servlets must be HTML code from your HTML editor declared in a DD JavaServer Pages (JSP) How the Container Handles a Request A JSP is just like HTML page, but 1. User clicks a link that has a URL to a you can put java code inside it servlet Copy C323\DateTime.jsp into your 2. The container sees that the request application’s root directory is for a servlet, so the container C:\Tomcat\webapps\testApp creates two objects: Launch your browser and type in a. HttpServletRequest http://localhost:8080/testApp/DateTi b. HttpServletResponse me.jsp 3. The container finds the correct servlet based on the URL in the request a. Creates or allocates a thread Servlet Basics for that request b. Passes the request and What is a Web Container? response objects to the Servlets don’t have a main() method. servlet thread ○ They are under control of 4. The thread calls the servlet’s another java application service() method called the web container a. Depending on the type of Also known as application server request, service() calls either Ex: Tomcat, Glassfish, WebLogic doGet() or doPost 5. The doGet() or doPost() method Container Services generates the dynamic page and stuffs the page into the response Communications support object Knows the HTTP protocol a. The response goes back to Knows how to communicate with the the container web server 6. The thread completes a. The container converts the Lifecycle management response object into an Controls the life and death of your HTTP response, and sends it servlets back to the client b. Container deletes the Multithreading request and response Creates a new java thread for every objects servlet request The Servlet Class Hierarchy Declarative Security 1. Servlet interface Configure security using an XML file - The servlet interface says No need to modify or recompile your that all servlets have these 5 code methods (the three in bold are lifecycle method) JSP Support 2. GenericServlet class -An abstract class that ○ When a client request comes implements most of the basic in, the container starts a servlet methods you’ll need, thread, and causes the including those from the servlet’s service() method to servlet interface. You will be invoked. probably never extend this What it’s for class yourself. Most of your ○ It looks at the request, servlet’s “secret behavior” determines the HTTP comes from this class. method (GET, POST, etc.) 3. HttpServlet class and invokes the matching - An abstract class that doGet(), doPost(), etc. on the implements the service() servlet method to reflect HTTP Do you override it? specific behavior. Note that ○ You should NOT override this the service() method now method. Override doGet() takes HTTP specific request and doPost() instead. and response objects. ○ You may be tempted to 4. MyServlet class override service() so that - All you have to do is override your servlet will execute the the HTTP methods you need. same code regardless if the request method. The Servlet Life Cycle Remember, there are other methods aside init() from POST and GET When it’s called service() ○ Executed once when the automatically calls the servlet is first loaded appropriate servlet ○ Executed before the servlet methods doPut(), can service any client doTrace(), etc. requests depending on the What it’s for request. ○ Gives you a chance to ○ Alternatives: initialize your servlet before Have doPost() call handling any client requests doGet() ○ Used by the container to Create a separate pass the servlet its method that will be ServletConfig object called by both Do you override it? doPost() and doGet() ○ Possibly. If you have Don’t forget to initialization code (like getting pass the a database connection). request and response service() objects When it’s called This is the ServletConfig approach Let’s say we have the following code used by in our servlet: NetBeans ○ PrintWriter out = response.getWriter(); doGet() / doPost() out.println(“[email protected]”); When it’s called We can put the address in the DD ○ The service() method calls (web.xml), and the servlet can doGet() or doPost() based on access the email address through the request’s HTTP method the ServletConfig object What it’s for If the email address changes, we ○ This is where your code just edit the web.xml file begins ○ No need to modify and Do you override it? recompile the servlet ○ Whichever one(s) you override tells the container ServletContext which HTTP method(s) you What if you want a parameter to be support. available to all servlets in the same web application destroy() ○ Use Context Init Parameters When it’s called ○ Called when server deletes ServletConfig vs ServletContext servlet instance ServletConfig is one per servlet ○ Not called after each request ServletContext is one per web app What it’s for ○ You might want to clean up ServletContextListener resources here such as ContextInit Parameters allow you to closing database declare strings that will be used in connections your servlets Do you override it? ○ If you want to pass objects ○ Possibly. Depends if you instead, use a have some cleaning up to do ServletContextListener javax.servlet.ServletContextListener More About Servlet Initialization ○ Executed when the web 1. When the container initializes a application is first created servlet, it makes a unique Before any of the ServletConfig for the servlet servlets are created 2. The container reads the servlet init parameters from the DD and gives Mapping Benefits them to the Servlet Config Improves your application’s flexibility 3. Container calls the servlet’s init() ○ Allows you to change the method, passing it the ServletConfig organization of your object packages and servlets without having to change the URLs in your HTMLs and JSPs Improves your application’s security ○ Prevents clients from knowing the directory structure of your server Debugging Servlets Use out.print or out.println Use System.out.print and System.out.println statements; run server on command-line ○ Will output in the console, not the browser Use Apache Log4J for logging Integrated debugger in IDE ○ Netbeans allows you to look at request headers, parameters, sessions values, cookies, etc. Look at the output HTML source Servlets and other classes may not have been reloaded. Restart the server.