View
236
Download
0
Category
Preview:
Citation preview
8/7/2019 Ch3-Java Servlets
1/30
Ch 3 - Java ServletsCOSC 617
Jeff SchmittSeptember 21, 2006
8/7/2019 Ch3-Java Servlets
2/30
Java Servlet API The predominant language for server-side
programming Standard way to extend server to generate
dynamic content Web browsers are universally available thin
clients Web server is middleware for running
application logic User sends request server invokes servlet
servlet takes request and generates response-returned to user
8/7/2019 Ch3-Java Servlets
3/30
Advantages of Servlet API CGI, ISAPI, ASP, PHP, etc also generate
dynamic content Standard, stable, supported API multithreaded for improved performance Persistent between invovations, improved
performance 100% portable between OS and servers Access to all APIs of Java platform Basis of JSP technology Basis of Struts and JSF frameworks
8/7/2019 Ch3-Java Servlets
4/30
Servlet Basics Packages:
javax.servlet, javax.servlet.http Runs in servlet container such as Tomcat
Tomcat 4.x for Servlet 2.3 API Tomcat 5.x for Servlet 2.4 API Servlet lifecycle
Persistent (remains in memory between requests) Startup overhead occurrs only once init() method runs at first request service() method for each request destroy() method when server shuts down
8/7/2019 Ch3-Java Servlets
5/30
Common Gateway Interface (CGI)
Not persistent Not multithreaded Not high performancce Any language that can read standard input, write
standard output and read environment variables Server sends request information specially
encoded on standard input Server expects response information onstandard output
8/7/2019 Ch3-Java Servlets
6/30
Writing servlets
public class MyServlet extendsjavax.servlet.GenericServlet {
public void service(ServletRequest req,ServletResponse resp)
throws ServletException, IOException { Resp.SetContentType(text/plain); } }
8/7/2019 Ch3-Java Servlets
7/30
GenericServlet
public class MyServlet extendsjavax.servlet.GenericServlet {
public void service(ServletRequest req,ServletResponse resp)
throws ServletException, IOException { resp.SetContentType(text/plain); } }
8/7/2019 Ch3-Java Servlets
8/30
HttpServlet public class MyServlet extends
javax.servlet.http.HttpServlet { public void doGet(ServletRequest req, ServletResponse
resp) throws ServletException, IOException { resp.SetContentType(text/plain); PrintWriter out = resp.getWriter(); out.println(Hello, world); } public void doPost(ServletRequest req, ServletResponse
resp) throws ServletException, IOException { doGet(req, resp); }
8/7/2019 Ch3-Java Servlets
9/30
HttpServlet doPost does three things
Set output type text/plain MIME type getWriter() method for out stream Print on out stream
getLastModified() method To cache content if content delivered by a servlet has
not changed Return Long =time content last changed
Default implementation returns a negative number servlet doesnt know getServletInfo() method
Returns String for logging purposes
8/7/2019 Ch3-Java Servlets
10/30
Web Applications
Consists of a set of resources including Servlets, Static content, JSP files, Class libraries
Servlet context, a particular path on server to identify the web
application Servlets have an isolated, protected environment to
operate in without interference ServletContext class where servlets running in same
context can use this to communicate with each other Example servlet context: /catalog request.getContextPath() + /servlet/CatalogServlet
8/7/2019 Ch3-Java Servlets
11/30
Web App Structure
Directory tree Static resources: /
Packed classes: /WEB-INF/lib/*.jar Unpacked classes: /WEB-INF/classes/*.class Deployment descriptor: /WEB-INF/web.xml
Configuration information for the servlets including Names, servlet (path) mapprings, initialization
parameters, context-level configuration
8/7/2019 Ch3-Java Servlets
12/30
Servlet Path Mappings Servlets are not files, so must be mapped to URIs (Uniform
Resource Identifiers) Servet container can set default, typically /servlet/* Example: /servlet/MyPacPageServlet can invoke
PageServlet.class Mapping by
Exact path: /store/chairs Prefix: /store/*
Extension: *.page A servlet mapped to / path becomes the default servlet for the application and is invoked when no other servlet isfound
8/7/2019 Ch3-Java Servlets
13/30
Servlet Context Methods Resources such as index.html can be accessed through
web server or by servlet Servlet uses request.getContextPath() to identify its context path,
for example: /app
Servlet uses getResource() andgetResourceAsStream(request.getContextPath() + /index.html)
To retrieve context-wide initialization parameters, servletuses getInitParameter() and getInitParameterNames()
To access a range of information about the localenvironment, shared with other servlets in same servletcontext, servlet uses getAttribute(), setAttribute(),removeAttribute(), getAttributeNames()
8/7/2019 Ch3-Java Servlets
14/30
HttpServletRequest interface
Server creates object implementing thisinterface, passes it to servlet. Allows access to
URL info: getProtocol(), getServerName(),getPort(), getScheme()
User host name: getRemoteHost() Parameter info: (variables from input form):
.getParameterNames(), getParameter() HTTP specific request data:getHeaderNames(), getHeader(), getAuthType()
8/7/2019 Ch3-Java Servlets
15/30
Forms and Interaction
GET method appends parameters to action URL:
/servlet/MyServlet?userid=Jeff&pass=1234
This is called a query string (starting with ?) Username: Password:
8/7/2019 Ch3-Java Servlets
16/30
POST Method
8/7/2019 Ch3-Java Servlets
17/30
8/7/2019 Ch3-Java Servlets
18/30
HttpServletResponse Specify the MIME type of the response
.setContentType(image/gif); Called before .getWriter() so correct Charset is used
Two methods for producing output streams: Java.io.Printwriter out = resp.getWriter() ServletOutputStream str = resp.getOutputStream()
//used for non-text responses
HTTP response headers and status code setHeader(), containsHeader(), setStatus(), 200 OK, 404 Not Found, etc. sendError() sendRedirect(), sets Location header and status code for
redirect. Causes browser to make another request.
8/7/2019 Ch3-Java Servlets
19/30
RequestDispatcher Can forward request to another servlet Can include bits of content from other servlets in its own
response RequestDispatcher d =
req.getRequestDispatcher(/servlet/OtherServlet); Either include goes and comes back
d.include(req, resp); Or forward doesnt come back
d.forward(req, resp);
Request dispatching is Different from sendRedirect() browser not involved from user perspective, URL is unchanged
8/7/2019 Ch3-Java Servlets
20/30
Status Codesresponse.sendError,HttpServletResponse.SC_NOT_FOUN
D, Could not find it); SC_OK = 200 // the success code SC_NO_CONTENT = 204 //content unchanged -- browser view
stays at the form but avoids contains no data error message SC_MOVED_PERMANENTLY = 301
// browser uses Location header SC_MOVED_TEMPORARILY = 302
// browser uses Location header SC_UNAUTHORIZED = 401 // wrong authentication SC_NOT_FOUND = 404 // page not found SC_INTERNAL_SERVER_ERROR = 500 SC_NOT_IMPLEMENTED = 501 // for HEADER, PUT, DELETE SC_SERVICE_UNAVAILABLE = 503
8/7/2019 Ch3-Java Servlets
21/30
Servlet Exceptions
ServletException thrown to indicate a generalservlet problem
try { } catch (Exception ex) {
throw new ServletException(ex);}
UnavailableException, a derivative of ServletException, notifies the server that servletis going to be temporarily unavailable
8/7/2019 Ch3-Java Servlets
22/30
Servlet Context Initialization
Application-level events use a listener styleinterface
Opportunity to create and share application-levelresources such as DB connection pools
Classes that implement ServletContextListener are notified when the context is initialized or destroyed.
Context listeners are associated with their context with the application-level web.xml file.
8/7/2019 Ch3-Java Servlets
23/30
Security J2EE User Role Model -- users can be assigned
one or more roles web.xml defines which servlets and resources
are protected and which users have access particular role allows access to specific
protected resources getRemoteUser() -- users ID getAuthType() -- Basic, Digest, or SSL isUserInRole() for dynamic content decisions getUserPrincipal() returns a
java.security.Principal object identifying the user
8/7/2019 Ch3-Java Servlets
24/30
Servlet Filters Filters perform processing on the request Implement logging, control security, set up
connection-specific objects
javax.servlet.Filter = filter resource class Filter chain zero or more Filter objects and adestination resource (servlet or JSP)
Set up a filter for a particular request path, (like aservlet mapping) such as *.jsp
Filter resource calls doFilter() to advance to nextfilter in the chain, if no more filters, request ispassed to ultimate destination
8/7/2019 Ch3-Java Servlets
25/30
Thread Safety
Multithreaded = one servlet, multiple requestssimultaneously
Threadsafe not using class variables sinceone copy of these variables is shared by allthreads
Synchronized blocks of code, all threads waituntil they can enter, one at a time
Servlet 2.4 deprecates SingleThreadModelinterface could not resolve all potentialthreading issues.
8/7/2019 Ch3-Java Servlets
26/30
Cookies Persistent client-side storage of data known to server and sent to client Cookie is multiple names and values. Value limited to
4096 bytes has expiration date, and a server name (returned to
same host and not to others) Cookie is sent in HTTP header of response resp.addCookie(name,value)
Cookie is returned to server in HTTP header of subsequent request
cookies = req.getCookies(); For (int i=0;i
8/7/2019 Ch3-Java Servlets
27/30
Session Tracking For tracking individual users through the site Application needs stateful environment whereas
the web is inherently stateless
Previously, applications had to resort tocomplicated code, using cookies, hiddenvariables in forms, rewriting URLs to containstate information
Delegates most of the user-tracking functions tothe server Server creates objectjavax.servlet.http.HttpSession
8/7/2019 Ch3-Java Servlets
28/30
Session Servlet uses req.getSession(true)
Boolean arg handles case if no current session object Should new one be created or not Session.isNew() useful to detect new session object
Servlet binds data to the HttpSession object withsession.setAttribute(hits,new Integer(34));
Server assigns unique session ID, stored in a cookie If cookies are not available, server uses URL rewriting.
To create links, with session ID use resp.encodeURL(/servlet/View)or
resp.encodeRedirectURL(/servlet/View)
8/7/2019 Ch3-Java Servlets
29/30
JDBC
Load the driver class Get a connection Create a statement Execute the query, returns ResultSet Iterate through ResultSet
8/7/2019 Ch3-Java Servlets
30/30
JDBC Example
// Load the Oracle JDBC driver Class.forName ("oracle.jdbc.driver.OracleDriver"); //Connect to DB server as authorized user
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@orion.towson.edu:1521:cosc",account, password);
// Create a JDBC Statement to hold SQL queryStatement stmt = conn.createStatement ();ResultSet rset = stmt.executeQuery ("select ticker fromstocks");
// Iterate through the result and print the employeenameswhile (rset.next ()) {
out.println (rset.getString (1));}
Recommended