Download presentation
Presentation is loading. Please wait.
Published byAugustine French Modified over 8 years ago
1
Java Servlets References: Karen Anewalt, Mary Washington College
2
Servlet overview Servlets are java programs that run on a web server within the environment of a servlet engine. Servlets facilitate the creation of dynamic web pages. More efficient than CGI. Platform independent.
3
Web Servers A web server is a program running on the server machine that listens for incoming requests and services those requests as they come (find a page, execute a program on the server,… and then returns results to the web browser). Examples: Apache is the most frequently used (http://apache.org).
4
Servlet engine Servlets require a servlet engine. A servlet engine is a software to handle requests to and responses from a servlet. Examples: Tomcat servlet engine (http://jakarta.apache.org/tomcat/), Jserv, Jrun...
5
URLs Uniform resource locator –Address for a file stored on a web browser http:// : / Servers usually listen for browser requests on port 80. Tomcat uses the 8080 port by default. BUT you were assigned a particular port number (port 2) on vulcan.
6
Servlets on vulcan Configuration: –echo $JAVA_HOME –echo $CLASSPATH –echo $HOME Starting the servlet engine: –cd tomcat/bin/ –./startup.sh Stopping the servlet engine: – cd tomcat/bin/ –./shutdown.sh
7
Servlets on vulcan Where to put your java files: –In the directory: tomcat/webapps/pace/WEB- INF/classes Try: –http://vulcan.seidenberg.pace.edu:port2/pace/servl et/HelloWorldServlet –Be sure that HelloWorldServlet is referenced in the tomcat/webapps/pace/WEB-INF/web.xml file
8
HTML files on vulcan You can put them in the directory: –public_html or –tomcat/webapps/pace You can then access them respectively by: –http://vulcan.seidenberg.pace.edu/~login/file.html –http://vulcan.seidenberg.pace.edu:port2/pace/file.h tml
9
HTML Hypertext Markup Language Formats web page layout
10
Creating forms in HTML Delimit form using Your form items here YourProgram is the file (with its location) to execute to process the form. The method specified must be GET or POST. Can use text boxes, radio buttons, checkboxes, pull-down lists…
11
Text boxes BoxLabel: Optional text box tag components: Size: size of box Maxlength: max number of characters Value: some default text
12
Radio buttons choice 1 choice 2 …
13
Checkboxes label
14
Pull down menus TextForChoice1 TextForChoice2 …
15
Textarea
16
Get versus Post There are two types of actions for requesting a servlet to be executed. Basic outcome is the same either way. Method of taking actions differs.
17
Get All form data that has been entered is appended to the request string using “key- value”pairs. Example: http://www/anywhere.com/cgi- bin/hello.cgi?name=ASHLEY Name=ASHLEY is the key-value pair. Get is the default method of web requests.
18
Get Downsides to get: –If previous results for same request URL exist in the cache, older results may be displayed. –Limits exist on the amount of data that can be included in the string.
19
Post Packages all form data as part of the request body. Server program is able to read contents of input file and parse out variable names and values. Advantages: –Allows more data to be passed –Always sends request to server (rather than looking in cache)
20
Choosing get or post Use get to retrieve info Use post to make requests that will modify contents of data stored on the server
21
Writing Servlets Put your.java and.class files in the right directory –tomcat/webapps/pace/WEB-INF/classes To compile a Servlet you must have your CLASSPATH environment variable set to the location of the servlet.jar file. –/tomcat/common/lib/servlet.jar (or servlet- bin.jar)
22
Servlet API JSDK (Java Servlet Development Kit) It contains 2 packages: –Generic Servlet Interface: javax.servlet –Classes derived from generic servlet interface for HTTP requests: javax.servlet.http
23
Java classes and interfaces http is the most commonly used protocol w.r.t. Servlets HTTPServlet provides an abstract class to be subclassed to create an HTTP Servlet suitable for a Web site. HTTPServletRequest interface –Allows submission of key/value pairs to the server HTTPServletResponse interface –Creates object that can be modified by the Servlet and returned from the Servlet
24
HTTPServlet class Protected void doGet(HttpServletRequest req, HttpServletResponse resp) –Called by the server to allow a Servlet to handle a GET request. Protected void doPost(HttpServletRequest req, HttpServletResponse resp) –Called by the server to allow a Servlet to handle a POST request.
25
HTTPServletRequest interface Public String getParameter(String key) Public String[] getParameterValues(String key) Public Enumeration getParameterNames()
26
HTTPServletResponse interface Public void setContentType(string type) ServletOutputStream getOutputStream() Public PrintWriter getWriter() throws IOException
27
Servlet format Import necessary packages –javax.servlet.* and javax.servlet.http.* –java.io-.* for any IOException that may occur Write a class that extends the HTTPServlet Class Write the doGet or doPost method Create your response using the res parameter of doGet or doPost
28
Sending a response to the browser Use the HTTPServletResponse object Set the type for the response (using setContentType) Create a ServletOutputStream object suitable for writing data in response using getOutputStream, use println to place text into this object and close the object. –Alternative: Create a PrintWriter object
29
Getting data from the Browser Use the HTTPServletRequest object Call getParameter() method passing the key of the key/value pair as a parameter Example: To retrieve the value of an identifier called name from the html form, use: req.getParameter(“name”);
30
Performance notes Servlet is instantiated once but run many times (each request generates a new thread) For optimal performance: –Avoid concatenating String objects (makes extra objects for JVM garbage collection)
31
Using Sessions HTTP is a stateless protocol Transactions are viewed as isolated events If multiple transactions need to be linked (example: shopping cart), you must maintain state Create a connection between client&server that persists over multiple requests
32
Using sessions HTTPSession interface Create a session using getSession(true) –The true parameter indicates: Check if session is there & return handle to it if it exists; create a new session otherwise. Use methods in HTTPSession to store and retrieve session values Session is established between client machine and web server (separate for each machine).
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.