Ch 3 - Java Servlets COSC 617 Jeff Schmitt September 21, 2006.

30
Ch 3 - Java Servlets COSC 617 Jeff Schmitt September 21, 2006

Transcript of Ch 3 - Java Servlets COSC 617 Jeff Schmitt September 21, 2006.

Ch 3 - Java Servlets

COSC 617

Jeff Schmitt

September 21, 2006

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

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 API’s of Java platform• Basis of JSP technology• Basis of Struts and JSF frameworks

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

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 on

standard output

Writing servlets

• public class MyServlet extends javax.servlet.GenericServlet {

• public void service(ServletRequest req, ServletResponse resp)

• throws ServletException, IOException {• Resp.SetContentType(“text/plain”);• …• }• }

GenericServlet

• public class MyServlet extends javax.servlet.GenericServlet {

• public void service(ServletRequest req, ServletResponse resp)

• throws ServletException, IOException {• resp.SetContentType(“text/plain”);• …• }• }

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);• }

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 doesn’t know• getServletInfo() method

– Returns String for logging purposes

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”

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

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 is found

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() and

getResourceAsStream(request.getContextPath() + “/index.html”)

• To retrieve context-wide initialization parameters, servlet uses getInitParameter() and getInitParameterNames()

• To access a range of information about the local environment, shared with other servlets in same servlet context, servlet uses getAttribute(), setAttribute(), removeAttribute(), getAttributeNames()

HttpServletRequest interface

• Server creates object implementing this interface, 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()

Forms and Interaction

• <form method=get action=“/servlet/MyServlet”>– GET method appends parameters to action URL:

/servlet/MyServlet?userid=Jeff&pass=1234– This is called a query string (starting with ?)

• Username: <input type=text name=“userid” size=20>

• Password: <input type=password name=“pass” size=20>

• <input type=submit value=“Login”>

POST Method

• <form method=post …– Post method does not append parameters to action URL:

/servlet/MyServlet– Instead, parameters are sent in body of request where the

password is not visible as in GET method

• POST requests are not idempotent– From Mathematics – an idempotent unary operator definition:

whenever it is applied twice to any element, it gives the same result as if it were applied once.

– Cannot bookmark them– Are not safely repeatable– Can’t be reloaded – browsers treat them specially, ask user

HEAD, and Other Methods

• HEAD – returns headers only• PUT, DELETE – create and remove resources

from the web server• TRACE – returns the request headers to the

client• doXXX() methods (XXX is one of the four)• Most servlet programmers ignore these methods• Default implementation informs user that request

is unsupported or provides minimal implementation

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.

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 – doesn’t come back

d.forward(req, resp);

• Request dispatching is Different from sendRedirect()– browser not involved– from user perspective, URL is unchanged

Status Codes

response.sendError,HttpServletResponse.SC_NOT_FOUND, “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

Servlet Exceptions

• ServletException – thrown to indicate a general servlet problem

• try { … } catch (Exception ex) { throw new ServletException(ex); }

• UnavailableException, a derivative of ServletException, notifies the server that servlet is going to be temporarily unavailable

Servlet Context Initialization

• Application-level events use a listener style interface

• Opportunity to create and share application-level resources 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.

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() -- user’s ID• getAuthType() -- Basic, Digest, or SSL• isUserInRole() – for dynamic content decisions• getUserPrincipal() – returns a

java.security.Principal object identifying the user

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 a

destination resource (servlet or JSP)• Set up a filter for a particular request path, (like a

servlet mapping) such as *.jsp• Filter resource calls doFilter() to advance to next

filter in the chain, if no more filters, request is passed to ultimate destination

Thread Safety

• Multithreaded = one servlet, multiple requests simultaneously

• Threadsafe – not using class variables since one copy of these variables is shared by all threads

• Synchronized blocks of code, all threads wait until they can enter, one at a time

• Servlet 2.4 deprecates SingleThreadModel interface – could not resolve all potential threading issues.

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<cookies.length;i++) {– cookies[i].getName cookies[i].getAttribute

Session Tracking

• For tracking individual users through the site• Application needs stateful environment whereas

the web is inherently stateless• Previously, applications had to resort to

complicated code, using cookies, hidden variables in forms, rewriting URLs to contain state information

• Delegates most of the user-tracking functions to the server

• Server creates object javax.servlet.http.HttpSession

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 with session.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”)

JDBC

• Load the driver class

• Get a connection

• Create a statement

• Execute the query, returns ResultSet

• Iterate through ResultSet

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 query Statement stmt = conn.createStatement (); ResultSet rset = stmt.executeQuery ("select ticker from stocks");

• // Iterate through the result and print the employee names while (rset.next ()) { out.println (rset.getString (1)); }