UNIT 8 JAVA SERVER PAGES Structure: 8.0 Learning Objectives 8.1 Introduction 8.2 What is JSP? 8.3 Architecture of JSP 8.4 Elements of JSP 8.5 Scripting Elements 8.6 Directives and Actions 8.7 Session Management 8.8 JSP Configuration 8.9 Implicit Objects 8.10 Filter 8.11 JSP in XML and Custom Tag Libraries 8.12 Practical Assignment 8.13 Summary 8.14 Key Words/Abbreviations 8.15 Learning Activity 8.16 Unit End Questions (MCQs and Descriptive) 8.17 References CU IDOL SELF LEARNING MATERIAL (SLM)
Java Server Pages 143 8.0 Learning Objectives After studying this unit, you will be able to: Describe architecture of JSP andelements of JSP Discuss Scripting elements,Directives & actions, and JSPconfiguration Explain white space preservation,implicit objects, and Filter Elaborate JSP in XML and customtag libraries. 8.1 Introduction JSP technology is used to create dynamic web applications. JSP pages are easier to maintain then a Servlet. JSP pages are opposite of Servlets as a servlet adds HTML code inside Java code, while JSP adds Java code inside HTML using JSP tags. Everything a Servlet can do, a JSP page can also do it. JSP enables us to write HTML pages containing tags, inside which we can include powerful Java programs. Using JSP, one can easily separate Presentation and Business logic as a web designer can design and update JSP pages creating the presentation layer and java developer can write server side complex computational code without concerning the web design. And both the layers can easily interact over HTTP requests. 8.2 What is JSP? Definition: Java Server Pages (JSP) is a Java technology that allows software developers to dynamically generate HTML, XML or other types of documents in response to a Web client request. The technology allows Java code and certain pre-defined actions to be embedded into static content. Java Server Pages or JSP for short is Sun's solution for developing dynamic websites. JSP Pages Typically Comprise of 1. Static HTML/XML components. 2. Special JSP tags 3. Optionally, snippets of code written in the Java programming language called “scriptlets.” CU IDOL SELF LEARNING MATERIAL (SLM)
144 Advanced Internet Programming Java Server Pages (JSP) is a Java-based technology that simplifies the process of developing dynamic websites using JSP, web designers and developer can quickly incorporate dynamic elements into web pages using embedded Java and markup tags. The tags allow the user to present data and java object (Applet/JDBC/Java bean/servlet etc.) allow storing business logic. Problems with Servlets 1. Detailed java programming knowledge is needed to develop and maintain all aspects of applets, since the processing code and HTML elements are combined together. 2. Changing the look and feel of the applet or adding support for a new type of client, the server code need to be updated and recompiled. 3. For writing servlets, HTML must be embedded into the servlet code, which is time consuming and error prone. Advantage of JSP Technology 1. Portability: Since it is based on Java, JSP technology is platform independent. To run .jsp files, we need a JSP engine (programs used to run .jsp files). This engine can be built for different type of web-servers to make them execute jsp files. 2. Reuse of Components & Tag Libraries: JSP technology emphasizes the use of reusable component such as Java Bean Components, Enterprise Java Bean Components etc. Data is the main reason of dynamic contents. The components may contain the code to obtain the data from databases or text files thus offering different contents to JSP files. It supports different types of markup languages such as HTML/DHTML/XML. JSP also supports user-defined tags. For user-defined tags, the control is transferred to classes that contain the code, which should be executed. Any type of code such as JDBC, File Handling etc. can be included in these classes. Thus a JSP page developer need not have considerable knowledge of Java. 3. Separation of Static & Dynamic Content: Using HTML pages, we can send only static contents to web clients. If we use servlets, then the entire HTML code is required to be written in println statement, which is tedious. It also makes the entire page to be dynamic. JSP allows you to include dynamic content into the static contents separating the two from each other. The static contents are provided using HTML tags and dynamic contents are generated using scriptlets, user-defined tags etc. It also follows popular MVC (Model-View-Control) Design Pattern. 4. Suitable for N-Tier Architecture: Because of features such as, platform-independence, support for different types of servers (web servers, database servers etc.), markup CU IDOL SELF LEARNING MATERIAL (SLM)
Java Server Pages 145 languages, reuse of objects in the form of components etc. it is best suited for N-Tier architecture. 5. Performance: JSP pages are automatically compiled before execution. So it frees the job of programmer to explicitly compile the program. After compilation, the page is kept in memory for certain duration to serve for next requests. Thus the compilation activity is not done for every request (unless there are modifications in the page). Features of JSP (a) Separation of static from dynamic content: In JSP, the logic to generate the dynamic content is kept separate from the static presentation templates by encapsulating it within external JavaBeans components. These are then used by the ISP page using special tags and scriptlets. When a page designer makes any changes to the presentation template, the JSP page is automatically recompiled and reloaded into the web server by the JSP engine. (b) Write Once Run Anywhere: JSP pages can be moved easily across platforms, and across web servers, without any changes. (c) Web Server Support: With Apache, many other popular web servers like Netscape, and Microsoft IIS can also be easily enabled with JSP. (d) Platform Independent: Runs on all Java-enabled platforms. (e) Scripting: Uses the Java programming language or JavaScript. (f) Database Access: Uses JDBC for data access. (g) Customizable Tags: JSP is extensible with custom tag libraries. 8.3 Architecture of JSP JSPs are HTML page with special JSP tags embedded. These JSP tags can contain Java code. The JSP file extension is .jsp rather than .html. The JSP engine parses the .jsp and creates a Java servlet source file. It then compiles the source file into a class file, this is done the first time and this is why the JSP is probably slower when first time it is accessed. Any time after this the special compiled servlet is executed and is therefore returns faster. CU IDOL SELF LEARNING MATERIAL (SLM)
146 Advanced Internet Programming Web Server Web Browser JSP 1. Web browser Request 2. JSP request sent to Web File server 3. Send to JSP Servlet Engine 9. HTML sent to browser JSP Servlet Engine INTERNET 4. Parse JSP file 5. Generate Servlet source code 6. Compile Servlet source code into class. 7. Instantiate Servlet 8. HTML (Servlet output) Fig. 8.1: Architecture of JSP Steps Required for a JSP Request 1. The user goes to a web site made using JSP. The user goes to a JSP page (ending with .jsp). 2. The web browser makes the request via the Internet. 3. The JSP request gets sent to the Web server. 4. The Web server recognizes that the file required is special (.jsp), therefore passes the JSP file to the JSP Servlet Engine. 5. If the JSP file has been called the first time, the JSP file is parsed, otherwise go to step 7. 6. The next step is to generate a special Servlet from the JSP file. The entire HTML code is converted to println statements. 7. The Servlet source code is compiled into a .class file. 8. The Servlet is instantiated, calling the init and service methods. 9. HTML from the Servlet output is sent via the Internet. 10. HTML results are displayed on the user's web browser. 8.4 Elements of JSP There are three types of JSP elements you can use: directive, action, and scripting. A new construct added in JSP 2.0 is an Expression Language (EL) expression JSP Scriptlet JSP Declaration CU IDOL SELF LEARNING MATERIAL (SLM)
Java Server Pages 147 JSP Expression JSP Comments JSP Scripting Elements JSP Scripting Elements are used for writing the Java Code inside the JSP page. There are different types of scripting elements these elements are used for various purposes. Following are the scripting elements : JSP Scriptlet element/tag: A scriptlet tag is denoted by the special characters <% %>. The special characters '<%' specifies the starting of the scriptlet tag and '%>' specifies end of scriptlet. On the JSP page Java Code is written inside it. Syntax: <% java code %> Example: implements JSP scriptlet tag <html> <head> <title> My First JSP Page </title> </head> <body> <% out.print(\"Welcome to JSP world\"); %> </body> </html> Output: Welcome to JSP world JSP Declaration element/tag: The declaration tag is denoted by the special characters <%! %>. The special character '<%!' specifies the start of the declaration and '%>' specifies the end of the declaration. Declaration element is used to declare the fields, methods to use inside the JSP page. These declaration element helps developer to declare fields, methods like in Servlet how they can declare. Syntax of Declaration Tag <%! Declaration %> CU IDOL SELF LEARNING MATERIAL (SLM)
148 Advanced Internet Programming Example: Declaring a method inside Declaration Tag <html> <head> <title>JSP Declaration Tag</title> </head> <body> <%! int square(int a) { return a * a; } %> <% = \"Square of 5 is: \"+square(5) %> </body> </html> Output: Square of 5 is: 25 JSP Expression element/tag: Then expression tag is denoted by the special characters <%= %>. The special character '<%= specifies the starting of the expression and '%>' specifies the end of the expression. The expression tag is used to set the output. The expression is used like the 'out' implicit object in JSP. JSP Expression Tag JSP expression tag is used to write the client response to the output stream. Expression tag keeps the expression that can be used as an argument to the output stream method. Syntax: <%= Java Expression %> Example: Displays current date using Expression tag <%@page contentType=\"text/html\" import=\"java.util.*\" %> <html> <head> <title>JSP Expression Tag</title> </head> <body> <h2>Current Date</h2> <p> Today's Date: <%= (new java.util.Date()).toLocalString() %> CU IDOL SELF LEARNING MATERIAL (SLM)
Java Server Pages 149 </p> </body> </html> Output: Today’s Date: 03-Aug-2016 10:52:21 JSP Directive Elements Directive elements in JSP provides the special information to the JSP engine. It gives the information about the JSP page. Each JSP page goes through the two phases i.e. translation phase and request time phase. At the translation phase JSP page is translated into a Servlet. The JSP engine translates the JSP page into a Servlet, directive elements are handled at the translation time. These directives are translated to the Servlet only for once, until there is no changes made to the directive elements in the Servlet. JSP Directive Elements can be declared within the following special characters '<%@ %>'. Syntax for using directive in the JSP page is as follows : <%@ directiveName attr1=\"value1\" attr2=\"value2\" %> JSP Standard Action Elements JSP Action Elements are used to take action on the basis of some information. These action elements can create, modify or use the other objects. Action elements are coded with the strict syntax they are used to apply the built-in functionality. Action elements are represented as <jsp:tagName> </jsp:tagName>. Code is written inside these tags, the <jsp:tagName> specifies the starting of the action tag where as the action tag is ends with </jsp:tagName>. When you are not required to defined the body of the tag you may end up the action tag by <jsp:tagName/> JSP Comment Elements JSP comment elements are used to hide your code from the “view page source”. However, you can use HTML comment tags in JSP page but, when user of your website will choose the “view page source” then they can see your commented code. The JSP comment is denoted by the special character <%-- --%>. The special character '<%--' specifies the opening comment element and the special character '--%>' specifies the end of the comment tag. HTML comment tag is denoted by the special characters '<!-- -->' where, '<!--' specifies the start tag and '-->' specifies the end tag. CU IDOL SELF LEARNING MATERIAL (SLM)
150 Advanced Internet Programming Syntax: <%-- JSP comment --%> Example: JSP comment tag <html> <head> <title>JSP Comments</title> </head> <body> <%-- this will hide on JSP page --%> </body> </html> 8.5 Scripting Elements JSP Scriptlet Scriptlet tag allows to write Java code into JSP file. JSP container moves statements in _jspservice() method while generating servlet from jsp. For each request of the client, service method of the JSP gets invoked hence the code inside the Scriptlet executes for every request. A Scriptlet contains java code that is executed every time JSP is invoked. Syntax of Scriptlet Tag <% java code %> Here <%%> tags are scriplets tag and within it, we can place java code. Example: <html> <head> <title>My First JSP Page</title> </head> <% int count = 0; %> </head> <body> CU IDOL SELF LEARNING MATERIAL (SLM)
Java Server Pages 151 Page Count is <% out.println(++count); %> </body> </html> In a scripting element, if the characters %> needs to be used, escape the greater than sign with a backslash: <% String message = “This is the %\\>”; %> The backslash before the expression acts as an escape character, informing the JSP engine to deliver the expression verbatim instead of evaluating it. There are a number of special constructs used in various cases to insert characters that would otherwise be treated specially, they are as follows: Escape Characters Table 8.1: Escape Characters \\’ Description \\” A single quote in an attribute that uses single quotes. \\\\ A double quotes in an attribute that uses double quotes. A backslash in an attribute that uses backslash. %\\> Escaping the scripting end tag with a backslash. <\\% Escaping the scripting start tag with a backslash. \\$ Escaping the dollar sign [dollar sign is used to start an EL expression] with a backslash Example Solutions: <% String message = ‘Escaping \\’ single quote’;%> <% String message = “Escaping \\” double quote”;%> <% String message = “Escaping \\\\ backslash”;%> <% String message = “Escaping %\\> scripting end tag”;%> <% String message = “Escaping <\\% scripting start tag”;%> <% String message = “Escaping \\$ dollar sign”;%> As an alternative to escaping quote characters, the character entities ' and " can also be used. CU IDOL SELF LEARNING MATERIAL (SLM)
152 Advanced Internet Programming 8.6 Directives and Actions Directives in JSP Directives are instructions to the JSP container that describe what code should be generated. They have the general form <%@ directive-name [attribute= ” value ” attribute= ” value” ….] %> Zero or more spaces, tabs, and newline characters can appear after the opening <%@ and before the ending %>, and one or more whitespace characters can appear after the directive name and between the attributes / value pairs. The only restriction is that the opening <%@ tag must be in the same physical file as the ending %> file. Three standard directives: – page – include – taglib Page Directive Page directive is used to specify attribute for the JSP page as a whole. The page directive lets you control the structure of the servlet by importing classes, customizing the servlet superclass, setting the content type and the like The page directive can be placed anywhere within the document. Syntax <% @ page [ attribute1=”value1”.. attributen=’valuen”] %> Include Directive Include directives includes an external document in the page. The include directive must be placed in the document at the point at which you want the file to be appended. The <%@ include %> directive inserts a file of text or code in a JSP file at translation time, when the JSP file is compiled. When you use the <%@ include %> directive, the include process is static. A static include means that the text of the included file is added to the JSP file. The included file can be a JSP file, HTML file, or text file. If the included file is a JSP file, its JSP elements are parsed and their results included (along with any other text) in the JSP file. CU IDOL SELF LEARNING MATERIAL (SLM)
Java Server Pages 153 Syntax: <%@ include file=“file _name” %> Taglib Directive The taglib directive has been introduced in JSP 1.1, which can be used to define custom markup tags. This directive requires that a prefix be specified (much like a namespace in C++) and the URI for the tag library description. Example :-<%@ taglib prefix=\"myprefix\" uri=\"taglib/mytag.tld\" %> Example:-<%@ taglib uri=\"http://www.jspcentral.com/tags\" prefix=\"public\" %> <public:loop> . </public:loop> Description The <%@ taglib %> directive declares that the JSP file uses custom tags, names the tag library that defines them, and specifies their tag prefix. Here, the term custom tag refers to both tags and elements. Attributes 1. uri= “URIToTagLibrary”: The Uniform Resource Identifier (URI) that uniquely names the set of custom tags associated with the named tag prefix. 2. prefix= “tagPrefix”: The prefix that precedes the custom tag name, for example, public in <public:loop>. Empty prefixes are illegal. Action in JSP Actions allow you to perform server-side resources like JSP pages and servlets without the Java coding. Although the same can be achieved using Java code within scriptiets, but using action tags help reusability of your components and enhances the maintainability of your application. The JSP Actions are XML tags that can be used in the JSP page. Action tag is used to transfer the control between pages and is also used to enable the use of server side JavaBeans. CU IDOL SELF LEARNING MATERIAL (SLM)
154 Advanced Internet Programming List of JSP Actions jsp:include The jsp:include action works as a subroutine that temporarily passes the request and responses to the specified SPIServlet. Control is then returned back to the current JSP page. The jsp:include action can be used to redirect the request to any static or dynamic resource that is in the same context as the calling JSP page. Syntax:- <jsp:include page=”relativeURL”/> jsp:param: The jsp:param action is used to add the specific parameter to current request. The jsp:param tag can be used inside a jsp:include, jsp:forward or jsp:params block. Syntax: <jsp:inctude page=.”relativeURL”> <jsp:param name=”parameterName” vatue=” parameterValue” /> </jsp:include> jsp:forward: With the <jsp:forward> tag, you can redirect the request to any JSP, servlet, or static HTML page within the same context as the invoking page. This effectively halts processing of the current page at the point where the redirection occurs, although all processing up to that point still takes place. The jsp:forward tag is used to hand off the request and response to another JSP or serviet. In this case the request never returns to the calling JSP page. Syntax: <jsp:forward page=”somePage.jsp” /> A <jsp:forward> tag may also have jsp:param subelements that can provide values for some elements in the request used in the forwarding Syntax: <jsp:forward page=”Some Page”> <jsp:param name=”name1” value=”value1”> </ jsp:forward page > CU IDOL SELF LEARNING MATERIAL (SLM)
Java Server Pages 155 jsp:plugin In older versions of Netscape Navigator and Internet Explorer, different tags were used to embed applet. The jsp:plugin tag actually generates the appropriate HTML code to embed the Applets correctly jsp:fallback The jsp:fallback tag is used to specify the message to be shown on the browser is not supported by browser. Example: <jsp:fallback> Unable to load applet </jsp:fallback> jsp:getProperty Gets the value of a Bean property so that you can display it in a result page. Syntax <jsp:getProperty name=\"beanInstanceName\" property=\"propertyName\" /> The <jsp:getProperty> element gets a Bean property value using the property's getter methods and displays the property value in a JSP page. You must create or locate a Bean with <jsp:useBean> before you use <jsp:getProperty>. jsp:setProperty Sets a property value or values in a Bean. Syntax: <jsp:setProperty name=\"beanInstanceName\" { property= \"*\" | property=\"propertyName\" [ param=\"parameterName\" ] | property=\"propertyName\" value=\"{string | <%= expression %>}\" } /> The <jsp:setProperty> element sets the value of one or more properties in a Bean, using the Bean's setter methods. You must declare the Bean with <jsp:useBean> before you set a property value with <jsp:setProperty>. Because <jsp:useBean> and <jsp:setProperty> work together, the Bean instance names they use must match (that is, the value of name in <jsp:setProperty> and the value of id in <jsp:useBean> must be the same). CU IDOL SELF LEARNING MATERIAL (SLM)
156 Advanced Internet Programming jsp:useBean The component model for JSP technology is based on JavaBeans component architecture. JavaBeans components are Java objects which follow a well-defined pattern: the bean encapsulates its properties by declaring them private provides public accessor (getter/setter) methods for reading and modifying values. Before you can access a bean within a JSP page, it is necessary to identify bean and obtain a reference to it. The <jsp:useBean> tag tries to reference to an existing instance using the specified id and scope. The jsp:useBean tag is used either to instantiate an object of Java Beanre-use existing java bean object. Syntax: <jsp:use8ean id=”beanlnstanceName” scope=”page/request/session/appLication” class=’package.class”type=package.ctass”/beanName”package.cLass” type=”package.class” </jsp:useBean> 8.7 Session Management In session management whenever a request comes for any resource, a unique token is generated by the server and transmitted to the client by the response object and stored on the client machine as a cookie. We can also say that the process of managing the state of a web based client is through the use of session IDs. Session IDs are used to uniquely identify a client browser, while the server side processes are used to associate the session ID with a level of access. Thus, once a client has successfully authenticated to the web applicatiion, the session ID can be used as a stored authentication voucher so that the client does not have to retype their login information with each page request. Now whenever a request goes from this client again the ID or token will also be passed through the request object so that the server can understand from where the request is coming. Session management can be achieved by using the following thing. 1. Cookies: cookies are small bits of textual information that a web server sends to a browser and that browsers returns the cookie when it visits the same site again. In cookie the information is stored in the form of a name, value pair. By default the cookie is generated. If the user doesn't want to use cookies then it can disable them. 2. URL rewriting: In URL rewriting we append some extra information on the end of each URL that identifies the session. This URL rewriting can be used where a cookie is CU IDOL SELF LEARNING MATERIAL (SLM)
Java Server Pages 157 disabled. It is a good practice to use URL rewriting. In this session ID information is embedded in the URL, which is recieved by the application through Http GET requests when the client clicks on the links embedded with a page. 3. Hidden form fields: In hidden form fields the html entry will be like this : <input type =\"hidden\" name = \"name\" value=\"\">. This means that when you submit the form, the specified name and value will be get included in get or post method. In this session ID information would be embedded within the form as a hidden field and submitted with the Http POST command. In JSP we have been provided a implicit object session so we don't need to create a object of session explicitly as we do in Servlets. In Jsp the session is by default true. The session is defined inside the directive <%@ page session = \"true/false\" %>. If we don't declare it inside the jsp page then session will be available to the page, as it is default by true. Following program illustrate the concept of session management The code of the program is given below: <html> <input type = \"submit\" name = \"submit\" value = \"submit\" > <head> </form> </body> </html> <title>Welcome to the first program of jsp </title> <% </head> String name = request.getParameter(\"name\"); <body> String password = request.getParameter(\"pwd\"); <form method = \"post\" action = if(name.equals(\"Williams\") && \"FirstPageOfSession.jsp\"> password.equals(\"abcde\")) { <font size = 6>Enter your name<input type session.setAttribute(\"username\",name); = \"text\" name = \"name\"></font><br><br> response.sendRedirect(\"NextPageAfterFirst.jsp\"); <font size = 6>Enter your password<input } type=\"password\" name = \"pwd\" > else { </font><br><br> response.sendRedirect(\"SessionManagement.html \"); } %> <html> <head> <title>Welcome in In the program of URL rewriting</title> </head> <body> <font size = 6>Hello</font> <%= session.getAttribute(\"username\") %> </body> </html> CU IDOL SELF LEARNING MATERIAL (SLM)
158 Advanced Internet Programming The output of the program is given below: Fig. 8.2: Session Management Program - 1 When the values entered is correct. Fig. 8.3: Session Management Program - 2 When the entered values are incorrect, the SessionManagement.html will be displayed again to you. Fig. 8.4: Session Management CU IDOL SELF LEARNING MATERIAL (SLM)
Java Server Pages 159 You can Enter new values again. 8.8 JSP Configuration Configuring Java Server Pages (JSPs) JSP config object is used to send the configuration information to JSP page. Here, config is an instance of servlet’s ServletConfig interface. In order to deploy Java Server Pages (JSP) files, you must place them in the root (or in a subdirectory below the root) of a Web application. You define JSP configuration parameters in subelements of the jsp-descriptor element in the WebLogic-specific deployment descriptor, weblogic.xml. These parameters define the following functionality: Options for the JSP compiler Debugging How often WebLogic Server checks for updated JSPs that need to be recompiled Character encoding Configuration of a JSP file in web.xml Declare the following tags in web.xml against your jsp <servlet> <servlet-name>myjsp</servlet-name> <jsp-file>/myjsp.jsp</jsp-file> <init-param> <param-name>hello</param-name> <param-value>test</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>myjsp</servlet-name> <url-pattern>/myjsp</url-pattern> </servlet-mapping> You need a servlet mapping, When you're dealing with a JSP as a Servlet.In order to be able to access servlet init params, you will need to create a mapping and call the JSP with the url- pattern in the mapping. JSP provides the \"config\" implicit object variable that eliminates the need to call getServletConfig(). You can get the init parameters from the implicit \"config\" object by calling getInitParameter() method or getInitParameters() method. For example, CU IDOL SELF LEARNING MATERIAL (SLM)
160 Advanced Internet Programming <%= config.getInitParameter(\"hello\");%> If you make the url-pattern match the name of the JSP, people won't be able to skirt the web.xml configurations by typing the url of the JSP in the browser's address window. If you want to add init-params to a JSP via web.xml, you need to create a servlet mapping for your JSP and use the url defined in that mapping when making the request. Context init params, on the other hand are bound to the Context object (which is available to all components of the app) will be available, regardless of how your JSP was invoked. Example of JSP Config In this example, web.xml file contains the information. The config object in index.jsp file fetches that information. index.jsp <html> <head> <title>Tutorial and Example</title> </head> <body> <% String name=config.getServletName(); out.print(\"<h2 align=center>Welcome to \"+name+\"</h2>\"); %> </body> </html> web.xml <web-app> <servlet> <servlet-name>Tutorial and Example</servlet-name> <jsp-file>/index.jsp</jsp-file> </servlet> <servlet-mapping> <servlet-name>Tutorial and Example</servlet-name> <url-pattern>/index</url-pattern> </servlet-mapping> </web-app> CU IDOL SELF LEARNING MATERIAL (SLM)
Java Server Pages 161 Output: 8.9 Implicit Objects Delivering dynamic website content to a client browser requires interacting with Java objects on the Web server. Java scripting elements provide a great deal of power and flexibility to the developer to achieve this. In addition tom permitting such intercommunication the JSP engine exposes a number of internal Java objects to the developer. These objects do not need to be declared or instantiated by the developer, but are provided by the JSP engine in its implementation and execution. Scripting elements can access predefined variables assigned by the JSP engine and using their content reference implicit objects to access request and application data. These objects are instances of class defined by the Servlet and JSP specifications. Request JSP pages are web components that respond to and process HTTP requests. The implicit Request object represents the HTTP request. The Request object provides access to all information associated with a request including its source, the requested URL and any headers, cookies or parameters associated with the request. The request object has a request scope. It encapsulates the request coming from the client and being processed by the JSP. It is passed to the JSP by the JSP engine, as a parameter to the _jspService() method. In other words, the request object is in scope unless the response to the client is complete. The request object is an instance of javax.Servlet.HttpServletRequest. If the protocol in the request is something other than HTTP, request object is allowed to be a subclass of ServletRequest other than HttpServletRequest, which is almost never done in practice as there are few, if any, JSP servers currently supporting non-HTTP Servlets. Response The implicit Response object represents the response sent back to the user browser as a result of processing the JSP page. Some of the tasks done using response object are setting headers, cookies for the client and sending a redirect response to the client. CU IDOL SELF LEARNING MATERIAL (SLM)
162 Advanced Internet Programming The response object has page scope. It encapsulates the response generated by the JSP. This is the response being sent back to a client browser in response to its request. The response is generated by the Web server and passed to the JSP as a parameter to _jspService(). Here the response generated can be modified by the JSP. The response object is an instance of javax.servlet.http.HttpServletResponse. The following table summarizes, most often used methods, available to the Response object: Table 8.2: Summarizes, Most often used Methods, Available to the Response Object Method Description addCookie() Adds the specified cookie to the response. It can be called multiple times to set more than one cookie sendRedirect() Sends a temporary redirect response to the client using the specified redirect location URL Out The Out object is a reference to an output stream that can be used within scriptlets. In actual fact, the Out object represents the output stream of the JSP page, the contents of which are being sent to a client browser. The out object in the PrintWriter, which is used to send output to the client. However, in order to make the response object useful, this is a buffered versions of PrintWriter called JspWriter. The out object has page scope and is an instance of javax.servlet.jsp.JspWrite: Method Table 8.3: The Out Object in the PrintWriter clear() Description close() Clears the contents of the buffer and throws an exception if some data has already been flush() written to the output stream print() Flushes and then closes the output stream println() Flushes the output buffer and sends any bytes contained in the buffer to their intended destination. It will also flush all the buffers in a chain of Writers and OutputStream Prints the specified primitive data type such as Object or String to the client Prints the specified primitive data type such as Object or String to the client followed by a new line character at the end CU IDOL SELF LEARNING MATERIAL (SLM)
Java Server Pages 163 Session HTTP is a stateless protocol. As far as Web server is concerned, each client’s request is a new request, with nothing to connect it to previous requests. However, n Web applications, a client’s interaction with the application will often span man requests and responses. To join all these separate interactions into one coherent conversation between the client and application, Wen applications use the concept of a session. A session refers to the entire conversation between a client and a server. The JSP components in a Web application automatically participate in a given client’s session, without needing to do anything special. The session object allows accessing the client’s session data, managed by the server. Sessions are created automatically. Hence, this variable is present even if there are no incoming session references. The following table lists the most commonly used Session object’s methods: Table 8.4: Lists the Most Commonly used Session Object’s Methods Method Description isNew() A session is considered to be new if it is been created by the server, but the client has not yet acknowledged joining the session invalidate() Discards the session, releasing any objects stored as attributes getAttribute() Retrieves the object associated with the named attribute setAttribute() Sets the object to the named attribute. Attribute is created if it does not exist removeAttribute() Removes the object bound with the specified name from this session Application The application object represents the application to which the JSP page belongs. It represents the context within which the JSP is executing [the Servlet context]. In other words, this object represents the application to which the JSP belongs. The application object holds references to other objects that more than one user may require access to such as a database connection pool shared by all application users. JSP pages are grouped into applications according to their URLs where the first directory name in a URL defines the application. The application object contains methods that provide information about the JSP engine, support for logging plus utility methods. For example: translating a relative URL to an absolute path. CU IDOL SELF LEARNING MATERIAL (SLM)
164 Advanced Internet Programming It is an instance of the javax.servlet.ServletContext. The application object has application scope. This table lists the most commonly used methods of the Application object: Table 8.5: Lists of the Most Commonly used Methods of the Application Object Method Description getAttribute() Returns the object named name getAttribute() Stores the object with the given object name in the application removeAttribute() Removes the name object from the application log() Writes a message to the Servlet engine’s log file Config The configuration information contains initialization parameters, defined in the deployment descriptor and the ServletContext object representing the Web application the Servlet or JSP page belongs to. The config object has page scope and is an instance of javax.servlet.ServletConfig. A Web server uses a ServletConfig instances to pass information to a Servlet or JSP page during initialization. This table lists the most commonly used methods of the Config object: Table 8.6: Lists of the most Commonly used Methods of the Config. Object Method Description getInitParameter() Returns the value of the specified initialization parameter getInitParaamterNames() Returns an Enumeration of String objects containing the names of all the Servlet’s initialization parameters getServerContext() Returns the ServletContext object [contains information about the environment in which the Servlet is running] associated with the invoking Servlet PageContext The PageContext object encapsulates the page context of a JSP page. The PageContext object implements methods for transferring control from the current page to another page either temporarily i.e. to generate output to be included in the output of the current page or permanently i.e. to transfer control altogether. CU IDOL SELF LEARNING MATERIAL (SLM)
Java Server Pages 165 PageContext encapsulates access to Web server specific features such as high performance. The reason being that if the JSP accesses these features through a standard class, rather than directly, then JSP can execute in any JSP engine irrespective of where the JSP engine is implemented due to this layer of abstraction. The pageContext object has page scope and is an instance of javax.servlet.jsp.PageContext. Page The Page object represents the JSP page itself and can be accessed using this reference. In other words, the Page object is simply a synonym for this. It was created as a placeholder for the time when the scripting language could be something other than java. The Page object has page scope and is an instance of the class java.lang.Object. In practice, the Page object is rarely used when JSP’s are scripted using Java. This is because the JSP scripting elements will ultimately be incorporated as method code of the constructed Servlet class. Hence, the scripting elements will automatically have access to all the Servlet class methods. Exception The Exception object refers to the runtime exception that results in an error page being invoked. The Exception object is available only in an error page [i.e. a JSP that has the attribute is ErrorPage=true in the page directive]. The Exception object has a page scope. It is an instance of java.lang.Throwable. The Throwable class is the superclass of all the errors and exception classes in the Java language. Only instances of these classes are thrown by the JVM or can be thrown by an application using the Java throw statement. This table lists the most commonly used methods of the Exception object: Table 8.7: Lists of the most Commonly used Methods of the Exception Object Method Description getMessage() Returns the error message string of the Throwable object toString() Returns a short description of the Throwable object CU IDOL SELF LEARNING MATERIAL (SLM)
166 Advanced Internet Programming 8.10 Filter JSP Filters Filters are used for filtering functionality of the Java web application. They intercept the requests from client before they try to access the resource They manipulate the responses from the server and sent to the client. Types of Filters in JSP Authentication filters Data compression filters Encryption filters MIME chain filters Logging Filters Tokenizing filters Filters are defined in web.xml, and they are a map to servlet or JSP.When JSP container starts with the web application, it creates the instance of each filter that have been declared in the deployment descriptor. Following are the filter methods: Public void doFilter(ServletRequest,ServletResponse, FilterChain) This is called everytime when a request/response is passed from every client when it is requested from a resource. Public void init(FilterConfig) This is to indicate that filter is placed into service Public void destroy() This to indicate the filter has been taken out from service. flow between JSP /Servlets and filters. There can be ‘n’ numbers of filters configured for a JSP or servlet and all filters execute in a chain. Filter 2 will be executed only if Filter 1 passes the request and so on . Once request passes all the filters ,it reaches destination resource. Once JSP or servlet completes its logic , request goes back to filter N and then Filter N-1.. and so on. CU IDOL SELF LEARNING MATERIAL (SLM)
Java Server Pages 167 JSP Filter Interface JSP Filter class has to implement javax.servlet.Filter interface. Filter interface defines three methods which means classes implements filter interface has to implement these methods. void init(FilterConfig) doFilter (ServletRequest, ServletResponse, FilterChain) public void destroy() Request Response Filter1 Filter1 Filter2 Filter2 Filter3 Filter3 JSP Fig. 8.5: JSP Filter Life cycle JSP Filter Life cycle The life cycle of a JSP filter is managed by a container and consists of implementing the following methods: init() This method is called only once after instantiation to perform any initialization task.We can define a initialization parameters in wex,xml for filters similar to init- params of servlets. doFilter() This method is called after the init() method and is called each time a filter needs to perform any function. This method performs the actual work of a filter, either modifying the request or the response. destroy() This method is used to perform any cleanup operation before the container removes a filter instance. 8.11 JSP in XML and Custom Tag Libraries Custom Tags in JSP Let’s say we want to show a number with formatting with commas and spaces. This can be very useful for user when the number is really long. So we want some custom tags like below: CU IDOL SELF LEARNING MATERIAL (SLM)
168 Advanced Internet Programming <mytags:formatNumber number=\"100050.574\" format=\"#,###.00\"/> Based on the number and format passed, it should write the formatted number in JSP page, for above example it should print 100,050.57 We know that JSTL doesn’t provide any inbuilt tags to achieve this, so we will create our own custom tag implementation and use it in the JSP page. Below will be the final structure of our example project. JSP Custom Tag Handler This is the first step in creating custom tags in JSP. All we need to do is extend javax.servlet.jsp.tagext.SimpleTagSupport class and override doTag() method. The important point to note is that we should have setter methods for the attributes we need for the tag. So we will define two setter methods – setFormat (String format) and setNumber(String number). SimpleTagSupport provide methods through which we can get JspWriter object and write data to the response. We will use DecimalFormat class to generate the formatted string and then write it to response. We are going to create a custom tag that prints the current date and time. We are performing action at the start of tag. For creating any custom tag, we need to follow following steps: 1. Create the Tag handler class and perform action at the start or at the end of the tag. 2. Create the Tag Library Descriptor (TLD) file and define tags 3. Create the JSP file that uses the Custom tag defined in the TLD file Understanding Flow of Custom Tag in jsp JSP File TLD File Tag Handler class Using tag Defining tag Business logic to be name and Tag performed on tag Handler class Fig. 8.6: Flow of Custom Tag in JSP CU IDOL SELF LEARNING MATERIAL (SLM)
Java Server Pages 169 8.12 Practical Assignment 1. Develop sample programs with JSP by creating Registration Form and Login Form. In Registration form, we will have a form to fill all the details which will contain name, username, password, address, contact number, etc. This form will help us to register with the application. They take all our details and store it in a database or cache. Like registration form we will have a login and logout form. In Login form where we have two fields “username” and “password” with a submit button. When we click on submit button then we get welcome message with a logout button. When we click on logout button then we get back to login form. 2. Develop a JSP application to upload any files using JSP. It can be a text file, binary file, image file or any other document. Here in case of file uploading, only POST method will be used and not the GET method. 3. Create a servlet that forwards the request to one of three different JSP pages, depending on the value of the operation request parameter. Say if input is <10 then page 1 or greater than 10 and less than 99 then page 2 otherwise error page 8.13 Summary JSP is a server side technology that does all the processing at server. It is used for creating dynamic web applications, using java as programming language. Basically, any html file can be converted to JSP file by just changing the file extension from “.html” to “.jsp”, it would run just fine. What differentiates JSP from HTML is the ability to use java code inside HTML. In JSP, you can embed Java code in HTML using JSP tags. for e.g. run the code below, every time you run this, it would display the current time. That is what makes this code dynamic. 8.14 Key Words/Abbreviations N-Tier Architecture: The n-tier architecture is an industry-proven software architecture model. It is suitable to support enterprise level client-server applications by providing solutions to scalability, security, fault tolerance, reusability, and maintainability. It helps developers to create flexible and reusable applications Scriptlet: A scriptlet is a piece of Java-code embedded in the HTML-like JSP code. CU IDOL SELF LEARNING MATERIAL (SLM)
170 Advanced Internet Programming JSP: JavaServer Pages HTML: Hyper Text Markup Language XML: eXtensible Markup Language 8.15 Learning Activity 1. Which methods are used for JSP Filter Interface. ----------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- 2. Explain Custom tags in JSP. ----------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- 8.16 Unit End Questions (MCQs and Descriptive) A. Descriptive Types Questions 1. What is JSP? Explain its advantage and disadvantage. 2. Explain Architecture of JSP. 3. Explain different Elements of JSP. 4. Explain Scripting elements. 5. What are Directives in JSP? Explain its types? 6. List and Explain any 5 JSP implicit objects? 7. Explain Directives and actions of JSP in short. 8. Explain JSP configuration. 9. Explain White space preservation in JSP. 10 Explain implicit objects used in JSP. 11. Explain Filter in JSP. 12. Explain Usuage of JSP in XML and custom tag libraries. CU IDOL SELF LEARNING MATERIAL (SLM)
Java Server Pages 171 B. Multiple Choice/Objective Type Questions 1. What technique is used for the authentication mechanism in the servlet specification? (a) Role Based Authentication (b) Form Based Authentication (c) Both A & B (d) None of the above 2. In JSP Action tags which tags are used for bean development? (a) jsp:useBean (b) jsp:setPoperty (c) jsp:getProperty (d) All mentioned above 3. Which two interfaces does the javax.servlet.jsp package have? (a) JspPage (b) HttpJspPage (c) JspWriter (d) Both A & B 4. How many jsp implicit objects are there and these objects are created by the web container that are available to all the jsp pages? (a) 8 (b) 9 (c) 10 (d) 7 5. Which of the following is an advantage of the statement – Separation of business logic from JSP ? (a) Custom Tags in JSP (b) JSP Standard Tag Library (c) All the above (d) None of the above Answers 1. (a), 2. (d), 3. (d), 4. (b), 5. (a) 8.17 References 1. https://beginnersbook.com/2013/05/jsp-tutorial-introduction/ 2. https://www.javatpoint.com/jsp-tutorial 3. Karl Avedal, “PRO JSP”. 4. Andrea Steelman and Joel Murach, “Murach’s Java Servlets and JSP: Training & Reference”. 5. Head first Servlet and JSP, O’REILLY Publication. CU IDOL SELF LEARNING MATERIAL (SLM)
UNIT 9 JAVA HIBERNATE Structure: 9.0 Learning Objectives 9.1 Introduction to Hibernate 9.2 Hibernate Architecture 9.3 Hibernate Configuration 9.4 Sessions 9.5 Persistent Class 9.6 Mapping 9.7 O/R mapping in Hibernate 9.8 Annotation Mapping 9.9 Hibernate Query Language 9.10 Hibernate Criteria Queries 9.11 Hibernate Native SQL 9.12 Hibernate Caching and Interceptor 9.13 Practical Assignment 9.14 Summary 9.15 Key Words/Abbreviations 9.16 Learning Activity CU IDOL SELF LEARNING MATERIAL (SLM)
Java Hibernate 173 9.17 Unit End Questions (MCQs and Descriptive) 9.18 References 9.0 Learning Objectives After studying this unit, you will be able to: Describe Java hibernate architectureconfigurations Define sessions, persistent class andmapping Explain criteria queries, and NativeSQL Elaborate caching and interceptor 9.1 Introduction Hibernate is a framework which provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like establishing a connection with the database, writing query to perform CRUD operations etc. It is a java framework which is used to develop persistence logic. Persistence logic means to store and process the data for long use. More precisely Hibernate is an open-source, non-invasive, light-weight java ORM(Object-relational mapping) framework to develop objects which are independent of the database software and make independent persistence logic in all JAVA, JEE. 9.1 Introduction to Hibernate Hibernate is a high-performance Object/Relational persistence and query service which is licensed under the open source GNU Lesser General Public License (LGPL) and is free to download. Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities. CU IDOL SELF LEARNING MATERIAL (SLM)
174 Advanced Internet Programming (Object Relational Mapping) Hibernate Overview Java Objects Directly maps Relational Object Database Tablets Mapping Relational Fig. 9.1: Hibernet (Object Relational Mapping) Fig. 9.2: Hibernet Overview Hibernate is a solution to map database tables to java class Copying of tables to objects & vice versa is ORM Saving objects to storage medium (Persistence) Hibernate is an Object-Relational Mapping(ORM) solution for JAVA and it raised as an open source persistent framework created by Gavin King in 2001. It is a powerful, high performance Object-Relational Persistence and Query service for any Java Application. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from 95% of common data persistence related programming tasks. Hibernate sits between traditional Java objects and database server to handle all the work in persisting those objects based on the appropriate O/R mechanisms and patterns. CU IDOL SELF LEARNING MATERIAL (SLM)
Java Hibernate 175 Mapping 1. Java classes Database Tables 2. Java Data type SQL Data type Hibernate Advantages 1. HibernateDaoSupport: superclass, easy HibernateTemplate access. 2. Database independence: sits between the database and your java code, easy database switch without changing any code. 3. Object/Relational Mapping (ORM): Hibernate takes care of mapping Java classes to database tables using XML files and without writing any line of code. Allows a developer to treat a database like a collection of Java objects. 4. Object oriented query language (HQL) - *Portable* query language, supports polymorphic queries etc. 5. You can also still issue native SQL, and also queries by “Criteria” (specified using “parse tree” of Java objects). 6. Hibernate Mapping: Uses HBM XML files to map value objects (POJOs) to database tables. 7. Transparent persistence: Allows easy saves/delete/retrieve for simple value Objects. 8. Provides simple APIs for storing and retrieving Java objects directly to and from the database. 9. If there is change in Database or in any table then the only need to change XML file properties. 10. Abstract away the unfamiliar SQL types and provide us to work around familiar Java Objects. 11. Hibernate does not require an application server to operate. 12. Manipulates Complex associations of objects of your database. 13. Minimize database access with smart fetching strategies. 14. Provides Simple querying of data. 15. It eliminates need for repetitive SQL 16. Handles all Create, Read, Update, Delete ( CRUD) operations CU IDOL SELF LEARNING MATERIAL (SLM)
176 Advanced Internet Programming Supported Databases Hibernate supports almost all the major RDBMS. Following is list of few of the database engines supported by Hibernate. HSQL Database Engine Applications can be DB2/NT JSP, Servlets, Swings MySQL PostgreSQL PO Java Beans FrontBase ( POJO, DAO) Oracle Microsoft SQL Server Database Hibernate.cfg.xml Sybase SQL Server & properties Informix Dynamic Server JDBCAPIs from Hibernate to database 9.2 Hibernate Architecture Hibernate Architecture The Hibernate architecture is layered to keep you isolated from having to know the underlying APIs. Hibernate makes use of the database and configuration data to provide persistence services (and persistent objects) to the application. Following is a very high level view of the Hibernate Application Architecture. Java Application Persistent Object Hibernate. Hibernet Properties XML Mapping Database Fig. 9.3: Hibernate Architecture CU IDOL SELF LEARNING MATERIAL (SLM)
Java Hibernate 177 Hibernate basically sits between the DB and your code Can map persistent objects to tables Hibernate 2-tier web architecture Can send data to JDBC or XML files Following is a detailed view of the Hibernate Application Architecture with few important core classes. Java Application Persistent Object Hibernet Configuration Session Factory Session Hibernate. Properties XML Mapping Transaction Query Criteria JTA JDBC JNDI Database Database Fig. 9.4: Application Architecture with few Important Core Classes Explain Architecture of Hibernate framework in detail. APPLICATION Persistent HIBERNATE Objects Configuration Session Session HibTerrannastaec.tion Query Criteria Factory Properties Java Transaction API JNBC JNDI DATABASE Fig. 9.5: Architecture of Hibernate Framework Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java CU IDOL SELF LEARNING MATERIAL (SLM)
178 Advanced Internet Programming Naming and Directory Interface (JNDI). JDBC provides a rudimentary level of abstraction of functionality common to relational databases, allowing almost any database with a JDBC driver to be supported by Hibernate. JNDI and JTA allow Hibernate to be integrated with J2EE application servers. Hibernate is made up to three components 1. Connection Management: Hibernate Connection management service provide well- organized management of the database connections. Database connection is the most expensive part of interacting with the database as it requires a lot of resources of open and close the database connection. 2. Transaction management: Transaction management service of hibernate provides the ability to the user to execute more than one database statements at a time. 3. Object relational mapping: Object relational mapping is technique of mapping the data representation from an object odel to a relational data model. This part of hibernate is used to select, insert, update and delete the records form the underlying table. When we pass an object to a Session.save() method, Hibernate reads the state of the variables of that object and executes the necessary query. Following section gives brief description of each of the class objects involved in Hibernate Application Architecture. Configuration Object The Configuration object is the first Hibernate object you create in any Hibernate application and usually created only once during application initialization. It represents a configuration or properties file required by the Hibernate. The Configuration object provides two keys components: 1. Database Connection: This is handled through one or more configuration files supported by Hibernate. These files are hibernate.properties and hibernate.cfg.xml. 2. Class Mapping Setup This component creates the connection between the Java classes and database tables. Session Factory Object Configuration object is used to create a Session Factory object which in turn configures Hibernate for the application using the supplied configuration file and allows for a Session object to instantiated. The Session Factory is a thread safe object and used by all the threads of an application. The Session Factory is is heavyweight object so usually it is created during application start up and kept for later use. You would need one Session Factory object per CU IDOL SELF LEARNING MATERIAL (SLM)
Java Hibernate 179 database using a separate configuration file. So if you are using multiple databases then you would have to create multiple Session Factory objects. Hence, the session factory is created with the help of a configuration object during the application start up.it serves as as factory for spawning session objects when required. Session Object A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object. The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed. Session objects are light weight and inexpensive to create. They provide the main interface to perform actual database operation. Transaction Object A Transaction represents a unit of work with the database and most of the RDBMS supports transaction functionality. Transactions in Hibernate are handled by an underlying transaction manager and transaction (from JDBC or JTA). This is an optional object and Hibernate applications may choose not to use this interface, instead managing transactions in their own application code. Query Object: Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects. A Query instance is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query. Hence Persistent objects are retrieved using a query object. Criteria Object Criteria object are used to create and execute object oriented criteria queries to retrieve objects. Persistent object can also be retrieved using a criteria object. CU IDOL SELF LEARNING MATERIAL (SLM)
180 Advanced Internet Programming 9.3 Hibernate Configuration Hibernate Environment Setup This chapter will explain how to install Hibernate and other associated packages to prepare a develop environment for the Hibernate applications. We will work with MySQL database to experiment with Hibernate examples, so make sure you already have setup for MySQL database. Downloading Hibernate It is assumed that you already have latest version of Java is installed on your machine. Following are the simple steps to download and install Hibernate on your machine. Make a choice whether you want to install Hibernate on Windows, or Unix and then proceed to the next step to download. zip file for windows and .tz file for Unix. At the time of writing this tutorial I downloaded hibernate-distribution-3.6.4.Final and when you unzip the downloaded file it will give you directory structure as follows. Fig. 9.6: Directory Structure of Downloaded Hibernate Installing Hibernate Once you downloaded and unzipped the latest version of the Hibernate Installation file, you need to perform following two simple steps. Make sure you are setting your CLASSPATH variable properly otherwise you will face problem while compiling your application. Now copy all the library files from /lib into your CLASSPATH, and change your classpath variable to include all the JARs: Finally copy hibernate3.jar file into your CLASSPATH. This file lies in the root directory of the installation and is the primary JAR that Hibernate needs to do its work. CU IDOL SELF LEARNING MATERIAL (SLM)
Java Hibernate 181 Hibernate Prerequisites Following is the list of the packages/libraries required by Hibernate and you should install them before starting with Hibernate. To install these packages you would have to copy library files from /lib into your CLASSPATH, and change your CLASSPATH variable accordingly. Hibernate Configuration Hibernate requires to know in advance where to find the mapping information that defines how your Java classes relate to the database tables. Hibernate also requires a set of configuration settings related to database and other related parameters. All such information is usually supplied as a standard Java properties file called hibernate.properties, or as an XML file named hibernate.cfg.xml. Struture of hibernate.cfg.xml file Hibernate uses the “ hibernate.cfg.xml ” file to create the connection & setup the required environment. Ans: This file contains information such as….. 1. Database Connection 2. Resource mapping hibernate.cfg.xml <?xml version=\"1.0\" encoding=\"UTF-8\"?> <!DOCTYPE hibernate-configuration PUBLIC \"-//Hibernate/Hibernate Configuration DTD 3.0//EN\" \"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd\"> <hibernate-configuration> <session-factory> <property name=\"hibernate.dialect\">org.hibernate.dialect.MySQLDialect</property> <property name=\"hibernate.connection.driver_class\">com.mysql.jdbc.Driver</property> <property name=\"hibernate.connection.url\"> jdbc:mysql://localhost:3306/Feedback </property> <property name=\"hibernate.connection.username\">root</property> <property name=\"hibernate.connection.password\">root</property> </session-factory> </hibernate-configuration> Explaination: 1. hibernate.connection.driver_class: It is the JDBC connection class for the specific database. CU IDOL SELF LEARNING MATERIAL (SLM)
182 Advanced Internet Programming 2. hibernate.connection.url: It is the full JDBC URL to the database. 3. hibernate.connection.username: It is the username used to connection the database. 4. hibernate.connection.password: It is the password used to authenticate the username. 5. hibernate.dialect: It is the name of SQL dialect for the database. Detailed Explaination I will consider XML formatted file hibernate.cfg.xml to specify required Hibernate properties in my examples. Most of the properties take their default values and it is not required to specify them in the property file unless it is really required. This file is kept in the root directory of your application’s classpath. Hibernate Properties Following is the list of important properties you would require to configure for a databases in a standalone situation: Properties and Description 1. hibernate.dialect 4. hibernate.connection.username This property makes Hibernate generate the The database username. appropriate SQL for the chosen database. 2. hibernate.connection.driver_class 5. hibernate.connection.password The JDBC driver class. The database password. 3. hibernate.connection.url 6. hibernate.connection.pool_size The JDBC URL to the database instance. Limits the number of connections waiting in the Hibernate database connection pool. 7. hibernate.connection.autocommit Allows autocommit mode to be used for the JDBC connection. If you are using a database along with an application server and JNDI then you would have to configure the following properties: Properties and Description 1. hibernate.connection.datasource 4. hibernate.jndi.url The JNDI name defined in the application Provides the URL for JNDI. server context you’re using for the application. 2. hibernate.jndi.class 5. hibernate.connection.username The InitialContext class for JNDI. The database username. CU IDOL SELF LEARNING MATERIAL (SLM)
Java Hibernate 183 3. hibernate.jndi.<JNDIpropertyname> 6. hibernate.connection.password Passes any JNDI property you like to the JNDI The database password. InitialContext. 9.4 Hibernate Sessions class the Session object will be created on demand. Session is a lightweight object. Session provides a physical connectivity between your application and database. The Session will be established each time your application wants do something with database. Session object will be provided by SessionFactory object. All the persistent objects will be saved and retrieved through Session object. The session object must be destroyed after using it. The lifecycle of a Session is bounded by the beginning and end of a logical transaction. The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes. Instances may exist in one of three states: transient: never persistent, not associated with any Session. persistent: associated with a unique Session. detached: previously persistent, not associated with any Session. Here is the sample implementation for getting Session object from SessionFactory: HibernateUtil configuration.configure(\"/j2n-hibernate.cfg.xml\"); package com.java2novice.hibernate; import org.hibernate.HibernateException; configuration.addAnnotatedClass(Employee.clas import org.hibernate.Session; s); import org.hibernate.SessionFactory; import ServiceRegistry srvcReg = new org.hibernate.boot.registry.StandardServiceR egistryBuilder; StandardServiceRegistryBuilder().applySettings( import org.hibernate.cfg.Configuration; configuration.getProperties()).build(); import org.hibernate.service.ServiceRegistry; import com.java2novice.model.Employee; sessionFactory = public class HibernateUtil { configuration.buildSessionFactory(srvcReg); private static SessionFactory sessionFactory = null; } static { try{ public static Session getSession() throws loadSessionFactory(); HibernateException { Session retSession=null; try { retSession = sessionFactory.openSession(); }catch(Throwable t){ System.err.println(\"Exception while getting session.. \"); CU IDOL SELF LEARNING MATERIAL (SLM)
184 Advanced Internet Programming } catch(Exception e) { t.printStackTrace(); } System.err.println(\"Exception while initializing if(retSession == null) { hibernate util.. \"); System.err.println(\"session is discovered null\"); } e.printStackTrace(); return retSession; }} }} public static void loadSessionFactory() { Configuration configuration = new Configuration(); List of methods which will be used very often in Hibernate implementations: beginTransaction() Begin a unit of work and return the associated Transaction object. This method needs to be called if you want to enable transaction, and once your DB interactions are done, call commit() method on the returned transaction object. Incase of any issues, call rollback() error on the transaction object. save() Persist the given transient instance, first assigning a generated identifier. This method stores the given object in the database. Before storing, it checks for generated identifier declaration and process it first, then it will store into DB. update() Update the persistent instance with the identifier of the given detached instance. It updates the database record. saveOrUpdate() Either save(Object) or update(Object) the given instance, depending upon resolution of the unsaved-value checks. This operation cascades to associated instances if the association is mapped with cascade=\"save-update\". createQuery() Create a new instance of Query for the given HQL query string. createSQLQuery() Create a new instance of SQLQuery for the given SQL query string. CU IDOL SELF LEARNING MATERIAL (SLM)
Java Hibernate 185 merge() Copy the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent instance. The given instance does not become associated with the session. This operation cascades to associated instances if the association is mapped with cascade=\"merge\". persist() Make a transient instance persistent. This operation cascades to associated instances if the association is mapped with cascade=\"persist\". flush() Force this session to flush. Must be called at the end of a unit of work, before committing the transaction and closing the session. Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory. delete() Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving Session or a transient instance with an identifier associated with existing persistent state. This operation cascades to associated instances if the association is mapped with cascade=\"delete\". 9.5 Hibernate Persistent Class Persistent classes are those java classes whose objects have to be stored in the database tables. They should follow some simple rules of Plain Old Java Object programming model (POJO). Some rules that should be, not must be followed by a persistence class. 1. A persistence class should have a default constructor. 2. A persistence class should have an id to uniquely identify the class objects. 3. All attributes should be declared private. 4. Public getter and setter methods should be defined to access the class attributes Java classes whose objects or instances will be stored in database tables are called persistent classes in Hibernate. Hibernate works best if these classes follow some simple rules, also known as the Plain Old Java Object (POJO) programming model. CU IDOL SELF LEARNING MATERIAL (SLM)
186 Advanced Internet Programming There are following main rules of persistent classes, however, none of these rules are hard requirements − 1. All Java classes that will be persisted need a default constructor. 2. All classes should contain an ID in order to allow easy identification of your objects within Hibernate and the database. This property maps to the primary key column of a database table. 3. All attributes that will be persisted should be declared private and have getXXX and setXXX methods defined in the JavaBean style. 4. A central feature of Hibernate, proxies, depends upon the persistent class being either non-final, or the implementation of an interface that declares all public methods. 5. All classes that do not extend or implement some specialized classes and interfaces required by the EJB framework. 6. The POJO name is used to emphasize that a given object is an ordinary Java Object, not a special object, and in particular not an Enterprise JavaBean. Simple POJO Example Based on the few rules mentioned above, we can define a POJO class as follows – public class Employee { public String getFirstName() { return firstName; private int id; } public void setFirstName( String first_name ) { private String firstName; this.firstName = first_name; } private String lastName; public String getLastName() { return lastName; private int salary; } public void setLastName( String last_name ) { public Employee() { } this.lastName = last_name; } public Employee(String fname, String lname, public int getSalary() { int salary) { return salary; } this.firstName = fname; public void setSalary( int salary ) { this.salary = salary; this.lastName = lname; }} this.salary = salary; } public int getId() { return id; } public void setId( int id ) { this.id = id; } CU IDOL SELF LEARNING MATERIAL (SLM)
Java Hibernate 187 9.6 Hibernate Mapping Hibernate mapping file is used by hibernate framework to get the information about the mapping of a POJO class and a database table. It mainly contains the following mapping information: 1. Mapping information of a POJO class name to a database table name. 2. Mapping information of POJO class properties to database table columns. Elements of the Hibernate mapping file: 1. hibernate-mapping: It is the root element. 2. Class: It defines the mapping of a POJO class to a database table. 3. Id: It defines the unique key attribute or primary key of the table. 4. Generator: It is the sub element of the id element. It is used to automatically generate the id. 5. Property: It is used to define the mapping of a POJO class property to database table column. Syntax <hibernate-mapping> <class name=\"POJO class name\" table=\"table name in database\"> <id name=\"propertyName\" column=\"columnName\" type=\"propertyType\" > <generator class=\"generatorClass\"/> </id> <property name=\"propertyName1\" column=\"colName1\" type=\"propertyType \" /> <property name=\"propertyName2\" column=\"colName2\" type=\"propertyType \" /> …. </class> </hibernate-mapping> List of mapping elements used in the mapping file − The mapping document is an XML document having <hibernate-mapping> as the root element, which contains all the <class> elements. CU IDOL SELF LEARNING MATERIAL (SLM)
188 Advanced Internet Programming The <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute. The <meta> element is optional element and can be used to create the class description. The <id> element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type. The <generator> element within the id element is used to generate the primary key values automatically. The class attribute of the generator element is set to native to let hibernate pick up either identity, sequence, or hilo algorithm to create primary key depending upon the capabilities of the underlying database. The <property> element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type. 9.7 O/R Mapping Hibernate O/RM (Object/Relational Mapping). O/RM itself can be defined as a software or product that represents and/or convert the data between the application (written in Object-Oriented Language) and the database. In other words we can say O/RM maps an object to the relational database table. Hibernate is also an O/RM and is available as open source project. To use Hibernate with Java you will be required to create a file with .hbm.xml extension into which the mapping information will be provided. This file contains the mapping of Object with the relational table that provides the information to the Hibernate at the time of persisting the data. ORM abstracts the application from the process related to database such as saving, updating, deleting of objects from the relational database table. We will understand the above concept with the help of an example CU IDOL SELF LEARNING MATERIAL (SLM)
Java Hibernate 189 Example Employee.java package roseindia; public void setEmpId(long empId) { public class Employee this.empId = empId; { } private long empId; public String getEmpName() { private String empName; public Employee() { return this.empName; } } public long getEmpId() { public void setEmpName(String empName) { return this.empId; this.empName = empName; } }} employee.hbm.xml <?xml version=\"1.0\"?> <!DOCTYPE hibernate-mapping PUBLIC \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\" \"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd\"> <hibernate-mapping> <class name=\"roseindia.Employee\" table=\"employee\"> <id name=\"empId\" type=\"long\" column=\"Id\" > <generator class=\"assigned\"/> </id> <property name=\"empName\"> <column name=\"Name\" /> </property> </class> </hibernate-mapping> The figure given below demonstrates you how ORM abstracts the application to the database related process and vice-versa: CU IDOL SELF LEARNING MATERIAL (SLM)
190 Advanced Internet Programming Java ORM JDBC Relational Application Middlewate Database Fig. 9.7: ORM Abstracts The above figure demonstrates that an ORM abstracts the both in respect to database how an application tries to persist the data and in respect to an application that how objects are stored in database. 9.8 Annotation Mapping Hibernate uses XML mapping file for the transformation of data from POJO to database tables and vice versa. Hibernate annotations are the newest way to define mappings without the use of XML file. You can use annotations in addition to or as a replacement of XML mapping metadata. Hibernate Annotations is the powerful way to provide the metadata for the Object and Relational Table mapping. All the metadata is clubbed into the POJO java file along with the code, this helps the user to understand the table structure and POJO simultaneously during the development. If you going to make your application portable to other EJB 3 compliant ORM applications, you must use annotations to represent the mapping information, but still if you want greater flexibility, then you should go with XML-based mappings. Environment Setup for Hibernate Annotation First of all you would have to make sure that you are using JDK 5.0 otherwise you need to upgrade your JDK to JDK 5.0 to take advantage of the native support for annotations. Second, you will need to install the Hibernate 3.x annotations distribution package, available from the sourceforge: (Download Hibernate Annotation) and copy hibernate-annotations.jar, lib/hibernate-comons-annotations.jar and lib/ejb3-persistence.jar from the Hibernate Annotations distribution to your CLASSPATH. CU IDOL SELF LEARNING MATERIAL (SLM)
Java Hibernate 191 Annotated Class Example As I mentioned above while working with Hibernate Annotation, all the metadata is clubbed into the POJO java file along with the code, this helps the user to understand the table structure and POJO simultaneously during the development. Consider we are going to use the following EMPLOYEE table to store our objects − create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, PRIMARY KEY (id)); Following is the mapping of Employee class with annotations to map objects with the defined EMPLOYEE table − import javax.persistence.*; public void setId( int id ) { @Entity@Table(name = \"EMPLOYEE\")public this.id = id; class Employee { } @Id @GeneratedValue public String getFirstName() { @Column(name = \"id\") return firstName; private int id; } @Column(name = \"first_name\") public void setFirstName( String first_name ) { this.firstName = first_name; private String firstName; } @Column(name = \"last_name\") public String getLastName() { return lastName; private String lastName; } @Column(name = \"salary\") public void setLastName( String last_name ) { private int salary; this.lastName = last_name; } public Employee() {} public int getSalary() { return salary; } public int getId() { public void setSalary( int salary ) { return id; this.salary = salary; } } } CU IDOL SELF LEARNING MATERIAL (SLM)
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
- 309
- 310
- 311
- 312
- 313
- 314
- 315
- 316
- 317
- 318
- 319
- 320
- 321
- 322
- 323
- 324
- 325
- 326
- 327
- 328
- 329
- 330
- 331
- 332
- 333
- 334
- 335
- 336
- 337
- 338
- 339
- 340
- 341
- 342
- 343
- 344
- 345
- 346
- 347
- 348
- 349
- 350
- 351
- 352
- 353
- 354
- 355
- 356
- 357
- 358
- 359
- 360
- 361
- 362
- 363
- 364
- 365
- 366
- 367
- 368
- 369
- 370
- 371
- 372