1.15k likes | 1.41k Vues
Java Enterprise Edition. Java EE Architecture. Tools Required. An IDE which helps Java Application Development , source code writing,compilation, integration and deployment of the components necesssary for Java EE. eg. NetBeans, Eclipse, Jbuilder, Jdeveloper etc.
E N D
Tools Required • An IDE which helps Java Application Development , source code writing,compilation, integration and deployment of the components necesssary for Java EE. eg. NetBeans, Eclipse, Jbuilder, Jdeveloper etc. • An Application Server which provides various containers to deploy components. eg. Glassfish, Tomcat, Jboss, Weblogic etc. • A complete RDBMS (Oracle, MySQL, Sybase)
Servlet Introduction • What is Servlet? • A java class which runs in a web server environment. • A compatible web server manages the execution of servlet with the help of servlet engine when requested by client using an http request. • It gives an http response to the client which can be displayed on browsers.
Why it should be used • Why it should be used? • Efficiency • Persistency • Portability • Robustness • Extensibility • Security
GenericServlet & HttpServlet • A java class qualifies to be a Servlet if it extends javax.servlet.http.HttpServlet • HttpServlet class is extended from GenericServlet class • GenericServlet.service() method has been defined as an abstract method • The two objects that the service() method receives are ServletRequest and ServletResponse • ServletRequest Object • Holds information that is being sent to the servlet • ServletResponse Object • Holds data that is being sent back to the client
GenericServlet & HttpServlet • Unlike the GenericServlet, when extending HttpServlet, don’t have to implement the service() method. It is already implemented for you • When HttpServlet.service( ) is invoked, it calls doGet( ) or doPost( ), depending upon how data is sent from the client • HttpServletRequest and HttpServletResponse classes are just extensions of ServletRequest and ServletResponse with HTTP-specific information stored in them
Servlet LifeCycle Uninstantiated Instantiated Success Initialized Failure Success Servicing Requests Idle Busy Request Serviced Destroy Request Recieved & all service threads idle Destroy Unload
Servlet Methods • The init Method • The init method is called when the servlet is first created and is not called again for each user request. public void init() throws ServletException { // Initialization code... } public void init(ServletConfig config) throws ServletException { super.init(config); // Initialization code... }
Servlet Methods • The service Method • The service method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc., as appropriate. public void service(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { // Servlet Code }
Servlet Method • The doGet, doPost, and doXxx Methods • These methods contain the real meat of your servlet. • Ninety-nine percent of the time, you only care about GET and/or POST requests, so you override doGet and/or doPost. However, if you want to, you can also override doDelete for DELETE requests, doPut for PUT, doOptions for OPTIONS, and doTrace for TRACE.
Servlet Method • The destroy Method • The server may decide to remove a previously loaded servlet instance, perhaps because it is explicitly asked to do so by the server administrator, or perhaps because the servlet is idle for a long time. Before it does, however, it calls the servlet’s destroy method. • This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities. Be aware, however, that it is possible for the Web server to crash.
Servlet Architecture The Request Object • Encapsulates all request information from the client • request headers • form data and query parameters • other client data{session info, cookies, path ...etc.} The Response Object • Encapsulates all data sent back to client • response headers • OutputStream to write data to the client • setting cookies http://localhost:8080/examples/
Servlet Architecture • Request Object Methods • String getContextPath() • Cookies[] getCookies() • String getHeader(String headerName) • Enumeration getHeaderNames() • Enumeration getHeaders(String header) • String getParameter(String parameterName) • String[] getparameterValues(String parameterNames) • Enumeration getParameterNames() • String getQueryString() • HttpSession getSession()
Servlet Architecture • Response Object Methods • void setStatus(int statusCode); statusCode can be SC_OK, SC_MOVED_TEMPORARILY SC_NOT_FOUND, SC_BAD_REQUEST. • void sendError(int code, String msg) • void sendRedirect(String url) • void addCookie(Cookie) • void setContentLength(int contentLength) • void setContentType(String contentType)
Servlet Architecture • Content Type • application/msword • application/octet-stream (unrecognised binary data) • application/pdf • application/zip • text/html • image/gif • image/jpeg • video/mpeg • video/quicktime
Servlet Architecture The HttpSession Object • Allows for the storage of transient, session data • Easy way to identify a single user between page requests • Servlets can obtain data from session, modify and store it again • Typical Example - Online Store • Customer profile information • Shopping Cart • protected void processRequest(HttpServletRequest request, HttpServletResponse response) • {HttpSession session = request.getSession(); • ..... }
HttpSession Methods • public Object getAttribute(String name) • Extracts a previously stored value from a session object. Returns null if no value is associated with given name. • public void setAttribute(String name, Object value) • Associates a value with a name. • public void removeAttribute(String name) • Removes any values associated with designated name. • getAttributeNames() • public void invalidate() • public boolean isNew() • public void setMaxInactiveInterval(int seconds) • public String getId()
Accessing Initialization Parameters ServletConfig • ServletConfig Object is used for accessing the servlet related information. • ServletConfig object is accessible in init() and obtain it with getServletConfig() of javax.servlet.Servlet interface. ServletConfig sc = getServletConfig(); ServletConfig methods • getInitParameter() • getInitParameterNames() • getServletContext() • getServletName()
Accessing InitializationParameters Servlet Context • There is one instance object of the ServletContext interface associated with each Web application deployed into a container. • <context-param> <param-name>Developer</param-name> <param-value>kamlendu@sgumscit.com</param-value> </context-param> • getInitParameter() • getInitParameterNames() • setAttribute() • getAttribute() • getAttributeNames() • removeAttribute()
Handling Cookies For adding cookie Cookie cookie = new Cookie("cookieName", "cookieValue"); response.addCookie(cookie); For retrieving / reading cookie Cookie[] cookies = request.getCookies(); if(cookies != null) { for(int i=0; i < cookies.length; i++) { Cookie thisCookie = cookies[i]; if (thisCookie.getName().equals("cookieName")) { String value = thisCookie.getValue(); } }}
Handling Cookies Setting cookie Life Cookie userCookie = new Cookie("user", "uid1234"); userCookie.setMaxAge(60*60*24*365); // 1 year response.addCookie(userCookie);
Dispatching Requests • The key to letting servlets forward requests or include external content is to use a RequestDispatcher. • Obtain a RequestDispatcher by calling the getRequestDispatcher method of ServletContext, supplying a URL relative to the server root. String url = "/presentation"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url); dispatcher.forward(request, response); dispatcher.include(request, response);
Dispatching Requests • RequestDispatcher Methods • void forward(ServletRequest request, ServletResponse response) • void include(ServletRequest request, ServletResponse response) • The forward method is used when a request is going to be serviced by other resource such as JSP or servlet. • The include method includes the output from another resources in the current output. • The important thing is that it is not a redirection. So the fact that the response came from another servlet is transparent to the client.
Servlet Filters • Since Servlet API 2.3, most significant part of API 2.3 • Filters are not servlets; they do not actually create a response. • They are preprocessors of the request before it reaches a servlet, and/or postprocessors of the response leaving a servlet. • In a sense, filters are a mature version of the old "servlet chaining" concept. • Practical filter ideas include • authentication filters, • logging and auditing filters, • image conversion filters, • data compression filters, encryption filters, tokenizing filters, filters that trigger resource access events, XSLT filters that transform XML content, or MIME-type chain filters (just like servlet chaining).
Servlet Filters • A filter can: • Intercept a servlet's invocation before the servlet is called • Examine a request before a servlet is called. • Modify the request headers and request data by providing a customized version of the request object that wraps the real request • Modify the response headers and response data by providing a customized version of the response object that wraps the real response • Intercept a servlet's invocation after the servlet is called • We can configure a filter to act on a servlet or group of servlets;
Servlet Filters • A filter implements javax.servlet.Filter and defines its three methods: • void setFilterConfig(FilterConfig config) • server calls setFilterConfig() once to set the filter's configuration object • FilterConfig getFilterConfig() • Returns the filter's configuration object • FilterConfig interface has methods to retrieve the filter's name, its init parameters, and the active servlet context. • void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) • Performs the actual filtering work
Servlet Filters • To use this filter, you must declare it in the web.xml deployment descriptor using the <filter>tag, as shown below: <filter> <filter-name>timerFilter</filter-name> <filter-class>TimerFilter</filter-class> </filter> <filter-mapping> <filter-name>timerFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Servlet Specifications • Java Servlet API 2.2 • Servlets are now part of the Java Enterprise Edition specification • Servlets now embrace the notion of pluggable Web applications, which can be configured and deployed in a server-independent manner • Rules have been provided that define how servlets can be distributed across multiple back-end servers • Response output buffering has been added • Control over HTTP headers has been enhanced • New styles of request dispatching have been added • More advanced error handling can now be used
Servlet Specifications • Distributed applications • The Servlet 2.2 specification dictates that, for an app marked as distributable in its deployment descriptor, there will be a single ServletContext instance per JVM. • This means the context attributes cannot be used to share global information. Global information in a distributed app needs to be stored externally from the Web server, as is the case in database or EJB component. • For applications marked as distributable, Servers will use session affinity to efficiently manage user state across multiple back-end servers. This means that all requests that are part of a single session from a particular user are to be handled by only one JVM at a time. • All objects placed into a session by servlets in a distributed app must implement Serializable
Servlet Specifications • Response buffering • One of the most useful features added in version 2.2 of the servlet API is response buffering. A servlet now has control over whether the server buffers its response, and may dictate how large a buffer the server can use. • Five new methods • setBufferSize(int size) • getBufferSize() • isCommitted() • reset() • flushBuffer() • It sends content in the buffer to the client and commits the response.
Servlet Specifications • Support for double headers • There's a new method in HttpServletRequest called getHeaders() that can return multiple values for a given header. This was needed because some headers, such as Accept-Language, can send multiple header values: • Accept-Language: en • Accept-Language: fr • Accept-Language: ja • The new addHeader(String name, String value) method sets the header to the given value. While the traditional setHeader() method would replace any existing value or values, addHeader() leaves current settings alone and just sets an additional value. There's also addIntHeader(String name, int value) and addDateHeader(String name, long date).
Servlet Specifications • Better dispatching • Finally, Java Servlet API 2.2 provides more convenient request dispatching. • There's a new getNamedDispatcher(String name) method in ServletContext that lets a servlet dispatch to a component specified by its registered name instead of a full URI path. This allows dispatching to a component that may not be publicly accessible on any URI path
Servlet Specifications • Java Servlet API 2.3 • Servlets now require JDK 1.2 or later • A filter mechanism has been created (finally!) • The technique to express inter-JAR dependencies has been formalized • Rules for class loading have been clarified • New error and security attributes have been added • The HttpUtils class has been deprecated • Several DTD behaviors have been expanded and clarified
Servlet Specifications • Inter-JAR dependencies • A WAR file (Web application archive file, added in API 2.2) requires various other JAR libraries to exist on the server and operate correctly. For example, a Web application using the ParameterParser class needs cos.jar in the classpath. A Web application using WebMacro needs webmacro.jar. • Before API 2.3, either those dependencies had to be documented (as if anyone actually reads documentation!) or each Web application had to include all its required jar files in its own WEB-INF/lib directory (unnecessarily bloating each Web application). • Servlet API 2.3 lets you express JAR dependencies within the WAR using the WAR's META-INF/MANIFEST.MF entry. • If a dependency can't be satisfied, a server can politely reject the Web application at deployment time instead of causing an obscure error message at runtime.
Servlet Specifications • Class loaders • In API 2.3, a servlet container, will ensure that classes in a Web application not be allowed to see the server's implementation classes. In other words, the class loaders should be kept separate. • It eliminates the possibility of a collision between Web application classes and server classes.
Servlet Specifications • Error and Security • You can configure a Web application so that certain error status codes or exception types cause specific pages to be displayed • <web-app> <!-- ..... --> • <error-page> <error-code> 404 </error-code> <location> /404.html </location> • </error-page> • <error-page> <exception-type> javax.servlet.ServletException </exception-type> <location> /servlet/ErrorDisplay </location> • </error-page> • <!-- ..... --> • </web-app>
Servlet Specifications • Error and Security • Servlet API 2.3 adds two new request attributes that can help a servlet make an informed decision about how to handle secure HTTPS connections. • For requests made using HTTPS, the server will provide these new request attributes: • javax.servlet.request.cipher_suite • A String representing the cipher suite used by HTTPS, if any • javax.servlet.request.key_size • An Integer representing the bit size of the algorithm, if any • A servlet can use those attributes to programmatically decide if the connection is secure enough to proceed. An application may reject connections with small bitsizes or untrusted algorithms. • Another addition, getAuthType() method that returns the type of authentication used to identify a client has been defined to return one of the four new static final String constants in the HttpServletRequest class: BASIC_AUTH, DIGEST_AUTH, CLIENT_CERT_AUTH, and FORM_AUTH.
Servlet Specifications • DTD (Document Type Defination) clarifications • Finally, Servlet API 2.3 ties up a few loose ends regarding the web.xml deployment descriptor behavior. It's now mandated that you trim text values in the web.xml file before use. (In standard non-validated XML, all white space is generally preserved.) This rule ensures that the following two entries can be treated identically: <servlet-name>hello<servlet-name> and <servlet-name> hello </servlet-name>
Servlet Specifications Java Servlet Specification 2.4 • On March 7, 2003, Sun Microsystems (working with the JSR (Java Specification Request) 154 expert group) published the "Proposed Final Draft 2" of the Servlet 2.4 specification 1. Upgraded supports for Http, J2SE, and J2EE: Servlet 2.4 depends on Http1.1 and J2SE 1.3. 2. Additional ServletRequest methods : In Servlet 2.4 four new methods are added in the ServletRequest • getRemotePort(): It returns the IP source port of the client. • getLocalName(): It returns the host name on which the request was recieved. • getLocalAddr(): It returns the IP address on which the request was recieved. • getLocalPort(): It returns the IP port number.
Servlet Specifications Java Servlet Specification 2.4 (contd..) 3.New Support for Internationalization and charset choice: To provide support of internationization, Servlet 2.4 has added two new methods in the ServletResponse interface. • setCharacterEncoding(String encoding): The purpose of this method is to set the response's character encoding. This method helps us to pass a charset parameter to setContentType(String) or passing a Locale to setLocale(Locale). We can now avoid setting the charset in the setContentType("text/html;charset=UTF-8") as setCharacterEncoding() method pairs with the pre-existing getCharacterEncoding() method to manipulate and view the response's character encoding. • getContentType(): It is responsible for returning the response's content type. The content type can be dynamically set with a combination of setContentType(), setLocale(), and setCharacterEncoding() calls, and the method getContentType() provides a way to view the generated type string.
Servlet Specifications Java Servlet Specification 2.4 (contd..) 4.New features has been added in RequestDispatcher: In Servlet 2.4 five new request attributes has been added for providing extra information during a RequestDispatcher forward() call. This features has been added is Servlet 2.4 to know the true original request URI. The following request attributes are: • javax.servlet.forward.request_uri • javax.servlet.forward.context_path • javax.servlet.forward.servlet_path • javax.servlet.forward.path_info • javax.servlet.forward.query_string
Servlet Specifications Java Servlet Specification 2.4 (contd..) 5. In Servlet 2.4 the SingleThreadModel interface has been deprecated. 6. HttpSession details and interaction with logins has been clarified: The new method HttpSession.logout() has been added in Servlet 2.4. Now session allows zero or negative values in the <session-timeout> element to indicate sessions should never time out. 7. Welcome file behavior and Classloading has been clarified. In servlet 2.4 welcome file can be a servlet. 8. The web.xml file now uses XML Schema: Version 2.4 servers must still accept the 2.2 and 2.3 deployment descriptor formats, but all new elements are solely specified in Schema.
Servlet Specifications Java Servlet Specification 2.5 • On September 26, 2005, Sun Microsystems and the Java Specification Request 154 Expert Group issued a maintenance release of the Servlet API. This release added several new features and changes, and made enough of an impact on servlets to justify a bump in the version number to Servlet 2.5. • Apache Tomcat version 6.0 implements the Servlet 2.5 • Jetty server and Sun's GlassFish server also implements Servlet 2.5