You are on page 1of 30
t} args) { PathResource( appli tionContext.xml BeanFactory(resoure®); tory.getBean( studentbean ‘i ce ‘ompiled By : Priyal Patel and Rajal Shah va Project: Dependency Injection (D! a general concept ‘The technology that Spring is most identified 1. The Inversion of Control (IoC) is rely one conere Inversion of Control opresse it many different ways. Dependency Injection Is Inversion of Control. Dependeney Injection is a fundamental aspect of the Spring fm Spring eoniainer'injets” objects into other objects or “dependen Stply put, this allows for loose coupling of components and mov managing components onto the container: > Spring Configuratio: ng core framework. Spring Configuration ‘annotation indicates that the class has @Bean definition methods. So Spring container can 1¢ Spring Beans to be used in the application. It indicates that a ed by the Spring container to rk, through which the ces the responsibility of Spring @Configuration annotation is part of the s} process the class and generat class declares one or more @Bean methods and may be proc ‘generate bean definitions and service requests for those beans at runtime: Page No. 46 Compiled By : Priyal Patel and Rajal Shah 4. AOP and Instrumentation: fant aspect-oriented programming ‘Spring's AOP module provides an AOP Allianc santa terceptors and pointcuts to implementation allowing you to define, for example, mt logically speaking be cleanly decouple code implementing functionality that sho me Scharated. Using source-tevel metadata functionality you can ali ONE ateOGea Tanloral information into your code, in a manne similar otha of NE ma ‘There is also a separate Aspects module that provides integration with pare : ae ine instrumentation module provides class. instrumentation support and cl implementations to be used in certain application servers 5. Test: The Test module contains the Test Framew. using Junit or TestNG. It provides consisie caching of those contexts. It also containg ‘many testing scenarios to test your code in > Inversion of Control (oC): TOC is also known as dependency injection (DD). It is a process whereby objects define the ependencies, that is, the other objects they wi “only rosgh constructor arguments, are Set on the object instance after it is conta then injects those dependencies ‘ork that supports testing Spring components nt loading of Spring ApplicationContexts and @ number of Mock objects that are usful in olation. a inverse, hence the name Inversion tantiation or location of its dependencies chanism such as the Service Locator pattern. eframey Dh are the basis for onality. The Applicat exclusively in th J2EE Tutorials cnoves the need for pro ‘ Modules: The Spring Framework contains a lot of features, which are well-organized in about twenty Todules. These modules can be grouped together based on their primary features into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation and Test, These Groups are shown in the diagram below, Validation, transactions and formatting. 1. Core Container: ie ‘The Core Container consists of the Core, Bean: ‘The Core and Beans modules provide the most ‘ Provides the 1oC and Dependency Injestio the BeanFactory which provides a sophisti Page No. 43 rm, It was ini license in June 200: . ic version of rk ean be used in developing any Java ailing web applications ontop of the Jove mtg make J2EE development easier 10 068 and fices by enabling @ POJO-based programming deney injection, events, resources, i18%- validation, data jon, SpEL. AOP. jects, TestContext framework, Spring MVC Test. WebTestClient fons, DAO support, JDBC, OR! i, Marshalling XML- JebFlux web fram« works. ‘JCA, JMX, email, tasks, mic languages. MVC and Sprit remoting. JMS. scheduling, cache. = Kotlin, Groovy, dyna +1. Predefined Templates ‘Spring framework provides templates for JDBC; Hibernate, JPA etc. technologies. So there is “pe need t04yritetoo much code. It hides.the basic steps of these technologies. Pere take thefexample of SdbcTemplate, you don’t need fo write the code for exception Iandlng, eating connection, creating statement, committing 4a saction, closing connection ie, Youneed 10 write the code of executing query only. Thus, it save a lot of JDBC code. 2. Loose Coupling “The Spring applications are loosely coupled because of dependency injection. 3, Easy to test “The Dependency Injection makes easier to test the a T I sakes easier to test the application. The EJB or Struts application require server to run the application but Spring framework doesn’t require server. rn Page No. 42 Compiled By : Priyal Patel and Rajal Shah 4 Accessing JavaBeans Pr L. : ed to get indicated property from the Jav wet. PBEIProperty> tag isto execute a getter str aBean object. The ategy to get an incentive biect “sed (0 read the property “hich is also called accessor, etProperty nam, ape erty na Property Attributes Hwill take ay Property: | ariab| Hake a p; le that is the same articul as the id attribute valu at property to execute in tag the respective getter method, 2 The jsp: Aisp:setPrope setProperty ta ation behind jsp. incentive to a specie a specific This method is used se Syntax SP'setProperty name. Attributes: Name: It will take a variany. twat a aAbe that i the Property: It will take 8 property name Value: It will take 4 value to pass etP ryt *© Seta property in the J SetProperty tag is t 10 execute a speci Bean property write ‘avaBean object. The principle fic setter technique to setan the property which ig also called mutator, — property —” value: Same as the id attrib in orde he respect 8 a parameter i | | Page No. 41 accesses Java Bean nects to the hich is ss Ji ISP? = FavaBean object that may be used in JSP. The bean becomes @ ay be accessed by both scriptin i ements and itis declared. and it request, session. OF * it’s a distinct name among Bi piiineeds the scope attribute can be set 19 Pere detribuc’s value can be anything as ong 45 1S declarations in the same JSP. HigeBean action is demonsirated inthe example below “aitle> JavaBeans Sample Example The date/time is suvag ase - | “Stuouunoop pur soBed dp ul 3x9} aye|duior ana 0 pas, wwordsy | poq s.WaU}a WX PauLjap-cjreartueUdp souyogy Spog:dse “ainume s,mowa}9 TWX pauljap- ABER -scoped variable names to their values & _applicationScope: Maps application-scoped variable names to their values > ISP Directives: _ ISP Directives: JSP directives are the mes sages to JSP contai i i Caeser eas ge: container. They provide global information about an ISP directives i i . ip i servlet code used 10 give special instruction to a container for install BereRco In JSP life cycle phase, JSP has to be conv ‘let which i i They give instructions to the container on how to handle cad Bi Cee an Directives can have many ati arated as key-value pairs, ‘scribed in <%@ %> tags, Crow 4 Syntax of Directive: <%@ directive attribute” y%> There are three types of directives: 1. Page directive 2. Include directive 3. Taglib directive - JSP Page Directive: Syntax of Page : <%@ page...%>"_ It provides attributes that get applied to entire JSP page. _Itdefines page dependent attributes, such as seripting language, error page, and buffering requirements, ; It is used to provide instructions to a container that Following are its list of attri fated wit 1. Buffer: Specifies a buffering model for the output stream. 2. AutoFlush: Controls the behavior of the servlet output buffer. 3. ContentType: Defines the character encoding scheme, 4. ErtorPagei, Defines the URL of another JSP that reports on Java unchecked exceptions, 5. isErrorPage: Indicates if this JSP page is a URL specified | attribute, 6. Extends: Specifics a superclass that the gent ated seer atte 7. import: Specifies a list of packages or classes for use in the J statement does for Java classes, ‘fai hie old 8. info: Defines a string that can be accessed with the servlet’s 9. isThreadSafe: Defines the threading model for the gene 10. language: Defines the programming | | 11. session: Specifies whether or not the JSP page 12, isELIgnored: Specifies whether or not the El ignored. enti 13. isScriptingEnabled: Determines if the Page No. 37 pertains to current JSP page. page directive: complete JSP page oF # He of a fragment of F ® Fused documents that describe, how ers. Mees and interfaces forthe COTE Ses and interfaces for the JSP 2.0 Expression L lefinition of JavaServer Pa JSP 2.0 APL anguage API fasses and interfaces for the d ISP to the servlet vice method an array of values Page No. 36 Compiled By : Priyal Patel and Rajal Shah a2 BasicDataSou rally Aste name suggests, itis simple and suitable for most common use ‘cases. It intern; ally creates PoolingDataSource for us. 2. PoolingDataso = ice: offers more flexibility. You only need to change code which creates DataSource. The Fest of the code will remain the same. simple. It is one of the preferred solutions for Connection ~ Spring Boot 2.x Uses it as a default connection manager. 3. C3P0: Bae ES oR" oF oldest brary Generally, iti Used with Hibernate, To use C3P0, we need to ‘add following dependency te project, ae a 4 Serouple>com.mehange % Santifactld>c3p0org.apache.commonscommo! Eyersion>2.7.0 me = “binsubmitupdate? Value upiate"> = “btnsubmitdelete” yalue= ‘Delete’ Ie arses Compiled By: ral Patel and Raa shah er("age") String a, request.getParameter("age’ "ide Stings cent, FROM emp WHERE ID: StmLexecuteU pdate(sql); SutprintinDATA HAS BEEN DELE FULLY !
"); eanbtintn("), Out printin(*"; cuterintn'Agecithsty. cut printin(’
Namec/ths: Out printin("", Outprintin("" 4 pe Out. printin(""); } con.close(); } catch (ClassNotFoundE: ex) J Logger getlogger( servlet, 'e0)-log(Level SEVERE, null ex): } catch (SQLException ex) { » i Coe Logger getlogger(serviet] a ime()) log(Level. SEVERE, null, ex); —— NN } mY @Override a Protected yoi reall ttpServletRequest quest, “tht s ServletException, HOEXception { nestisque Fesponse); } e er @Override Ne Protected void doPostHpServletRequest request, 8 throws ServletException, TOException{ ProcessRequest(request, response); 4 erride oar String getServletinfo() { return “Short description”: y Page No. 29 -servletResponse response) t(HttpServietRequest request Http’ TOException { se("text/html;charset-UT! get Writer(s A Name(JDBC_DRIVER): iverManager-getConnection' = con.createStatement0) Dt guest getParameter("binsubrnt) [=D { Seng id = request.getParameter("1 request getParameter("name st. getParameter( age") sp values(" + id +" + name (DB_URL, USER, PASS): String age = reques 1 sql=("insert into ern Sti stmtiexecuteUpdate(sa)> cout printin( "Inserted Successtully!
! if_request.getParameter("binsubmitdelete") != null) String id = request.getParameter("id"); String name = request.getParameter("name"); Page No. 28 J2EE Tutoriaig String name Stee BAM = rs. getString name"); Syenetob = rs.getString "job , S¥stem.out.printingids™ ) “4namet" "4job) } catch(SQLExce ption e) { System.out.printinc'sy k tin ‘QL exception occured" + ¢); ch Process With one call t tes Batch Processing: ing allows yo 10 the databace {0 group related SQL Statements into a batch and submit them tabase at once, you reduce the amount of r mance, Tequired to Support this. features You should use ortsBatchUpdates() method to determine if the target bea thod returns true if your JDBC driver The ad cl ey Required steps: The following steps are required vo + Import the packages — classes needed for suffice, * Register the JDBC driver— Requires that yo communications channel with the database, Open a connection = a Connection object, Execute a query ~ hare new Database using IDBC application — Reauires that you include the packages containing the JDBC database programming. Most often, using import java.sql.* will which represents a physical cor Requires using an obj an SQL statement to insert records into a table. Clean up the environment try with resources ‘automatically closes the resources, > Creating table in JDBC. public void createTable() throws. SQLException { String createString = ‘create table SUPPLIERS "+ "(SUP_ID integer NOT NULL, " + ee "SUP_NAME varchar(40) NOT NULL, "+ "STREET -varchar(40) NOT NULL, "+ "CITY varchar(20) NOT NULL »"+"STATE char(2) NOT NULL, "+ "ZAP char(5), "+ "PRIMARY KEY, (SUP_ID)) try (Statement stmt = con.er reateStatement()) { stmt.executelpdate(createString); } catch (SQLException e) { JDBCTutorialUtilities.printSQLException(e);} ) cae ee Compiled By Priya Patel and Rajal Shah "age No. drivers based 0” iverManager class ed by the and connecting ‘used only by the Dri 2s for a JDBC driver: not us¢ rived L statements. pared statements.of basi cedures (derived from “SOL statements (de database stored pro provides methods for creating, statements and managing pers. i ints ina transaction: ‘ofaquery 1g when there is a problem accessing data and fon ~ thrown by most method! Gme methods for other reasons. ‘Waring — thrown to indicate a warming. thrown to indicate that data may 7 BatchUUpdateException -- thrown to indicate that nota ‘executed successfully. have been truncated. || commands in a batch update Database (SQL) connection with JDBC: Structured Query Language (SQL) is a standardized language that allows you to perform ‘operations ona database, such as creating entries, reading content, updating content, and deleting en SOL is supported by almost any database you will likely use, database code independently of the underlying database. ‘This chapter gives an overview of ch is a prer pe See rat ee nae , Hela ig rec JDBC concepts. s EES iapter, you be able to Create, Create, Read, Update, ind Delete (often referred to as CRUD operations) data from a database. a and it allows you to write Page No. 24 | Compiled By : Priyal Patel and Rajal Shah .° Transaction Management in JDBC: sents a single unit of work, atic se Setbe the transaction management well. ACID stands for Atomi isolation and durability, Atomicity: m Consistency: consistent stat Tsolati 'eans either all su lecessful of hone, ensu it will remain so, even in if, and when, SQL staten changes are applied to the database, I treats ments as one logical unit, and if any statement ct as follows Otherwise, to roll back upd: z at the following code ot SPAMS 0 the database made Sing the Connection named conn, use conn.rollback( ); 'y Although the JDBCT M API Provides for reading and writ reader/writer facility, availabl customized to us source, ‘mainly geared to passing SQL statements to a database, it ing data from any data source with a tabular format. The ec through the javax.sql. RowSet group of interfaces, can be ind update data from a spread sheet, flat file, or any other tabular data Page No. 23 sigue tin vier > Advantage: + Better performan: «No software is required at clic + Disadvantage: Drivers depend on the Database. ice than all other drivers. ient side or server Page No, 22 « pecific database protocol 1. That is why 2.) SDBC- Part java/part native driver: "art java/part native driver: ‘The Native API Method calls int Sriver uses the client. side libraries of the database. The driver converts 0 native <

You might also like