Java with Web applications - PowerPoint PPT Presentation

1 / 59
About This Presentation
Title:

Java with Web applications

Description:

Initially, the cursor is positioned before the first row. ... This method moves the cursor to the next record and ... cursors for currently open resultsets. ... – PowerPoint PPT presentation

Number of Views:47
Avg rating:3.0/5.0
Slides: 60
Provided by: thanapolw
Category:

less

Transcript and Presenter's Notes

Title: Java with Web applications


1
Java with Web applications
2
Servlet
3
What is Servlet?
  • A servlet more closely resembles a CGI (Common
    Gateway Interface) script. Like a CGI script, a
    servlet can respond to user input -- such as the
    clicking of a button on a form -- and can either
    collect information from the user or send
    information back to the user (or both), depending
    upon what kinds of actions are initiated by the
    form the user fills out.
  • Servlets are not the only mechanism that can
    interact in this way with a user. CGI scripts can
    perform similar operations -- and indeed, until
    servlets came along, CGI scripts were the
    standard mechanism for creating and displaying
    HTML pages dynamically. But servlets have many
    advantages over CGI scripts, and are quickly
    replacing them in the world of enterprise
    computing.

4
Creating a Servlet
  • To create a servlet, you must write a program
    that implements the javax.servlet.Servlet
    interface. Most servlets implement this interface
    by extending either the javax.servlet.GenericServl
    et class, which is implemented in the
    javax.servlet package, or the javax.servlet.http.H
    ttpServlet class, which provides extra
    functionality needed by HTTP servlets and is
    implemented in the javax.servlet.http package.
    Almost all servlets written today are designed to
    use the HTTP protocol, so most servlets currently
    extend the javax.servlet.http.HttpServlet class.

5
How servlet work?
6
Invoking a Servlet(1)
  • Invoking a servlet from an HTML page
  • A link
  • Submit form.
  • Typing its pathname into the Address bar of a
    browser.
  • The Java Servlet API provides a number of methods
    that servlets can (and do) override.
  • init() (Servlets, like applets, are always
    equipped with an init() method rather than a
    main() method).
  • doGet() retrieves data in response to GET actions
    embedded in a form
  • doPost() posts data in response to POST requests.
  • doPut() posts file on the server and is similar
    to sending a file by FTP.
  • doDelete() remove a document or Web page from the
    server.

7
Invoking a Servlet(2)
  • When a user invokes a servlet by clicking a
    button or using some other mechanism that
    activates a link to the servlet, the Web server
    that is hosting the user's browser session tracks
    down the servlet by looking in a special
    directory. The name of this directory can vary,
    depending on the Web server or application server
    being used. But no matter what the actual
    pathname of the directory is, an HTML page that
    invokes a servlet can always use the /servlet
    alias to find the servlet it's looking for. For
    instance, the HTML code
  • ltFORM METHODGET ACTION"/servlet/HelloWorld"gt

8
Using a servlet
  • A user (1) requests some information
  • by filling out a form containing a
  • link to a servlet and clicking the
  • Submit button (2)
  • The server (3) locates the requested
  • servlet (4). The servlet then gathers the
    information needed to satisfy the user's request
    and constructs a Web page (5) containing the
    information. That Web page is then displayed on
    the user's browser (6).

9
How to use servlet with tomcat
  • Install apache tomcat
  • Compile your servlet
  • Copy your package folder to TOMCAT_HOME/webapps/
    yourapps/WEB-INF/classes
  • Mapping your servlet with url in
    TOMCAT_HOME/webapps/yourapps/WEB-INF/web.xml
  • Servlet name ShowServlet
  • Servlet class Test.ShowParameters
  • URL /servlet/showparams.do
  • Restart tomcat

10
Servlet vs. CGI
  • Efficient With traditional CGI, a new process is
    started for each HTTP request. If the CGI program
    does a relatively fast operation, the overhead of
    starting the process can dominate the execution
    time. With servlets, the Java Virtual Machine
    stays up, and each request is handled by a
    lightweight Java thread, not a heavyweight
    operating system process. Servlets also have more
    alternatives than do regular CGI programs for
    optimizations such as caching previous
    computations, keeping database connections open,
    and the like.
  • Convenient Besides the convenience of being able
    to use a familiar language, servlets have an
    extensive infrastructure for automatically
    parsing and decoding HTML form data, reading and
    setting HTTP headers, handling cookies, tracking
    sessions, and many other such tasks.

11
  • Powerful Java servlets let you easily do several
    things that are difficult or impossible with
    regular CGI. For one thing, servlets can talk
    directly to the Web server (regular CGI programs
    can't). This simplifies operations that need to
    look up images and other data stored in standard
    places. Servlets can also share data among each
    other, making useful things like database
    connection pools easy to implement. They can also
    maintain information from request to request,
    simplifying things like session tracking and
    caching of previous computations.
  • Portable Servlets are written in Java and follow
    a well-standardized API. Consequently, servlets
    written for, say Apache Server can run virtually
    unchanged on Microsoft IIS, or WebSphere.
    Servlets are supported directly or via a plugin
    on almost every major Web server.

12
  • Inexpensive There are a number of free or very
    inexpensive Web servers available that are good
    for "personal" use or low-volume Web sites. But
    with the major exception of Apache, which is
    free, most commercial-quality Web servers are
    relatively expensive. But once you have a Web
    server, no matter the cost of that server, adding
    servlet support to it (if it doesn't come
    preconfigured to support servlets) is usually
    cheap or even free.

13
Example
  • Save in HelloWorld.java
  • Map servlet with name hello
  • Call servlet by /servlet/hello

14
  • Test GET method
  • Test POST method by HTML

15
Workshop
  • Create your own servlet to query data from
    database.
  • Input ID
  • Output

16
Java Server Page(JSP)
17
Definition
  • A Java Server Page is an HTML document thats
    saved in a file with the extension .jsp instead
    of .htm or .html. Unlike servlet class files, you
    can store a JSP file in any directory thats
    available to the Web server
  • JSPs are built on top of Servlet technology. JSPs
    are essential an HTML page with special JSP tags
    embedded. 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 why the JSP is
    probably slower the first time it is accessed.
    Any time after this the special compiled servlet
    is executed and is therefore returns faster.

18
JSP Advantage
  • JSP vs. Active Server Pages (ASP) ASP is a
    similar technology from Microsoft. The advantages
    of JSP are twofold. First, the dynamic part is
    written in Java, so it is more powerful and
    easier to use. Second, it is portable to other
    operating systems and non-Microsoft Web servers.
  • JSP vs. Pure Servlets JSP is more convenient to
    write (and to modify!) regular HTML than to have
    a println statements that generate the HTML.
    Plus, by separating the look from the content you
    can put different people on different tasks your
    Web page design experts can build the HTML,
    leaving places for your servlet programmers to
    insert the dynamic content.

19
  • JSP vs. Server-Side Includes (SSI) SSI is a
    widely-supported technology for including
    externally-defined pieces into a static Web page.
    JSP is better because it lets you use servlets
    instead of a separate program to generate that
    dynamic part. Besides, SSI is really only
    intended for simple inclusions, not for "real"
    programs that use form data, make database
    connections.
  • JSP vs. JavaScript JavaScript can generate HTML
    dynamically on the client. This is a useful
    capability, but only handles situations where the
    dynamic information is based on the client's
    environment. With the exception of cookies, HTTP
    and form submission data is not available to
    JavaScript. And, since it runs on the client,
    JavaScript can't access server-side resources
    like databases, catalogs, pricing information.

20
How JSP Work?
21
Example
  • HTML JSP

22
Types of JSP elements
  • Directives A directive is an option setting that
    affects how the servlet is constructed from a JSP
    page. Directives let you do things such as
    specify what import statements the servlet
    requires, specify whether the servlet is
    thread-safe, and include other source files in
    the servlet.
  • lt_at_ page attributevalue gt
  • Expressions An expression can be any Java
    expression. The expression is evaluated,
    converted to a string (if necessary) and the
    result is inserted into the document. Expressions
    assume the following form
  • lt expression gt

23
  • Scriptlets A scriptlet is a sequence of Java
    statements that are inserted directly into the
    servlet code generated for the JSP. You can do
    just about anything you want in a scriptlet,
    including if statements, looping, and calling
    other methods. You can even use out.println to
    add output to the page the output is inserted in
    the page at the location where the scriptlet
    appears. Scriptlets have the following form
    lt statements gt
  • Declarations A declaration is Java code that is
    placed in the servlet class outside of any
    methods. You use declarations to create class
    variables or define methods that can be called by
    scriptlets or expressions. Declarations take on
    this form lt! statements gt

24
Expressions
25
Scriptlets
26
Simple Debugging
In Server Log
27
  • If you run the above example, you will notice the
    output from the "System.out.println" on the
    server log.  This is a convenient way to do
    simple debugging (some servers also have
    techniques of debugging the JSP in the IDE.  See
    your server's documentation to see if it offers
    such a technique.)
  • Here, instead of using an expression, we are
    generating the HTML directly by printing to the
    "out" variable.  The "out" variable is of type
    javax.servlet.jsp.JspWriter. Another very useful
    pre-defined variable is "request".  It is of type
    javax.servlet.http.HttpServletRequest

28
  • A "request" in server-side processing refers to
    the transaction between a browser and the
    server.  When someone clicks or enters a URL, the
    browser sends a "request" to the server for that
    URL, and shows the data returned.  As a part of
    this "request", various data is available,
    including the file the browser wants from the
    server, and if the request is coming from
    pressing a SUBMIT button, the information the
    user has entered in the form fields.
  • The JSP "request" variable is used to obtain
    information from the request as sent by the
    browser.  For instance, you can find out the name
    of the client's host (if available, otherwise the
    IP address will be returned.)

29
Directives
  • We have been fully qualifying the java.util.Date
    in the previous examples.
  • Why we don't just import java.util.

30
Page directive
  • The page directive can contain the list of all
    imported packages.  To import more than one item,
    separate the package names by commas, e.g.
  • lt_at_ page import"java.util.,java.text." gt

31
Page directive options
32
Include directive
  • The include directive is used to physically
    include the contents of another file.  The
    included file can be HTML or JSP or anything else
    -- the result is as if the original JSP file
    actually contained the included text. 

33
Declarations
  • The JSP you write turns into a class definition. 
    All the scriptlets you write are placed inside a
    single method of this class. You can also add
    variable and method declarations to this class. 
    You can then use these variables and methods from
    your scriptlets and expressions.
  • To add a declaration, you must use the lt! and gt
    sequences to enclose your declarations

34
Example
35
JSP Tags
  • Tags can be of two types loaded from an external
    tag library, or predefined tags.   Predefined
    tags start with jsp characters. 
  • ltjsp tag .. /gt
  • ltjspinclude page"hello.jsp"/gt
  • ltjspforward page"hello.jsp"/gt

36
JSP Session
  • A session is an object associated with a
    visitor.  Data can be put in the session and
    retrieved from it, much like a Hash table.  A
    different set of data is kept for each visitor to
    the site.
  • The variable  "session".  This is another
    variable that is normally made available in JSPs,
    just like out and request variables. 

37
Example
  • testsession.jsp
  • Nextpage.jsp

38
Workshop
  • Create your own JSP to query data from database.
  • Input ID
  • Output

39
Beans and Form processing
  • If you bring up two different browsers (not
    different windows of the same browser), or run
    two browsers from two different machines, you can
    put one name in one browser and another name in
    another browser, and both names will be kept
    track of. The session is kept around until a
    timeout period.  Then it is assumed the user is
    no longer visiting the site, and the session is
    discarded.
  • Forms are a very common method of interactions in
    web sites.  JSP makes forms processing specially
    easy. The standard way of handling forms in JSP
    is to define a "bean".  This is not a full Java
    bean.  You just need to define a class that has a
    field corresponding to each field in the form. 
    The class fields must have "setters" that match
    the names of the form fields.

40
Using Beans with JSP
41
Creating bean instances
  • ltjspuseBean idname classpackage.Class /gt
  • The jspuseBean tag can appear anywhere in the
    JSP document, but it must appear before any other
    tag that refers to the bean.
  • This and all bean tags are case sensitive, so be
    sure to code them exactly as shown.
    ltjspusebean.../gt wont work.
  • If Tomcat complains that it cant find your bean
    when you run the JSP, double-check the package
    and class name theyre case sensitive too and
    make sure the bean is stored in a directory under
    WEB-INF\classes thats named the same as the
    package. For example, store the Triangle beans
    class file in WEB-INF\classes\calculators.

42
Creating bean instances
  • The jspuseBean element can have a body that
    contains jspsetProperty tags that initialize
    property values. Then, the element is formed more
    like normal HTML, with proper start and end tags.
    For example
  • ltjspuseBean idt1 classcalculators.Triangle
    gt
  • ltjspsetProperty namet1 propertysideA
    value3.0 gt
  • ltjspsetProperty namet1 propertysideB
    value3.0 gt
  • lt/jspuseBeangt
  • Dont worry about the details of the
    jspsetProperty tags just yet. Instead, just make
    a note that theyre executed only if a new
    instance of the bean is actually created by the
    jspuseBean tag. If an instance of the bean
    already exists, the jspsetProperty tags are not
    executed.
  • The jspuseBean tag also has a scope attribute,
    which I explain later in this chapter, in the
    section Scoping Your Beans.

43
Getting property values
  • ltjspgetProperty namename propertyproperty
    /gt
  • ltinput typetext namesideA
    valueltjspgetProperty nametriangle
    propertysideA /gt gt

44
Setting property values
  • ltjspsetProperty nametriangle propertysideA
    value4.0 /gt
  • ltjspsetProperty nametriangle property /gt
  • The asterisk () in the property attribute
    indicates that all properties that have names
    identical to form fields (or query string
    parameters) are automatically assigned. For forms
    that have a lot of fields, this form of the
    jspsetProperty tag can save you a lot of coding.

45
Beans scopes
  • page
  • valid until page completes.
  • request
  • bean instance lasts for the client request
  • session
  • bean lasts for the client session.
  • application
  • bean instance created and lasts until
    application ends.

46
Scoping Your Beans
47
JSP with Beans
  • Contain all classes in packages. Choose a nice
    package name for your application, and then add a
    package statement to the beginning of each class
    file.
  • Store the class files (not necessarily the source
    files) in the WEB-INF\classes\package\ directory
    beneath the directory the JSP pages are stored
    in. For example, if youre storing your JSP pages
    in c\tomcat\webapps\ROOT\Movies and the package
    name youre using is movie, save the class files
    in the following directory
  • C\tomcat\webapps\ROOT\Movies\WEB-INF\classes\mo
    vie
  • If you prefer, you can save your class files in
    c\tomcat\shared\classes\package, where package
    is the name of your package. Then, the classes
    are available to any JSP or servlet.

48
  • Any JSP that uses one of your classes has to
    include a page directive that imports the
    package. For example
  • lt_at_ page importmovie. gt
  • Add the directory you saved the packages in to
    your ClassPath environment variable. Note that
    you want to add the directory that contains the
    packages, not the directory that contains the
    classes themselves. Thats because the Java
    compiler uses the package name to find the
    package directory. So, if you put your classes in
    the shared\classes directory, you need to add
    c\tomcat\shared\classes to your ClassPath.

49
Example(1)
  • getname.html html form
  • testbean.jsp jsp set values to bean

50
Example(2)
  • NextPageUseBean.jsp get values form bean

51
JSP with DB
  • Declaring Variables
  • Connection to database
  • Executing Query/Access data from DB
  • Reading value from ResultSet
  • Close connection

52
Setup database
  • Start MYSQL prompt and type this SQL statement
    press Enter
  •                                 MYSQLgtCREATE
    DATABASE books
  • This will create "books" database.Now we create
    table a table "books_details" in database
    "books".                                
    MYSQLgtCREATE TABLE books_details
    (                                               
    id INT( 11 ) NOT NULL AUTO_INCREMENT
    ,                                               
    book_name VARCHAR( 100 ) NOT NULL
    ,                                              
    author VARCHAR( 100 ) NOT NULL
    ,                                               
    PRIMARY KEY ( id )                             
                        ) TYPE MYISAM This will
    create a table "books_details" in database
    "books"

53
Declaring Variables
  • testdb.jsp
  • Java is a strongly typed language which means,
    that variables must be explicitly declared before
    use and must be declared with the correct data
    types. In the above example code we declare some
    variables for making connection. Theses variables
    are
  • Connection connullResultSet
    rsnullStatement stnull

54
  • The objects of type Connection, ResultSet and
    Statement are associated with the Java sql. "con"
    is a Connection type object variable that will
    hold Connection type object. "rs" is a ResultSet
    type object variable that will hold a result set
    returned by a database query. "stmt" is a object
    variable of Statement .Statement Class methods
    allow to execute any query.  

55
Connection to database
  • The first task of this programmer is to load
    database driver. This is achieved using the
    single line of code -
  • String driver "org.gjt.mm.mysql.Driver"Class.
    forName(driver).newInstance()
  • String url"jdbcmysql//127.0.0.1/books?userltuse
    rNamegtpasswordltpasswordgt"conDriverManager.get
    Connection(url)
  • When url is passed into getConnection() method of
    DriverManager class it  returns connection object.

56
Executing Query from DB
  • stmtcon.createStatement() //create a Statement
    object rsstmt.executeQuery("select from
    books_details")
  • The two most important methods of this Statement
    interface are executeQuery() and executeUpdate().
    The executeQuery() method executes an SQL
    statement that returns a single ResultSet object.
    The executeUpdate() method executes an insert,
    update, and delete SQL statement. The method
    returns the number of records affected by the SQL
    statement execution.

57
Reading values from a ResultSet
  • while(rst.next())   gt        
    lttrgtlttdgtltnogtlt/tdgtlttdgtltrst.getString("book_nam
    e")gtlt/tdgtlttdgtltrst.getString("author")gtlt/tdgtlt/t
    rgt  lt 
  • The ResultSet  represents a table-like database
    result set. A ResultSet object maintains a cursor
    pointing to its current row of data.

58
  • Initially, the cursor is positioned before the
    first row. Therefore, to access the first row in
    the ResultSet, you use the next() method. This
    method moves the cursor to the next record and
    returns true if the next row is valid, and false
    if there are no more records in the ResultSet
    object.
  • Other important methods are getXXX() methods,
    where XXX is the data type returned by the method
    at the specified index, including String, long,
    and int. The indexing used is 1-based.

59
  • You can also use the getXXX() methods that accept
    a column name instead of a column index. For
    instance, the following code retrieves the value
    of the column LastName of type String.
  • In the case of connections to remote database
    servers, further resources are tied up on the
    server, eg. cursors for currently open
    resultsets. It is vital to close() any JDBC
    object as soon as it has played its part

60
Close connection
  • rs.close()
  • stmt.close()
  • con.close()

61
Workshop
  • Use Connection Bean name Test.MySQLConnection
  • Create JSP with Bean to
  • Query
  • Insert
  • Update
  • Delete
Write a Comment
User Comments (0)
About PowerShow.com