Java & J2EE Struts with Hibernate Framework

9,412 views

Published on

A complete presentation on Java and J2ee with Struta & Hibernate framework

4 Comments
13 Likes
Statistics
Notes
No Downloads
Views
Total views
9,412
On SlideShare
0
From Embeds
0
Number of Embeds
11
Actions
Shares
0
Downloads
661
Comments
4
Likes
13
Embeds 0
No embeds

No notes for slide
  • Other servlet examples implement the doPost() and/or doGet() methods. These methods reply only to POST or GET requests; if you
    want to handle all request types from a single method, your servlet can simply implement the service() method. (However, if you choose to implement the service() method, you will not be able to implement the doPost() or doGet() methods, unless you call super.service() at the beginning of the service() method.)
  • Java & J2EE Struts with Hibernate Framework

    1. 1. J2EE-STRUTS WITH HIBERNATE FRAMEWORK BYMohit Chandra Belwal B.Tech(C.S.E)-4th year
    2. 2. Brief Overview: JAVA
    3. 3. Why JAVA? The answer is that Java enables users to develop and deploy applications on the Internet for servers, desktop computers, and small hand-held devices. The future of computing is being profoundly influenced by the Internet, and Java promises to remain a big part of that future. Java is the Internet programming language. Java is a general purpose programming language. Java is the Internet programming language.
    4. 4. Java, Web, and Beyond     Java can be used to develop Web applications. Java Applets Java Web Applications Java can also be used to develop applications for hand-held devices such as Palm and cell phones
    5. 5. Java's History  Developed by Sun Microsystems --James Gosling, Bill Joy, Patrick Naughton Originally named OAK in 1991 Renamed and modified to Java in 1995 First non commercial version in 1994 First Commercial version in late 1995  HotJava      The first Java-enabled Web browser
    6. 6. Java Technology  What is Java? Java technology is both a programming language and a platform. --The Java Programming Language The Java programming language is a high-level language that can be characterized by all of the following buzzwords: -Simple -Distributed -Dynamic -Portable -Robust -Object oriented -Multithreaded -Architecture neutral -High performance -Secure
    7. 7. Java Technology….  Characteristics of Java:  Simple: Java is partially modeled on C++, but greatly simplified and improved. Some people refer to Java as "C++--" because it is like C++ but with more functionality and fewer negative aspects.  Object Oriented: Object-oriented programming (OOP) is a popular programming approach that is replacing traditional procedural programming techniques. One of the central issues in software development is how to reuse code. Object-oriented programming provides great flexibility, modularity, clarity, and reusability through abstraction, encapsulation, inheritance, and polymorphism.
    8. 8. Java Technology….  Characteristics of Java:  Distributed: Distributed computing involves several computers working together on a network. Java is designed to make distributed computing easy. Since networking capability is inherently integrated into Java, writing network programs is like sending and receiving data to and from a file.  Multi Threaded: Multithread programming is smoothly integrated in Java, whereas in other languages you have to call procedures specific to the operating system to enable multithreading.
    9. 9. Java Technology….  Characteristics of Java:  Dynamic: Java was designed to adapt to an evolving environment. New code can be loaded on the fly without recompilation. There is no need for developers to create, and for users to install, major new software versions. New features can be incorporated transparently as needed. Architecture Neutral: Write once, run anywhere  With a Java Virtual Machine (JVM), you can write one program that will run on any platform.
    10. 10. Java Technology….  Characteristics of Java:  Portable: Because Java is architecture neutral, Java programs are portable. They can be run on any platform without being recompiled. High Performance: The java programs are compiled to portable intermediate form known as the bytecodes, rather then machine level instructions and JVM executes them on any machine on which it is placed. JVM uses the adaptive and JIT technique that improves performance by converting the java bytecodes to native machine instructions on the fly. 
    11. 11. Java Technology….  Characteristics of Java: Robust: Java compilers can detect many problems that would first show up at execution time in other languages.  Java has eliminated certain types of error-prone programming constructs found in other languages. Java has a runtime exception-handling feature to provide programming support for robustness. Java provides automatic memory management.  Secure: Java implements several security mechanisms to protect your system against harm caused by stray programs.
    12. 12. Java Technology….  What is Java? --The Java Platform A platform is the hardware or software environment in which a program runs. Some of the most popular platforms are Microsoft Windows, Linux, Solaris OS, and Mac OS. Most platforms can be described as a combination of the operating system and underlying hardware. The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms. The Java platform has two components: --The Java Virtual Machine --The Java Application Programming Interface (API)
    13. 13. Java Virtual Machine (JVM)     JVM is part of Java programming language. JVM is a software, staying on top of Operating System, such as UNIX, Windows NT. It help Java create high level of portability by hiding the difference between the Operating System implementations. It creates an environment that Java language lives.
    14. 14. Why JVM?    An ordinary language can not create a system independent program. Java’s goal is “Write-Once-Run-Anywhere”. Java programs are not computer, operating system dependent. Need to create an “abstract computer” of its own and runs on it, a kind of virtual machine which hiding the different OS implementations.
    15. 15. Java Runtime Environment (JRE)
    16. 16. How JVM works?     Java programs are compiled into byte code. JVM interprets and converts Java byte code into machine code in order to execute on a CPU. Most web browser has an integrated JVM to run applets. Other JVM tasks include:  Object creations of Java programs.  Garbage collection.  Security responsibility.
    17. 17. Java’s Magic: The Bytecode    JVM keeps a compact set of Byte Code Instructions in order to interpret byte code into native binary code. Java compilers do not translate programs directly into native binary code, which is system dependent. Instead, programs are translated into byte code, just in its midway to a runnable. JVM interprets these half-cooked byte code into executable machine code on different computer systems and platforms.
    18. 18. JIT Compiler    JIT stands for “Just In Time”. 10 years ago, a smart idea was discovered by Peter Deutsch while trying to make Smalltalk run faster. He called it “dynamic translation” during interpretation. Every time JIT compiler interprets byte codes, it will keep the binary code in log and optimize it. Next time, when the same method is running, the optimized code will run. Experiments show Java programs using JIT could be as fast as a compiled C program.
    19. 19. JIT Example  ( Loop with 1000 times ) for(int i=0;i<1000;i++){ do_action( ); } Without JIT, JVM will interpret do_action() method 1000 times. (A waste of time!) With JIT, JVM interprets do_action() method only once and keeps it in log, and the binary native code will execute for the rest 999 loops.
    20. 20. JIT Compiler…. Java Virtual Machine Java Compiler Optimize d & Kept in Log Compiled Byte Code JIT Compiler Native Machine Code Machine
    21. 21. Java Technology…. An overview of the Software Development process
    22. 22. Java Technology…. Through the Java VM, the same application is capable of running on multiple platforms.
    23. 23. Java Application Programming Interface (API)  The API is a large collection of ready-made software components that provide many useful capabilities.  It is grouped into libraries of related classes and interfaces; these libraries are known as packages. The API and Java Virtual Machine insulate the program from the underlying hardware.
    24. 24. Different Editions of Java  Java Standard Edition (J2SE)   Java Enterprise Edition (J2EE)   J2SE can be used to develop client-side standalone applications or applets. J2EE can be used to develop server-side applications such as Java servlets, Java ServerPages, and Java ServerFaces. Java Micro Edition (J2ME).  J2ME can be used to develop applications for mobile devices such as cell phones.
    25. 25. A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }
    26. 26. Creating, Compiling, and Running Programs Create/Modify Source Code Source code (developed by the programmer) public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } } Byte code (generated by the compiler for JVM to read and interpret, not for you to understand) … Method Welcome() 0 aload_0 … Method void main(java.lang.String[]) 0 getstatic #2 … 3 ldc #3 <String "Welcome to Java!"> 5 invokevirtual #4 … 8 return Saved on the disk Source Code Compile Source Code i.e., javac Welcome.java If compilation errors stored on the disk Bytecode Run Byteode i.e., java Welcome Result If runtime errors or incorrect result
    27. 27. Trace a Program Execution Enter main method //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }
    28. 28. Trace a Program Execution Execute statement //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }
    29. 29. Trace a Program Execution //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } } print a message to the console
    30. 30. Starting J2EE JAVA ENTERPRISE EDITION (J2EE)
    31. 31. J2EE Concepts : Definition : The Java 2 Enterprise Edition (J2EE) is a multi-tiered architecture for implementing enterprise-class applications and web based applications. Model : It is based on component based application model. In this model such components use services provided by the container which would otherwise typically need to be incorporated in the application code.  Open and standard based platform for  developing, deploying and managing  n-tier, Web-enabled, server-centric, and component-based enterprise applications
    32. 32. J2EE Features      Component based model Container provided services Highly Scalable Simplified Architecture Flexible security model
    33. 33. J2EE Benefits   Flexibility of scenarios and support to several types of clients. Programming productivity:     Services allow developer to focus on business Component development facilitates maintenance and reuse Enables deploy-time behaviors Supports division of labor
    34. 34. J2EE Components    Application clients and applets are components that run on the client. Java Servlet and JavaServer Pages technology components are Web components that run on the web server. (Web Container) Enterprise JavaBeans components (enterprise beans) are business components that run on the application server. (EJB Container)
    35. 35. J2EE Components -- continued
    36. 36. J2EE Containers Definition : Containers are the interface between a component and the low-level platform-specific functionality that supports the component. Ex: Apache Tomcat, GlassFish Types :  Enterprise JavaBeans (EJB) container  Web container  Application client container  Applet container
    37. 37. J2EE Container -- continued
    38. 38. What does container gives you?      Communications Support Lifecycle Management Multithreading Support Declarative Security JSP Support
    39. 39. J2EE Components   As said earlier, J2EE applications are made up of components A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and that communicates with other components
    40. 40. Components    Client components run on the client machine, which correlate to the client containers Web components -Servlets and JSP page EJB Components
    41. 41. Packaging Applications and Components   Under J2EE, applications and components reside in Java Archive (JAR) files These JARs are named with different extensions to denote their purpose, and the terminology is important
    42. 42. Various File types    Enterprise Archive (EAR) files represent the application, and contain all other server-side component archives that comprise the application Client interface files and EJB components reside in JAR files Web components reside in Web Archive (WAR) files
    43. 43. Deployment Descriptors    Deployment descriptors are included in the JARs, along with component-related resources Deployment descriptors are XML documents that describe configuration and other deployment settings (remember that the J2EE application server controls many functional aspects of the services it provides) The statements in the deployment descriptor are declarative instructions to the J2EE container; for example, transactional settings are defined in the deployment descriptor and implemented by the J2EE container
    44. 44. J2EE Application Model    Browser is able to process HTML and applets pages. It forwards requests to the web server, which has JSPs and Servlets Servlets and JSPs may access EJB server.
    45. 45. J2EE Application Model
    46. 46. Overview of Servlets       Are container managed web components Processes HTTP requests (non-blocking call-andreturn) Loaded into memory once and then called many times Generate dynamic response to requests from web based clients Synchronize multiple concurrent client request Better alternative to CGI  Efficient  Platform and server independent  Session management  Java-based
    47. 47. Servlet Operation    Servlet is Java program that runs as separate thread inside servlet container. Servlet container is part of web server It interact with web client using response request paradigm.
    48. 48. The Servlet API ServletConfig Servlet GenericServlet ServletRequest HttpServlet HttpServletRequest ServletResponse HttpServletResponse javax.servlet.* javax.servlet.http.* 48
    49. 49. Lifecycle of Servlets
    50. 50. Servlet example public class HelloWorldServlet extends HttpServlet { public void service(HttpServletRequest req, HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<html><head><title>Hello World Servlet</title></head>"); out.println("<body><h1>Hello World!</h1></body></html>"); } }
    51. 51. Overview of JSP    JSP (Java Server Pages) is an alternate way of creating servlets  JSP is written as ordinary HTML, with a little Java mixed in  The Java is enclosed in special tags  The HTML is known as the template text JSP files must have the extension .jsp  JSP is translated into a Java servlet, which is then compiled  Servlets are run in the usual way  The browser or other client sees only the resultant HTML, as usual Tomcat knows how to handle servlets and JSP pages
    52. 52. Parts of JSP Pages  Directive  Directives affect the servlet class itself. The most useful directive is page, which lets you import packages. <%@ page import=“java.util.”, MVCApp.Cart, MVCApp.CartItem” %>  Declaration  The declarations are inserted into the servlet class, not into a method <%! Iterator it = null; CartItem ci = null; Vector cpi = null;%>  Raw HTML <html><head><title>Shopping Cart</title></head></html>  Action  Actions are XML-syntax tags used to control the servlet engine <jsp:usebean id =“Cart” scope = “session” class = “MVCApp.Cart”/>  Scriplets   The code is inserted into the servlet's service method This construction is called a scriptlet <% Cpi = cart.getCartItems ( ); it = cpi.iterator(); While (it.hasNext()){ci= (Cart Item)it.next(); %>
    53. 53. Parts of JSP Pages  Expression  The expression is evaluated and the result is inserted into the HTML page. <td<% = ci.getTitle() %></td> <td align =“right”><%=ci.getQuantity()%></td>  Implicit Objects  JSP provides several predefined objects. <% string action = request.getParameter(“action”) ; %>
    54. 54. JSP Life Cycle Process of a JSP page
    55. 55. JSP Life Cycle  (cont.) JSP initialization  The jspInit() method is executed first after the JSP is loaded.  If the JSP developer needs to perform any JSPspecific initialization such as database connections at the beginning this method can be specified.  The jspInit() is only called once during any JSP component life time.
    56. 56. JSP Life Cycle  (cont.) JSP execution public _service(HttpServletRequest req, HttpServletResponse res) is a JSP service method the same as the service() method of a Servlet class. This method never needs to be customized. All Java code defined in scripting elements are inserted in this method by JSP engine.  JSP termination <%! public void jspDestroy(){ . . . } %> This method allows developers to specify resource cleanup jobs such as database disconnections.
    57. 57. JSP example <tr> <td width="150" &nbsp; </td> <td width="550"> <form method="get"> <input type="text" name="username" size="25"> <br> <input type="submit" value="Submit"> <input type="reset" value="Reset"> </td> </tr> </form> </table> <% if (request.getParameter("username") != null) { %> <%@ include file="response.jsp" %> <% } %> </body> </html>
    58. 58. JSP Standard Tag Library (JSTL)  JSP 1.2 introduced supported for a special tag library called the JSP Standard Tag Library (JSTL)  The JSTL saves programmers from having to develop custom tag libraries for a range of common tasks, such as if statements, conditional loops etc.  Enables developers to produce more maintainable and simpler JSP code  Important development for JSP technology
    59. 59. JSTL  The JSP Standard Tag Library groups actions into four libraries as follows: Library Contents Core Core functions such as conditional processing and looping, important data from external environments etc Formatting Format and parse information SQL read and write relational database data XMl Processing of XML data
    60. 60. JSTL  To use any of these libraries in a JSP, need to declare using the taglib directive in the JSP page, specifying the URI and the Prefix Library Prefix URI Core c http://java.sun.com/jsp/jstl/core Formatting fmt http://java.sun.com/jsp/jstl/fmt SQL sql http://java.sun.com/jsp/jstl/sql XMl xml http://java.sun.com/jsp/jstl/xml Example of declaring use of core library: <%@ taglib prefix = “c” uri = “http://java.sun.com/jsp/jstl/core %>
    61. 61. JSTL: Example Example: JSP page using JSTL that outputs 1 to 10 on a webpage using the <c:forEach> and <c:out> tags of the core library <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <html> <head> <title>Count to 10 Example (using JSTL)</title> </head> <body> <c:forEach var="i" begin="1" end="10" step="1"> <c:out value="${i}" /> <br /> </c:forEach> </body> </html> A taglib directive declare use of core library JSTL tag examples
    62. 62. Beginning Struts Framework
    63. 63. Model-view-controller (MVC) Design Pattern  MVC helps resolve some of the issues with the single module approach by dividing the problem into three categories:  Model.   View.   The model contains the core of the application's functionality. The model encapsulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller. The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur. Controller.  The controller reacts to the user input. It creates and sets the model.
    64. 64. Model-view-controller (MVC) Design Pattern
    65. 65. Two Different Models  MVC or JSP Model 1 and Model 2 differ essentially in the location at which the bulk of the request processing is performed. Model 1 Model 2
    66. 66. Model 1  In the Model 1 architecture the JSP page alone is responsible for processing the incoming request and replying back to the client.
    67. 67. Model 1    There is still separation of presentation from content, because all data access is performed using beans. Model 1 architecture is perfectly suitable for simple applications but it may not be desirable for complex implementations. Indiscriminate usage of this architecture usually leads to a significant amount of scriptlets or Java code embedded within the JSP page
    68. 68. Model 2   A hybrid approach for serving dynamic content. It combines the use of both servlets and JSP.
    69. 69. Model 2  The servlet:      performs process-intensive tasks. acts as the controller. is in charge of the request processing. creates any beans or objects used by the JSP. Decides, depending on the user's actions, which JSP page to forward the request to.
    70. 70. Model 2  The JSP:     generates the presentation layer. has no processing logic. Is responsible for retrieving any objects or beans that may have been previously created by the servlet. Extracts the dynamic content from the servlet for insertion within static templates.
    71. 71. Model 2    Typically results in the cleanest separation of presentation from content. Leads to clear delineation of the roles and responsibilities of the developers and page designers. The more complex your application, the greater the benefits of using the Model 2 architecture should be.
    72. 72. Jakarta Struts Is:  A model-view-controller (MVC) Model 2 implementation that uses servlets and JavaServer pages (JSP) technology.
    73. 73. Struts, an MVC 2 Implementation    Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2 design. This definition implies that Struts is a framework, rather than a library. Struts also contains an extensive tag library and utility classes that work independently of the framework.
    74. 74. Struts Overview
    75. 75. Request Processing 4 Action ActionForm 5 3 Model 6 1 Web Browser displays page 2 Controller struts-config 8 7 JSP Page
    76. 76. Struts Overview  Client browser  An HTTP request from the client browser creates an event. The Web container will respond with an HTTP response.
    77. 77. Struts Overview  Controller    The Controller receives the request from the browser, and makes the decision where to send the request. With Struts, the Controller is a command design pattern implemented as a servlet which is ActionServlet. The struts-config.xml file configures the Controller.
    78. 78. Struts Overview  Business logic   The business logic updates the state of the model and helps control the flow of the application. With Struts this is done with an Action class as a thin wrapper to the actual business logic.
    79. 79. Struts Overview  Model state     The model represents the state of the application. The business objects update the application state. The ActionForm bean represents the Model state at a session or request level, and not at a persistent level. The JSP file reads information from the ActionForm bean using JSP tags.
    80. 80. Struts Overview  View    The view is simply a JSP file. There is no flow logic, no business logic, and no model information -- just tags. Tags are one of the things that make Struts unique compared to other frameworks.
    81. 81. The ActionServlet Class   The Struts Controller is a servlet that maps events (an event generally being an HTTP post) to classes. The Controller uses a configuration file so we don’t have to hard-code the values.
    82. 82. The ActionServlet Class      ActionServlet is the Command part of the MVC implementation. It is the core of the Framework. ActionServlet (Command) creates and uses an Action, an ActionForm, and an ActionForward. The struts-config.xml file configures the Command. During the creation of the Web project, Action and ActionForm are extended to solve the specific problem space.
    83. 83. The ActionServlet Class  There are several advantages to this approach:    The entire logical flow of the application is in a hierarchical text file. This makes it easier to view and understand, especially with large applications. The page designer does not have to wade through Java code to understand the flow of the application. The Java developer does not need to recompile code when making flow changes.
    84. 84. The ActionForm Class    ActionForm maintains the session state for the Web application. ActionForm is an abstract class that is subclassed for each input form model. ActionForm represents a general concept of data that is set or updated by a HTML form. E.g., you may have a UserActionForm that is set by an HTML Form.
    85. 85. The ActionForm Class  The Struts framework will:    Check to see if a UserActionForm exists; if not, it will create an instance of the class. Set the state of the UserActionForm using corresponding fields from the HttpServletRequest.  No more request.getParameter() calls. For instance, the Struts framework will take fname from request stream and call UserActionForm.setFname(). The Struts framework updates the state of the UserActionForm before passing it to the business wrapper UserAction.
    86. 86. The ActionForm Class  Notes:   The struts-config.xml file controls which HTML form request maps to which ActionForm. Multiple requests can be mapped to UserActionForm.
    87. 87. The Action Class    The Action class is a wrapper around the business logic. The purpose of Action class is to translate the HttpServletRequest to the business logic. To use Action, subclass and overwrite the perform() method.
    88. 88. The Action Class    The ActionServlet (Command) passes the parameterized classes to ActionForm using the perform() method. No more request.getParameter() calls. By the time the event gets here, the input form data (or HTML form data) has already been translated out of the request stream and into an ActionForm class.
    89. 89. The Action Class  Note:    "Think thin" when extending the Action class. The Action class should control the flow and not the logic of the application. By placing the business logic in a separate package or EJB, we allow flexibility and reuse.
    90. 90. The Action Class    Another way of thinking about Action class is as the Adapter design pattern. The purpose of the Action is to "Convert the interface of a class into another interface the clients expect." "Adapter lets classes work together that couldn’t otherwise because of incompatibility of interfaces" (from Design Patterns - Elements of Reusable OO Software by Gof).
    91. 91. The Action Class    The client in this instance is the ActionServlet that knows nothing about our specific business class interface. Struts provides a business interface it does understand, Action. By extending the Action, we make our business interface compatible with Struts business interface.
    92. 92. The ActionMapping Class   An incoming event is normally in the form of an HTTP request, which the servlet Container turns into an HttpServletRequest. The Controller looks at the incoming event and dispatches the request to an Action class.
    93. 93. The ActionMapping Class   The struts-config.xml determines what Action class the Controller calls. The struts-config.xml configuration information is translated into a set of ActionMapping, which are put into container of ActionMappings.
    94. 94. The ActionMapping Class    The ActionMapping contains the knowledge of how a specific event maps to specific Actions. The ActionServlet (Command) passes the ActionMapping to the Action class via the perform() method. This allows Action to access the information to control flow.
    95. 95. Hibernate: An Introduction
    96. 96. What is Hibernate?    It is an object-relational mapping (ORM) solution for Java We make our data persistent by storing it in a database Hibernate takes care of this for us
    97. 97. Object-Relational Mapping   It is a programming technique for converting object-type data of an object oriented programming language into database tables. Hibernate is used convert object data in JAVA to relational database tables.
    98. 98. Why Hibernate and not JDBC?  JDBC maps Java classes to database tables (and from Java data types to SQL data types)  Hibernate automatically generates the SQL queries.  Hibernate provides data query and retrieval facilities and can significantly reduce development time otherwise spent with manual data handling in SQL and JDBC.  Makes an application portable to all SQL databases.
    99. 99. Hibernate vs. JDBC (an example)  JDBC tuple insertion – st.executeUpdate(“INSERT INTO book VALUES(“Harry Potter”,”J.K.Rowling”));  Hibernate tuple insertion – session.save(book1);
    100. 100. Architecture Hibernate sits between your code and the database Maps persistent objects to tables in the database
    101. 101. End Of Presentation THANK YOU….

    ×