JavaWebDeveloper Notes

download JavaWebDeveloper Notes

of 19

Transcript of JavaWebDeveloper Notes

  • 8/11/2019 JavaWebDeveloper Notes

    1/19

    Learn Java for Web Development: Modern Java Web Development

    By: Vishal Layka

    Work: architecture, design, and implementation of distributed business systems.

    service-oriented architecture, enterprise application architecture and development.

    Learning the Java programming language is a noble cause, but learning merely theJava language is not enough in the real world.

    Java developers have to learn Java , a collection of related server-sidetechnologies, to put their Java skills to any real use.

    But learning Java is not enough either. !he Java language along with Java

    may suffice to develop web applications for pro"ects in the same organi#ation, as ameans to reusability, but the diverse landscape of Java on the Webispermeated with several web frameworks, such as Spring Web MVC, that makedevelopment much easier$ thus, a Java web developer has to have the knowledge ofthese web frameworks.

    %odern Java &eveloper.

    %odern Java is more than "ust a language$ it is now a fully optimi#ed platformbecause several other languages such as 'roovy and (cala, called theJVM

    languages, now run on the Java Virtual %achine )JV%*.

    +ll such JV% languages, especially 'roovy, have a close association with Java, andyou will come across web applications before long where Java and these other JV%languages work in tandem. !he most ambitious pro"ects will reuire you to buildweb applications using these JV% languages.

    hat we are going to learn is, the specifics of Java on the eb.

    eb rameworks:

    / types0. 1euest based 2 (tricts 3, (pring %V43. 4omponent based 2 J( 35. 1apid - 'rails/. 1eactive

    &ifferent rameworks: five frameworks )6*(tructs 3, (pring eb %V4, J( 3, 'rails 3, 7lay 3 )using (cala*

    %odern Java eb +pplications: 5 players0. JV% Languages

    3. Java 5. Java eb rameworks.

  • 8/11/2019 JavaWebDeveloper Notes

    2/19

    8ntroducing Java eb &evelopment

    !he JV%, originally intended for Java, can now host a myriad of programminglanguages, including 'roovy and (cala.

    !he open source community has capitali#ed on capabilities offered by the languages

    that run on the JV%, by means of web frameworks, to dramatically enhance theproductivity in web development and led to a renaissance of Java web development.

    !his carves out a number of niches in the Java ecosystem, resulting in a richerweb landscapethan ever before.

    !he JV% languages represent a new category of languages that run on the JV%.ith the latest version, Java 9, Java is no longer a privileged JV% language and isnow simply one of the many languages that run on the JV%.

    JV% Languages:

    !he JV% is the runtime environment that provides you the ability to use differentprogramming languages for building web applications.

    3 types:0. Languages designed for the JV% 2 Java, 'roovy, (cala, 4lo"ure, etc3. Languages ported to JV% 2 Jruby, Jphython, etc

    'roovy 2 &ynamically typed language, can be used as a scripting language for theJava platform, dynamically compiled to Java bytecode, and interoperates with otherJava code and libraries. 8t synta; is similar to Java, but more fle;ible.

    Java 2 (tatically typed language, imperative programming.

    (cala 2 full support of functional programming, and a very strong statically typedlanguage. (cale code compiled to byte code to run on JV%.

    4lo"ure 2 purely functional programming language, non-

  • 8/11/2019 JavaWebDeveloper Notes

    3/19

    &ynamic web pages 2 generating content with help of web components.

    eb +pplication 2 collection of web pages and is capable of generating dynamiccontent in response to reuests.

    eb 7age 2 to provide some information.

    eb +pplication 2 to perform an activity and save the result.

    &eveloping eb +pplication:

    0. Java 2 set of +78s that are building blocks of web application.3. eb 4ontainer 2 implements +78 specs of Java . 7rovides services for

    hosting, managing and e;ecuting web components5. eb 4omponents - >osted by the web container. ;amples, servlets, J(7s,

    filters, and listeners, etc.

    Java platform :

    3 goals0. 7roviding +78 specifications for web applications3. (tandardi#ing and reducing the comple;ity of enterprise app development.

    Java provides an application model that defines architecture for implementingservices.

    !ypical +pplication %odel:

    4lient !ier:0. 4onsists of application clients that makes reuests to the Java server.3.

  • 8/11/2019 JavaWebDeveloper Notes

    4/19

    eb !ier:>andles interaction between clients and the business tier.

    0. 4ollects input from the client3. 4ontrols the flow of screens or pages on the client5. %aintains the state of data for a users session/.

  • 8/11/2019 JavaWebDeveloper Notes

    5/19

    Java eb rameworks

    hy going with web framework, inspite of Java providing an application model,and providing components adeuate to develop web applications

    3 problems:

    0. 8nteracting directly with Java components results in lot of boilerplate codeand even code redundancy.

    3. 8ts not a non-trivial task and all team members many not have the level ofe;pertise that meets the Java criteria.

    6 frameworks which we are going to learn:

    (truct 3, (pring %V4, J( 3, 'rails 3)Csing 'roovy*, 7lay 3 )Csing (cala*

    (imple +pplication 2 Book (tore application

    + simple data model that will be used for the bookstore web application.

    0. !he 4ategory table stores the different categories of books$ categories includeJava, (cala, and so on.

    3. !he Book table stores the book details such as titles.

    5. !he +uthor table stores the details of the authors.

    ach category can have #ero or more books. 8n other words, there is a one-to-manyrelationship between the 4ategory and Book tables.

    ach book can have one or more authors. 8n other words, there is a one-to-manyrelationship between the Book and +uthor tables.

    e are going to use %y(DL for our applicaiton.

    !o create the books database, use the following command:

    create database books;

    Eou need to instruct %y(DL to create tables in the books database by using thefollowing command:

    use books;

    CREATE TABLE CATEGORY (

    ID INT NOT NULL AUTO_INCREMENT ,CATEGORY_DECRI!TION "ARC#AR($%& NOT NULL ,!RIMARY 'EY (ID&&;

    CREATE TABLE BOO' (

    ID INT NOT NULL AUTO_INCREMENT,CATEGORY_ID INT NOT NULL ,BOO'_TITLE "ARC#AR(%& NOT NULL,

  • 8/11/2019 JavaWebDeveloper Notes

    6/19

    !UBLI#ER "ARC#AR(%& NOT NULL ,!RIMARY 'EY (ID& ,CONTRAINT )'_BOO'_* )OREIGN 'EY (CATEGORY_ID& RE)ERENCECATEGORY(ID&

    &;

    CREATE TABLE AUT#OR (

    ID INT NOT NULL AUTO_INCREMENT ,BOO'_ID INT NOT NULL ,)IRT_NAME "ARC#AR($%& NOT NULL ,LAT_NAME "ARC#AR($%& NOT NULL ,!RIMARY 'EY (ID& ,CONTRAINT )'_AUT#OR_* )OREIGN 'EY (BOO'_ID& RE)ERENCE BOO' (ID&&;

    Fow populate the tables using the +sertstatements, as follows:

    +sert +to cate-or. (cate-or._descr+/t+o& 0a1ues (2C1o3ure2&;+sert +to cate-or. (cate-or._descr+/t+o& 0a1ues (2Groo0.2&;+sert +to cate-or. (cate-or._descr+/t+o& 0a1ues (24a0a2&;+sert +to cate-or. (cate-or._descr+/t+o& 0a1ues (2ca1a2&;

    +sert +to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues (*,2!ract+ca1 C1o3ure2, 2A/ress2&;

    +sert +to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues ($,2Be-++- Groo0., Gra+1s ad Gr+55o2, 2A/ress2&;

    +sert +to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues ($,2De5++t+0e Gu+de to Gra+1s $2, 2A/ress2&;+sert +to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues ($,2Groo0. ad Gra+1s Rec+/es2, 2A/ress2&;+sert +to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues (6,2Moder 4a0a 7eb De0e1o/8et2, 2A/ress2&;+sert +to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues (6, 24a0a9 Rec+/es2, 2A/ress2&;+sert +to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues (6, 24a0aEE 9 Rec+/es2, 2A/ress2&;+sert +to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues (6,2Be-++- 4a0a 9 2, 2A/ress2&;

    +sert +to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues (6, 2!ro4a0a 9 NIO:$2, 2A/ress2&;+sert +to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues (6, 24a0a9 5or Abso1ute Be-+ers2, 2A/ress2&;+sert +to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues (6,2Orac1e Cert+5+ed 4a0a Eter/r+se Arc+tect 4a0a EE92, 2A/ress2&;+sert +to Book (CATEGORY_ID, BOO'_TITLE, !UBLI#ER& 0a1ues (

  • 8/11/2019 JavaWebDeveloper Notes

    7/19

    2"+sa12, 2La.ka2&;

    +sert +to Autor (BOO'_ID, )IRT_NAME, LAT_NAME& 0a1ues (6, 24e552,2Bro=2&;+sert +to Autor (BOO'_ID, )IRT_NAME, LAT_NAME& 0a1ues (

  • 8/11/2019 JavaWebDeveloper Notes

    8/19

    abstracts the implementation details of accessing the data from the client)application ob"ect* and provides the domain-specific ob"ects that the client)application ob"ect* needs.

    irst (tep:

    irst, you need to create the domain-specific classes for the Java

  • 8/11/2019 JavaWebDeveloper Notes

    9/19

    publicLong getCategoryId() { returncategoryId; }

    publicvoidsetCategoryId(Long categoryId) { this.categoryId= categoryId; }

    publicString getook*itle() { returnbook*itle; }

    publicvoidsetook*itle(String book*itle) { this.book*itle= book*itle; }

    publicList+'&tor, get'&tors() { returna&tors; }

    publicvoidset'&tors(List+'&tor, a&tors) { this.a&tors= a&tors; }

    publicString get&bliser-ame() { returnp&bliser-ame; }

    publicvoidset&bliser-ame(String p&bliser-ame) { this.p&bliser-ame= p&bliser-ame; }

    publicString toString() {

    return"ook Id! " id "# ook *itle! " book*itle; }

    }

    packagecom.apress.books.model;

    publicclass'&tor {privateLong id;

    privateLong bookId; privateString /irst-ame;

    privateString last-ame;publicLong getId() {

    returnid; }

    publicvoidsetId(Long id) { this.id= id; }

    publicLong getookId() { returnbookId; }

    publicvoidsetookId(Long bookId) { this.bookId= bookId; }

  • 8/11/2019 JavaWebDeveloper Notes

    10/19

    publicString get0irst-ame() {

    return/irst-ame; }

    publicvoidset0irst-ame(String /irst-ame) { this./irst-ame= /irst-ame;

    }publicString getLast-ame() {

    returnlast-ame; }

    publicvoidsetLast-ame(String last-ame) { this.last-ame= last-ame; }

    publicString toString() { return"'&tor Id! " id "# ook id! " bookId "# 0irst -ame! " /irst-ame "# Last -ame! "last-ame;

    }

    }

    packagecom.apress.books.dao;

    import$a%a.&til.List;importcom.apress.books.model.ook;importcom.apress.books.model.Category;

    publicinterfaceookD'1 {publicList+ook,/ind'llooks();

    publicList+ook,searcooksy2ey3ord(String key4ord);publicList+Category,/ind'llCategories();publicvoidinsert(ook book);publicvoid&pdate(ook book);publicvoiddelete(Long bookId);

    }

    packagecom.apress.books.dao;

    import$a%a.s5l.Connection;

    import$a%a.s5l.Dri%er6anager;import$a%a.s5l.reparedStatement;import$a%a.s5l.7es&ltSet;import$a%a.s5l.S8L9:ception;import$a%a.&til.'rrayList;import$a%a.&til.List;importcom.apress.books.model.'&tor;importcom.apress.books.model.ook;importcom.apress.books.model.Category;

    publicclassookD'1Impl implementsookD'1 {static{

    try{

    Class.forName("com.mys5l.$dbc.Dri%er");}catch(Class-ot0o&nd9:ception e:) {}

  • 8/11/2019 JavaWebDeveloper Notes

    11/19

    }

    privateConnection getConnection() throwsS8L9:ception {returnDri%er6anager.getConnection("$dbc!mys5l!localostbooks"#

    "rag&"# "cot&");}

    privatevoidcloseConnection(Connection connection) {if(connection == null)return;

    try{connection.close();

    }catch(S8L9:ception e:) {

    }}

    publicList+ook, /ind'llooks() {List+ook, res&lt = new'rrayList+,();

    List+'&tor, a&torList = new'rrayList+,();String s5l = "select ? /rom book inner $oin a&tor on book.id=

    a&tor.book@id";Connection connection = null;try{

    connection = getConnection();reparedStatement statement =

    connection.prepareStatement(s5l);7es&ltSet res&ltSet = statement.e:ec&te8&ery();while(res&ltSet.ne:t()) {

    ook book = newook();'&tor a&tor = new'&tor();book.setId(res&ltSet.getLong("id"));

    book.setook*itle(res&ltSet.getString("book@title"));book.setCategoryId(res&ltSet.getLong("category@id"));a&tor.setookId(res&ltSet.getLong("book@Id"));a&tor.set0irst-ame(res&ltSet.getString("/irst@name"));a&tor.setLast-ame(res&ltSet.getString("last@name"));a&torList.add(a&tor);book.set'&tors(a&torList);book.set&bliser-ame(res&ltSet.getString("p&bliser"));res&lt.add(book);

    }} catch(S8L9:ception e:) {

    e:.printStack*race();} finally{

    closeConnection(connection);}returnres!!7. eb browser)client*, eb server)server* and web applicationall converse with each other using >!!7 protocol.

    >!!7 1euests and >!!7 1esponses.

    >!!7 is a reuest-response stateless protocol. eb servers view, any reuest is thefirst reuest from the web browser.

    C1L 2 Cniform 1esource Locator 2 uniform way of uniuely identifying a resource. H---= locating a resource by describing its location on a network.

    + generic C1L is a hierarchical seuence of components, structured asscheme:??hostFame:portFumber?path?resourceueryIstring.

    (cheme : http ? https

    !he host name and port number together are termed an authority.

    >ttp 2 default port 9A

    https 2 default port //5

    !omcat web server listens for incoming reuests on port 9A9A.

    hen present, a uery string is a series of name-value pairs preceded with auestion mark )* and with an ampersand )* separating the pairs.

    Duery strings are supported only for the '! method.

    + web application is a collection of web components that work together. 8n Java ,a web component is either a (ervlet or a J(7.

    eb components are managed and e;ecuted inside the web container, also called aservlet container, which provides additional features such as security.

  • 8/11/2019 JavaWebDeveloper Notes

    16/19

    eb server forwards reuest to the servlet container in which web componentresides.

    eb browser -= web server -= servlet container -= servlet

    +ll reuests for the dynamic content are mediated by the servlet container.

    + (ervlet is a "ava class that acts as a dynamic web resource.

    (ervlets

    (ervlets are responsible for most of the processing reuired by a web application.

    + servlet is a "ava class that implements "ava;.servlet.(ervlet interface. !he (ervletinterface defines the methods that all servlets must implement.

    Life cycle methods: init)* - to initiali#e a servlet

    service)* - to service reuests

    destroy)* - to remove a servlet from the server

    void init(Servlet#onfig config)

    void service(Servlet%e&uest re&, Servlet%esponse res)

    void 'estro()

    init(Servlet#onfig): #alled b the servlet container exactly once after instantiating the

    servlet. This method must complete successfull before the servlet is a candidate to receive

    an re&uests.

    service(): #alled b the servlet container, after the servlets init() method has completed

    successfull, to allow the servlet to respond to a re&uest.

    destro(): #alled b the container to destro the servlet and serves as a method in which the

    servlet must release ac&uired resources before it is destroed.

    getServlet#onfig(): llows the servlet to get start*up information in the form of a

    Servlet#onfig ob!ect returned b this method. The Servlet#onfig ob!ect containsinitiali+ation and start*up parameters for the servlet.

    getServlet$nfo(): llows the servlet to return its own information such as the servlets author

    and version.

    1euest low for the >elloorld (ervlet

    !he reuest originating from the web browser flows through the web server and theservlet container before the >elloorld servlet can generate the response.

    eb browser -= web server -= servlet container -= your servlet

    >!!7 1euest %essage:

    hen user access the web application through this C1L, web browser creates >!!71euest.

  • 8/11/2019 JavaWebDeveloper Notes

    17/19

    '! ?helloworld?hello >!!7?0.0>ost: localhost:9A9ACser-+gent: %o#illa?6.A )indows F! K.0* +ppleebit?65M.50 )>!%L, like 'ecko*4hrome?3K.A.0/0A./5 (afari?65M.50

    web browser -= reuest )say '! reuest* -= web server -= sees the resource path

    in reuest.

    8f the resource reuested by the user is not a static page, so forwards reuest toweb container.

    !omcat is both web server N web container.

    1esource path in C1L to (ervlet mapping is through web.;ml file. )&eployment&escriptor file*

    !he Oservlet= tag is used to configure our servlet. 8t contains two nested tags:

    Oservlet-name= defines a logical name for the servlet, and Oservlet-class=indicates the Java class defining the servlet.

    Oservlet=Oservlet-name=Oservlet-class=O?servlet=

    !he Oservlet-mapping= @%L tag is used to configure our servlet. 8t contains twonested tags: Oservlet-name= matches the value set in the Oservlet= tag, and Ourl-pattern= sets the C1L pattern for which the servlet will e;ecute.

    Oservlet-mapping=Oservlet-name=Ourl-pattern=O?servlet-mapping=

    one instance of servlet per JV%one JV% 2 one servlet instance only.

    Java web applications run from within a conte;t root.!he conte;t root is the first string in the C1L after the server name and port.

    !he value for Ourl-pattern= is relative to the applicationPs conte;t root.!he web container loads the servlet class and instantiates it. very client reuestgenerates a new pair of reuest and response ob"ects.

    !he web container runs multiple threads to process multiple reuests to a singleinstance of the servlet.

    + servlet has to e;ecute inside the web container.

    +n >!!7 reuest to an >ttp(ervlet subclass goes through a number of steps:

    . call to the public service (Servlet%e&uest, Servlet%esponse) method b the container.

    -. 'elegation of this call to ttpServlets protected service (ttpServlet%e&uest,

  • 8/11/2019 JavaWebDeveloper Notes

    18/19

    ttpServlet%esponse) method.

    /. The protected service (ttpServlet%e&uest, ttpServlet%esponse) method then delegates to

    the appropriate do011 method, depending on the TT2 method used for the re&uest.

    !he 'eneric(ervlet abstract class defines an init)* method that is called by the

    default init)(ervlet4onfig* method to e;ecute any application-specific servletinitiali#ation.

    !he service)* method is implemented by >ttp(ervlet, which inspects the incoming>!!7 method and invokes the appropriate method for that reuest type.

    !he init)(ervlet4onfig* method calls the no-arg init)*, so you need to override onlythe no-arg version.

    init) *

    !he container calls init)*on the servlet instance. Eou can override it in order to getdatabase connections registered with other ob"ects.

  • 8/11/2019 JavaWebDeveloper Notes

    19/19