Java Enterprise Edition The Web Tier Malik SAHEB
Objectives of this Course Focus on Presentation
The Presentation Tier as a Web application Managed by the Web Container as a Web Application Web applications are of the following types: Presentation-oriented: generate interactive web pages containing various types of markup language (HTML, XHTML, XML,...) Service-oriented: implements the endpoint of a web service. Often clients of service-oriented web applications.
.... JavaMail JPA JTA Connectors JMS Management WS Metadata Web Services JACC JASPIC JAXR JAX-RS JAX-WS JAX-RPC.... JavaMail JPA JTA Connectors JMS Management WS Metadata Web Services JACC JASPIC JAXR JAX-RS JAX-WS JAX-RPC JPA Management WS Metadata Web Services JMS JAXR JAX-WS JAX-RPC Java EE Containers Servlet Web Container JSP JSF RMI/IIOP EJB Container EJB SAAJ Java SE SAAJ Java SE HTTP SSL HTTP SSL Client Container RMI/IIOP Applet Container Client Application JDBC Applet JDBC Database Java SE SAAJ Java SE
Java Web Application request handling Servlet technology serves as the base to build Web Applications and used as a layer below other techniques, such JSP, JSF,...
Servlets
Servlets Servlets are programs written in Java which run on the web server and communicate with the web browser using HTTP and HTML The servlet runs inside a container called a Servlet Engine The communication services, security etc are provided by the container Container runs within the JVM Hides coding issues around with Sockets, TCP/IP or Java serialisation. Servlets communicate with the browser using only HTML and HTTP Compatible with all web browsers Servlets run only on the server Servlets do not need any component to be stored or installed on the client 7
Servlets features Produce dynamic web content. Processing HTTP Requests with Servlets. Servlet API GET and POST requests. Passing parameters to servlets. Servlet API - getparameter HTTP Sessions. Keeping server-side state for a client. Creating and deploying a packaged web application War file. More advanced topics Session tracking, request dispatcher, filters, events
Servlet Architecture http://crimeportal.org/killerapp/assassination HTTP Client Web Server Servlet Container Other Web App 1 Other Web App 2 Request Dispatcher /killerapp Killer App /assassination Assassination Servlet
Servlet Lifecycle I: 1. Web browser sends HTTP Post or Get message to Web Server 2. Web server redirect the request to the servlet. If the servlet is not already loaded it loads it and calls the servlet's init method 3. The web browser passes the HTML request to the servlet's service method Client Web Browser HTML Get or Post Web Server Server Servlet Container Init Service Servlet 10
Servlet Lifecycle II: 4. Service method calls the doget or dopost method of the servlet 5. Method executes and generates HTML which is passed back to the web browser. 6. Threads in Service method exit Client Server Servlet Container Init Web Browser HTML Web Server HTML Service Servlet dopost HTML doget Destroy 11
Servlet Lifecycle III: 4. When the servlet container decides to unload the servlet it calls the destroy method At shutdown or if memory is short Will not happen until all active threads finish (exit or time out) Client Web Browser Web Server Server Servlet Engine Init Service Servlet dopost doget Destroy 12
Writing a Servlet All Servlets extend the Servlet class Normally extends HttpServlet which is derived from Servlet class HttpServlet class provides default implementations of Init: Need to override if some additional initialisation required such as open a database connection. Destroy: Need to override if some additional cleaning up required such as closing a database connection. Service: Not normally be overridden doget: Normally over-ridden as HTTP Get is the default web browser request which causes the doget method of the servlet to be invoked. dopost: Over-ridden if HTTP Post is responded to.
A Simple Example import javax.servlet.*; import javax.servlet.http.*; Import java.io.*; public class AssassinationServlet extends HttpServlet { public void doget ( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { PrintWriter out = response.getwriter() ; out.println( "<html><head><title>assassination Servlet</title></head>" ) ; out.println( "<body><b>bang!!<b></body>" ) ; out.println( "</html>" ) ; out.close(); } public void dopost ( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { doget(request,response); // just calls doget method. } } AssassinationServlet.java
Request and Response Request and Response arguments are passed to doget, dopost, etc. HttpServletRequest provides access to: Named parameters passed to URL. Client information remote host, security info if authenticated. Stored attributes (inserted using the setattribute method). Session information (more later). HttpServletResponse Used to write the output to the client. Can be text (getwriter()) or binary (getoutputstream()).
Request Parameters A browser can pass values to the server side by embedding them in the GET URL They are passed using standard CGI format, name-value pairs: http://crimeportal.org/killerapp/assassination?who=fredo&how=pistol The web container parses the URL and stores them in the HttpServletRequest object. The servlet programmer then has access to them using the getparameter() method: public void doget (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getwriter() ; out.println( "<html><head><title>sicilian Message</title></head>" ) ; out.println( "<body>" + req.getparameter("who") + " sleeps with the fishes.</body>" ) ; out.println( "</html>" ) ; out.close(); }
Client Output
Using Forms and HTTP Post Post is an HTTP alternative to GET. Must be used with forms (not URLs). No limit on parameter size. Results not cached by browser. <html> <html> <head><title>assassination Servlet</title></head> <body> <body> <form <form method= method= "POST" "POST" action="assassination"> Name: Name: <input <input type="text" type="text" name="who"> name="who"> Method: Method: <input <input type="text" type="text" name="how"> name="how"> <br><br> <br><br> <input <input type="submit" type="submit" value="whack" value="whack" name="submit"> </form> </form> </body> </body> </html> </html>
Deployment Descriptor - web.xml <web-app> <display-name>crime Portal Killer Application</display-name> <description>use with care</description> <!-- register the servlet - name and full class name --> <servlet> <servlet-name>whacker</servlet-name> <servlet-class>crimeportal.assassinationservlet</servletclass> </servlet> <!-- set up the mapping to to a URL (or URLs) --> <servlet-mapping> <servlet-name>whacker</servlet-name> <url-pattern>/assassination</url-pattern> </servlet-mapping> </web-app> web.xml
Deployment - the WAR File killerapp.war WEB-INF whack. html web.xml vendor.xml classes crimeportal AssassinationServlet
Session Tracking In Java EE, the web-tier has the responsibility of tracking a user session. However, Http is a stateless request/response protocol. There is no inherent concept of a session. Cookies allow requests from the same client to be recognised. Using HttpServlet gives you session management for free. Can maintain state for a user across multiple requests. The session ID is passed as a cookie or by rewriting URLs. Container handles it all - transparent to application. Essential for any serious online applications. The session is a private storage area for the application. Server code can add or remove objects (EJB references, shopping carts). Allows secure sessions to be handled for authenticated users. Session ID acts as client token.
HttpSession Interface Obtained by invoking getsession on HttpServletRequest. Two forms: getsession() creates new session instance or returns existing one. getsession(boolean create) as above, but only creates a new session if create is true. Otherwise, if no session already exists, returns null. Attributes (objects) can be stored, retrieved or removed from the session setattribute, getattribute, removeattribute methods. public void doget (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String who = req.getparameter("who"); HttpSession sesh = req.getsession(); // // store attribute for future reference sesh.setattribute("themark", who); }
Ending Sessions Sessions usually have a timeout. Can be set in web.xml file. Can be read or set programmatically using get/setmaxinactiveinterval(). <web-app> <web-app> <session-config> <session-timeout>30</session-timeout> </session-config> </web-app> </web-app> web.xml web.xml Can call invalidate() on the session. Invalidates the session and unbinds any objects stored in it.
The Request Dispatcher (javax.servlet.requestdispatcher) Used to forward the request to another resource (servlet, JSP, HTML). On the same server. Allows processing by multiple resources. servlet chaining. Can be used to implement control flow logic. Key part of controller servlet in Model-2 frameworks such as struts. Example usage: public void doget (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String path = "/forward/to/url"; RequestDispatcher rd rd = getservletcontext().getrequestdispatcher(path); rd.forward(request, response); }
The Request Dispatcher (continued) Also provides include Allows content to be included, the URL doesn t change Key to portals and other similar interfaces Usually dreadfully lower performance than concatenating strings/composing the interface directly. But its far easier to do.. Example usage: public void doget (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String path = "/include/url"; RequestDispatcher rd rd = getservletcontext().getrequestdispatcher(path); rd.include(request, response); }
Filters Filters can perform request and response pre-processing for the servlet. Can replace the request and response objects with customized ones. Can be linked together to form a chain. Can terminate a request. <filter> <filter-name>whack Filter</filter-name> <filter-class>crimeportal.whackfilter</filterclass> </filter> <filter-mapping> <!-- apply the filter to to a particular servlet --> <filter-name>whack Filter</filter-name> <servlet-name>whacker</servlet-name> </filter-mapping> web.xml
Application Lifecycle Events Now have ability to listen for web application events. ServletContextListener: context creation and destruction. HttpSessionListener: session creation and destruction. Listener classes must implement one of these interfaces. <web-app> <web-app> <listener> <listener> <listenerclass>crimeportal.sessionlistener</listener-class> </listener> </listener> <listener-...... </web-app> </web-app> web.xml web.xml
@Webservlet Annotation @WebServlet annotation is used to declare a servlet. Avoid the manipulation of the web.xml file @WebServlet( attribute1=value1, attribute2=value2,...... ) public class TheServlet extends javax.servlet.http.httpservlet { // // servlet code... } @WebServlet attributes are : name Description, Value, UrlPatterns, InitParams, LoadOnStartup, AsyncSupported, SmallIcon, largeicon Similarly there are: @WebListener, @WebFilter, @WebInitParam
Java Server Pages
The problem with Servlets Servlets are great for server side request processing. But not so good for rendering output. Producing anything other than simple HTML is very messy. Lots of out.println() statements. The HTML is embedded in Java code. Can t be edited separately. Makes designer/coder role separation impossible. Have to recompile the servlet class every time you make a change.
What are JSPs? JSP-JavaServer Pages is a server side programming language. It has the ability to integerate with HTML very easily to enhance the presentation of a page. JSP pages helps to differentiate the design from the programming logic of a web page. They are compiled into Java servlets when first accessed. The servlet is then compiled to Java bytecode. So JSPs are just servlets, as far as the server is concerned. The servlet generates the HTML code for the page. Special tags are used to embed the Java code in the page.
Servlet vs. JSP public class HelloWorldServlet extends HttpServlet { protected void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException { res.setcontenttype("text/html"); PrintWriter out = res.getwriter(); out.println("<html>"); out.println(" <head>"); out.println(" <title>bonjour tout le monde</title>"); out.println(" </head>"); out.println(" <body>"); out.println(" <h1>bonjour tout le monde</h1>"); out.println(" Nous sommes le " + (new java.util.date().tostring()) ); out.println(" </body>"); out.println("</html>"); } } Java code added in JSP Bonjour tout le monde Nous sommes le Sat Oct 26 11:30:28 CEST 2013 <html> <head> <title>bonjour tout le monde</title> </head> <body> <h1>bonjour tout le monde</h1> Nous sommes le <%= new java.util.date().tostring() %> </body> </html>
Architecture JSP pages are converted into Servlet then compiled before execution Translation and compilation are executed if necessary ; when the page is called the first time or modified.
Conversion JSP to Servlet public final class helloworldjsp_jsp extends org.apache.jasper.runtime.httpjspbase implements org.apache.jasper.runtime.jspsourcedependent { public void _jspservice(httpservletrequest request, HttpServletResponse response) throws java.io.ioexception, ServletException { HttpSession session = null;... try {... _jspx_out = out; out.write("<html>\r\n");out.write("\t<head>\r\n"); out.write("\t\t<title>bonjour tout le monde</title>\r\n"); out.write("\t</head>\r\n");out.write("\t<body>\r\n"); out.write("\t\t<h1>bonjour tout le monde</h1>\r\n"); out.write("\t\tnous sommes le ");out.print( new java.util.date().tostring() ); out.write(" et tout va bien.\r\n");out.write("\t</body>\r\n");out.write("</html>"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out;... if (_jspx_page_context!= null) _jspx_page_context.handlepageexception(t); } } finally { if (_jspxfactory!= null) _jspxfactory.releasepagecontext(_jspx_page_context); } }
JSP Lifecycle
Standard objects A JSP is a servlet so it has access to servlet parameters and properties. These are provided through named objects. These implicit objects include: request - HttpServletRequest. response - HttpServletResponse. session - HttpSession. out JspWriter.... They can be accessed directly by name in your JSP code. Just as with servlets.
Predefined Variable request: This variable specifies the data included in a http request. This variable takes value from the clients' browser to pass it over to the server. reponse: This variable specifies the data included in the http response. It is used with cookies and also in http headers. out: This variable specifies the output stream otherwise known as printwriter in a page context. session: This variable specifies the data associated with httpsession object with a specific session of a user. The main purpose of this object is to use the session information to maintain multiple page requests. application: this variable is used to share data with all application pages. config: This variable refers the java servlet configuration value. pagecontext: This variable is used to store the environment for the page like page attributes, access to the request, response and session objects. page: This variable is used to store the instance of the generated java servlet.
Expression Language in JSP JSP EL is used to set action attribute values from different sources at runtime. JSP EL always starts with a "$" followed by a "{" and ends with a "}". The expression is specified inside the brackets : ${expr} Examples ${2+3+4} Box Perimeter is: ${2*box.width + 2*box.height}
JSP EL Implicit Objects Implicit Objects Description pagescope Scoped variables from page scope requestscope sessionscope applicationscope param paramvalues header headervalues initparam cookie pagecontext Scoped variables from request scope Scoped variables from session scope Scoped variables from application scope Request parameters as strings Request parameters as collections of strings HTTP request headers as strings HTTP request headers as collections of strings Context-initialization parameters Cookie values The JSP PageContext object for the current page
JSP Implicit Objects - Example Example Result <html> <html> <body> <body> <form <form action="implicitobjects.jsp" method="get"> method="get"> NAME:<input NAME:<input type="text" type="text" name="nam"> name="nam"> <input <input type="submit"> type="submit"> </form> </form> <p><b>name</b> :: ${param.nam}</p> <p><b>header</b> <p><b>header</b> :: ${header["host"]}</p> <p><b>user <p><b>user AGENT</b>:${header["user-agent"]}</p> </html> </html> NAME NAME : william william HEADER HEADER : : localhost:8080 localhost:8080 USER USER AGENT:Mozilla/5.0 AGENT:Mozilla/5.0 (X11; (X11; Linux Linux x86_64) x86_64) AppleWebKit/537.36 AppleWebKit/537.36 (KHTML, (KHTML, like like Gecko) Gecko) Chrome/30.0.1599.114 Chrome/30.0.1599.114 Safari/537.36 Safari/537.36
JSP Tags - Directives These are messages to the container. They don t (directly) produce any output. They are delimited by <%@ %>. Page directives are used for page dependent properties such as: Import statements: <%@ page import= java.util.*; %> Error page declarations: <%@ page errorpage= /aaarrrghh.jsp %> Indicate if a page is a normal ou error page : <%@ page iserrorpage=false %> Content types <%@ page contenttype= text/html;gb2312 %> Include directives are used to include other source in the page: <%@ include file= otherstuff.html %>
JSP Tags - Scripting Used for computation within the page. Manipulate the page objects (beans, implicit objects). Used for iteration and conditional execution. There are 3 variations Variable declarations: <%! %> Translate to instance members of the generated servlet. <%! int hits = 0; %> Scriptlets: <% %> Contain pure Java code. Java expressions: <%= %> The content is evaluated as a String and output to the page.
Examples <%@ page import= java.util.* %> <%@ page errorpage= /error.jsp %> import java.util classes <html> <body> <% for ( int i i = 0; 0; i i < 50; i++ ) { %> Hello from your friendly JSP!!!!!! (count = <%= i i %>) <br> <% } %> </body> </html> normal html define the page to show if an error occurs print out the value of i <%! public int mul(int a, a, int b) b) { return a * b; b; } %> Multiplication of of two numbers:<%= mul(2, 2) 2) %> Result: Multiplication of of two numbers:4 Creating a method
JSP Deployment - Like an html file, somewhere in the webapp tree, outside WEB-INF - Container detects the.jsp extension <servlet> <servlet> <servlet-name>myjsp</servlet-name> <jsp-file>/myjsp.jsp</jsp-file> <init-param> <init-param> <param-name>hello</param-name> <param-value>test</param-value> </init-param> </init-param> </servlet> </servlet> <servlet-mapping> <servlet-name>myjsp</servlet-name> <url-pattern>/myjsp</url-pattern> </servlet-mapping> - You can add a web.xml entry url-patterns + init parameters
Including JSP pages <html> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <title>jsp:include example</title> </head> <body> This is is a page<br/> <jsp:include page="welcome.jsp" /> /> </body> </html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <title>welcome</title> </head> <body> Welcome Dynamic Include Is Is Working Now </body> </html>
Redirecting JSP pages <html> <head> <title>jsp Redirect Example</title> </head> <body> <% String redirecturl = "http://www.examples.net/"; response.sendredirect(redirecturl); %> </body> </html> <html> <head> <title>jsp Redirect Example</title> </head> <body> <%...... %> </body> </html> Redirection to resource to different servers or domains Client/browser is aware, the header change
Forwarding JSP pages <html> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <title>jsp:forward example</title> </head> <body> This is is a page<br/> <jsp:forward page="welcome.jsp" /> /> </body> </html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <title>welcome</title> </head> <body> Welcome Forward Is Is Working Now </body> </html> Forward to resource within the same server Client/browser not involved original request and response objects transferred
JSP Exception Handling Redirection to dedicated error pages <%@ page errorpage="showerror.jsp" %> <html> <head> <title>error Handling Example</title> </head> <body> <% // // Throw an an exception to to invoke the error page int int x = 1; 1; if if (x (x == == 1) 1) { throw new RuntimeException("Error condition!!!"); } %> </body> </html>
JSP Exception Handling Error-handling page includes the directive <%@ page iserrorpage="true" %>. Causes the JSP compiler to generate the exception instance variable. <%@ page iserrorpage="true" %> <html> <head> <title>show Error Page</title> </head> <body> <h1>opps...</h1> <p>sorry, an an error occurred. <p>here is is the exception stack trace: </p> <pre> <% exception.printstacktrace(response.getwriter()); %> </pre> </body> </html>
JSP Exception Handling Using Try...Catch Block Handling errors within the same page and want to take some action instead of firing an error page <html> <head> <title>try...catch Example</title> </head> <body> <% try{ int i i = 1; 1; i i = i i // 0; 0; out.println("the answer is is " + i); i); } catch (Exception e){ out.println("an exception occurred: " + e.getmessage()); } %> </body> </html>
JSP Tags - Actions The JSP specification also defines standard action tags. Use an XML-based syntax, prefixed with <jsp: Examples: <jsp:usebean.../> - allows a Java object to be used as a scripting variable. <jsp:forward.../> - dispatches the request to another resource. <jsp:plugin.../> - use the Java Plug-In to run a Java applet. Additional actions can be defined using the taglib mechanism (see later).
Using a JavaBean from a JSP Java bean : a class that implements java.io.serializable interface and uses set/get methods to project its properties. There are three basic actions or tags used to embedd a java bean into a jsp page <jsp:usebean> used to associate a bean with the given "id" and "scope" attributes. <jsp:setproperty> used to set the value for a beans property mainly with the "name" attribute which defines a object already defined with the same scope. Other attributes are "property", "param", "value" <jsp:getproperty> used to get the referenced beans instance property and stores in implicit out object.
Rules for using Java Beans Package should be first line of Java bean Bean should have an empty constructor All the variables in a bean should have "get", "set" methods. The Property name should start with an Uppercase letter when used with "set", "get" methods. For example the variable "name" the get, set methods will be getname(), setname(string) Set method should return a void value like "return void()"
Using Java beans Example package pack; public class Counter { int count = 0; 0; String name; public Counter() { } public int getcount() { return this.count; } public void setcount(int count){ this.count = count; } public String getname(){ return this.name; } public void setname(string name){ this.name=name; } }
Using Java beans from a JSP <%@ page language="java" %> <%@ page import="pack.counter" %> <jsp:usebean id="counter" scope="page" class="pack.counter" /> <jsp:setproperty name="counter" property="count" value="4" /> /> Get Value: <jsp:getproperty name="counter" property="count" /><BR> <jsp:setproperty name="counter" property="name" value="prasad" /> /> Get Name: <jsp:getproperty name="counter" property="name" /><BR> The created bean is associated with a scope or context: page request session application
JSP Tag Libraries Tag libraries are used to extend the list of supported action tags. The tags encapsulate Java code. They are implemented using standard APIs. Cleaner than inserting code directly in the page. Easier for designers to work around. Facilitates reuse. The use of the taglib directive indicates that a page uses a taglib. <%@ taglib uri="taglibraryuri" prefix="tagprefix" %> Used as <tagprefix:dosomething>..</tagprefix:dosomething> You can write your own or use third-party libraries. See, for example, the Jakarta Taglibs project.
Some JSP Tag Libraries Core Tags <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> Some tags : <c:out >, <c:if>, <c:choose>, <c:foreach >,... Formatting tags <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> Some tags : <fmt:formatnumber>, <fmt:formatdate>,... SQL tags <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %> <sql:setdatasource>, <sql:query>, <sql:update>,... XML tags <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %> <x:parse>, <x:transform >,... JSTL Functions <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> fn:contains(), fn:endswith(), fn:length(), fn:startswith(), fn:substring(),...
Example of tag lib Accessing database <%@ page import="java.io.*,java.util.*,java.sql.*"%> <%@ page import="javax.servlet.http.*,javax.servlet.*" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%> <html> <head> <title>select Operation</title> </head> <body> <sql:setdatasource var="snapshot" driver="com.mysql.jdbc.driver" url="jdbc:mysql://localhost/test" user="root" password="pass123"/> <sql:query datasource="${snapshot}" var="result"> SELECT * from Employees; </sql:query>...
Example of tag lib Database Access... <table border="1" width="100%"> <tr> <th>emp ID</th> <th>first Name</th> <th>last Name</th> <th>age</th> </tr> <c:foreach var="row" items="${result.rows}"> <tr> <td><c:out value="${row.id}"/></td> <td><c:out value="${row.first}"/></td> <td><c:out value="${row.last}"/></td> <td><c:out value="${row.age}"/></td> </tr> </c:foreach> </table> </body> </html>