Docstoc

JSP TUTORIAL

Document Sample
JSP TUTORIAL Powered By Docstoc
					                                 Java Server Pages




                    Java Server Pages

                               Documentation By
                             C.Veera Sekhar Reddy




Documentation By C.Veera Sekhar Reddy                Page 1
                                 Java Server Pages

Introduction to jsp:
    Jsp is a java server pages technology
    Jsp technology used for developing web based applications for
     generating dynamic webcontent
     Def WebContainer:
                There are so many server vendors are there for running
     servlets and jsp’s. those servers are called web container.
     Ex:Tomcat,Weblogic

      Note:As part of webcontainer, we will hava servlet container
      and jspcontainer.
      ServletContainer:
                         Is responsible for create object for servlet &
      executed.
      Jsp Container:
                     Is responsible to invoke (OR) to call jsp compiler
      & Generate the Servlet Program

      One.jsp

      jspcompiler

      One.java

        Javac

      One.class



Documentation By C.Veera Sekhar Reddy                               Page 2
                                 Java Server Pages

      Advantages of Jsp:
        1. With jsp, we can simplify development process (i.e. it take
           less time)
        2. Jsp provide the better mechanism of separating
           presentation logic from Business Logic
        3. By using jsp’s, without writing any java code we will be able
           to develop the servlet program.

          Note: jsp gives less performance than Servelt, but comfortable.

          Every server vendor uses their own servlet classs for creating
          server program.

          Ex:

          In Case of Tomat, it uses HttpJspBase class.

          In case of Weblogic , it uses JspBase class.

Example program:

        This is first line of jsp program//           Template Text
        <%
        System.out.println(“sekhar”);                 Scriptlet
        %>
        This is last line of jsp program             Template Text




Documentation By C.Veera Sekhar Reddy                                 Page 3
                                 Java Server Pages

What is Scriptlet?

 If any java developer wants to write the java code inside the jsp, we
can use Scriptlet.

Syntax: <% ………………                         java code

             …………………….

          %>

Note: When ever the jsp complier encounters the scriptlet it translate
the code ,which is available inside servlet _jspService method.

What is Templet Text?

Any text that is not available inside scriptlet is called Template text.

Implicit Variables:

<%
Int a=10;// here a is variable
System.out.println(a);
System.out.println(a+b);//a,b are variable
out.println(a);//out is variable.
%>


When u run above code it gives error.because the variable b can not be
initialized.

Here out is also variable, but it not gives error because out is implicit
variable



Documentation By C.Veera Sekhar Reddy                                  Page 4
                                 Java Server Pages

i.e. A variable that can be used in the scriptlet without declaring is
called implicit variable .

like out variable, there are 9 implicit variables available inside jsp

there are

      1.   HttpServletRequest request
      2.   HttpServletResponse response
      3.   ServletConfig config
      4.   ServletContext application
      5.   HttpSession session
      6.   Object page
      7.   PageContext Pagecontext
      8.   JspWriter out
      9.   Exception exception

These implicit variables are called local variable inside jspService()
method.

HttpServletRequest request:

can be used to access the httprequest data.

It uses the getParameter() method to access the request parameters
values.




Documentation By C.Veera Sekhar Reddy                                    Page 5
                                     Java Server Pages

Ex:

GetForm1.jsp

 Username:                                 Uname is property for this field


  Password:                                 pwd is propery for this field
                    Button




 Getting the values from above jsp using request object

String username=request.getparameter(uname);

String pwd=request.getparameter(pwd);

HttpServletResponse response:

can be used to send the output to the client on the browser.

Ex:
        <%

        Try {

        Java.io.FileInputStrem fis=new java.io.FileInputStream(“test.jsp”);

        }

        Catch(Exception e) {

        Response.sendError(505,”fileNotFoundException is occuredin server”);

        }

        %>




Documentation By C.Veera Sekhar Reddy                                          Page 6
                                           Java Server Pages

     ServletConfig config:

            config object allows to pass the initialization data to a jsp pages
     servlet.

     The method getInitParameter() is used to acess the initialization
     parameters.

     Ex:

     if we want pass the initialization

     Web.xml


<web-app>

<servlet>

<servlet-name>first</servlet-name>

<servet-class>/WEB-INF/classes/Test.jsp</servlet-class>

<init-param>                                              These values will be available to this test.jsp
                                                          file only.if u want share these values for
<param-name>user</param-name>                             entire application we can place these values
<param-value>Veerasekhar</param-value>                    in context param attributes.here we can use
                                                          context for object for retrieving values.
</init-param>

<servlet>

<servlet-mapping>

<servlet-name>first</servlet-name>

<url-pattern>/test</url-pattern>

<servlet-mapping>

</web-app>




     Documentation By C.Veera Sekhar Reddy                                                         Page 7
                                    Java Server Pages

Using config we can retrieve the values from xml file
           String name=config.getInitParameter(user);

           //it retrieve user value from init-param attribute.



Exception exception: this object allows the exception data to the jsp’s

ServletContext application :

this object allows to share the same same information between the jsp
pages servlet.

By using servletcontext object we can find the information about
server,where our application is running.

Ex:

      <%

      Out.print<application.getServerInfo());//it display Apache Tomcat/6.0.14

      <%>

      Like wise <%

      Out.print(application.getMajorVersion()+”<br>”+// it display 2

               Application.getMinorVersion());// it display 5. %>




Documentation By C.Veera Sekhar Reddy                                            Page 8
                                    Java Server Pages

pageContext pagecontext:

pagecontext has a page scope.

Pagecontext also provides access to several page attributes like
including some static or dynamic resources.

HttpSession session:this object provide information across multiple
user connection.

Object page:page object represents the current page that is used to call
the methods defined by the translate servlet class.

Page variable holds the curret object

The current object means the servlet object which is being getting
executed.

Ex:one.jsp       <%

                 out.print(page.getClass());// it display   class org.apache.jsp.one_jsp
                 %>




JSPWriter Out:It provide the outputstream to the browser

IMP Note: all these objects can be used in scriptlet tag and expression

Tag




Documentation By C.Veera Sekhar Reddy                                                      Page 9
                                          Java Server Pages

Chapter 2:
Jsp composed of only jsp elements
Those elements are
        Template text
        Scriptlet                            these are scripting
        Jsp expression                       elements
        Jsp declaration
        Jsp directive                         Directive tags
        Jsp action tags
        Jsp custom tags                             these are action
        El expression tag                             tags
Declarations: we can use the declarations to provide instance variable,
static variables and methods
Syntax:                         <%!
                                     // instance variables &static
                      variables
                                         // instance methods &static
                      methods
Ex:one .jsp                         %>

<%! Int a;

Static int b;

Public void mthodOne() {

System.out.println(“we r in method one()”);

}

Public static void method two() {

System.out.println(“we r in method two()”);
 Documentation By C.Veera Sekhar Reddy                                  Page 10
}

}
                                       Java Server Pages

      When the above jsp converted into the appropriate servlet ,the
      jsp compiler placethe contents inside the class directly.
      The following is the example of generated servlet program


         Public class org.apache.jsp.one_jsp extends HttpJspBase {
         Int a;

         Static int b;

         Public void mthodOne() {

         System.out.println(“we r in method one()”);

         }

         Public static void method two() {

         System.out.println(“we r in method two()”);

         }

         }

         Public void service (………………………………..) {

         PageContext pageContext = null;

             HttpSession session = null;

             JspWriter out = null;

              PageContext _jspx_page_context = null;

         …………………………………………

         ……………………………………..

         }

         }




Documentation By C.Veera Sekhar Reddy                                Page 11
                                            Java Server Pages

How will you call our methods that are written in declaration part:

There is one possible to call the methods from service ie.

We can write the methods inside scriptlet only

<% methodone(); it will place the code

Methodtwo();                inside jsp service method()

%> i.e
                Public class org.apache.jsp.one_jsp extends HttpJspBase {

                Int a;

                Static int b;

                Public void mthodOne() {

                System.out.println(“we r in method one()”);

                }

                Public static void method two() {

                System.out.println(“we r in method two()”);
                } }

                Public void service (………………………………..) {
                PageContext pageContext = null;

                    JspWriter out = null;

                      PageContext _jspx_page_context = null;

                …………………………………………

                ……………………………………..

                methodone();

                methodtwo(); }

                }




Documentation By C.Veera Sekhar Reddy                                       Page 12
                                    Java Server Pages

Expression tag:

This tag used to give some java expression(one expression within one
tag)

The expression given in this expression tag is evaluated and then
printed on the browser.

Syntax:
                          <%=expression%>

Note:

      The Expression tag should not end with semicolon(;).

Ex:

                     <% java .util.Date date=new java.util.Date();

                     %>

                     The following code used to display the date to
                     browser

                     <%=date%>




Documentation By C.Veera Sekhar Reddy                                 Page 13
                                 Java Server Pages

JSP DIRECTIVE TAGS;
A JSP directive is an instruction given by the developer to the jsp compiler

If u provide any scripting language as part of jsp scriptlet ,it is
responsible of the jsp compiler to translate the scripting language
code to java code

If u provide vbscript or javascript in the jsp file we need to give
instructions to the jsp compiler saying that the code available is java
script or vbscript

So to give the instruction we use jsp dicrective.

The followings are examples for jsp directive tag

                1. <%@ page language=”javascript” %>
                2. <%@ page import=”java.util.*” %>
                3. <%@ page session=”false” %> default value is true




                    Attribute name           attribute value

DIRECTIVE ATTRIBUTES ARE

    language
    extends
    session           we can use this attribute to make session
     object unavailable to the jsp
    import           is used to import the packages inside jsp file
    info            <%@ page info=”we are in jdbc programjsp file” %>
    autoFlush



Documentation By C.Veera Sekhar Reddy                                          Page 14
                                  Java Server Pages

    buffer       take the buffer size like 8kb,16kb,32kb and 0 kb
     also
    isThreadSafe
    errorPage
    isErrorPage
    contentType

Concept of JavaBean;

What is java bean?

      A java bean is a simple java program .which consit of set of
setter methods and getter methods.

Java software release the java bean specification to develop the
javabeans.

If a developer wants developa java bean he has to follow the rules
which are available in the specification(documentation)

Rule 1.

Every java bean class needs have the default constructor or zero
argument constructor.
            Class MyApp {

            Public MyApp () { }

            }



the above java program can be called as a java bean.

Because the program consist of default constructor.


Documentation By C.Veera Sekhar Reddy                                Page 15
                                     Java Server Pages



Rule 2.

    Every class should be placed inside package
               Package info.inetsolv

               Class MyApp {
.
               Public MyApp () { }

               }

Rule 3

   A java bean consist of a set of properties & set of events,some
additional methods

           //properties

           // events

           //additional methods




Documentation By C.Veera Sekhar Reddy                            Page 16
                                 Java Server Pages



Ex for java bean:


          Package info.inetsolv;
          Public class Student {
          String name;
          Boolean male;
          Public void setName(String name) {
          This.name=name; }
          Public void setMale(Boolean male) {
          This.male=male; }
          Public void getName() {
          Return name; }
          Public void getMale() {
          Return male; } }




Advantage of java bean

 1.To separate the business logic and presentation logic

2.completely remove java code



Documentation By C.Veera Sekhar Reddy                      Page 17
                                 Java Server Pages



working on java beans:

productJB.java:

  package info.inetsolv;

import java.sql.*;

public class ProductJB {

private String prouductId;

private String ProductName;

private String ProductPrice;

//setter methods and getter methods

Public void storeProduct() throws SQLException {

DriverManager.registerDriver(new oracle.jdbc.driver.OralceDriver());

Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521
:XE","res","res");

String query="insert into product values(?,?,?)";

PreparedStatement ps=con.prepareStatement(query);

ps.setString(1,productId);

ps.setString(2,productName);

ps.setString(3,ProductPrice);


Documentation By C.Veera Sekhar Reddy                          Page 18
                                     Java Server Pages

ps.executeUpdate();

System.out.println("data is stored correctly");

}

}

Newproduct.html:


        Producat id                            pid

        Produ name                         pname            these are properties

        Price                                price



                                    submit




Store.jsp       <% String pid1=request.getParameter(“pid”);

                  String pname1=request.getParameter(“pname”);

                  String price1=request.getParameter(“price”);

                %>

                <%

                Info.inetsolv.ProductJB prod=new info.inetsolv.ProductJB();

                Prod.setProductId(pid1);             //call productJB class method of setProductId()

                Prod.setProuductname(pname1));// call productJB class method of setProductName()

                Prod.setProuductname(pprice1));// call productJB class method of setProductprice()

                Prod.storeProduct();%>

                Data stored in jsp<br>

                For adding new data <a href=”newproduct.html”>click</a>



Documentation By C.Veera Sekhar Reddy                                                                  Page 19
                                 Java Server Pages



To remove the java code from above jsp , we can use jsp action tags.

Some of the jsp action tags are

1.<jsp:useBean>

2.<jsp:setProperty>

3.<jsp.getProperty>

4.<jsp:include>

5.<jsp:forward>

<jsp:usebean>

Syntax:


          <jsp:useBean id=”prod” class=”info.inetsolv.ProductJB” />

Is equal to
                 <%

                  Info.inetsolv.ProductJB prod=new info.inetsolv.ProductJB()

                 %>




Documentation By C.Veera Sekhar Reddy                               Page 20
                                 Java Server Pages

<jsp:setProperty>

This method can be used to call setter methods of java bean class
            <jsp:setProperty name=”prod” property=”productId” param=”pname”/>
Syntax:



Is same as
          <% info.inetsolv.ProductJB prod=new info.inetsolv.ProductJB();

          Prod.setProductId(request.getParameter(“pname”);

          %>




<jsp:getProperty>

This method can be used to call getter methods of java bean class
            <jsp:getProperty name=”productId” property=”ProductId” />

Is same as
                           Out.println(prod.getProductId());




Note: every time use bean tag can’t create the object for class , only
one time it create the object.

What will happened when rewriting the above application of store.jsp
using jsp action tags;


Documentation By C.Veera Sekhar Reddy                                      Page 21
                                      Java Server Pages

     Store.jsp

<%   <jsp:useBean id=”prod” class=”info.inetsolv.ProductJB” scope=”request” />

 <jsp:setProperty name=”prod” property=” ProductId” param=”pname”/>

 <jsp:setProperty name=”prod” property=” ProductName” param=”pname”/>

 <jsp:setProperty name=”prod” property=” ProductPrice” param=”pname”/>

%>

<%

 <jsp:getProperty name=”prod” property=”ProductId” />

<jsp:getProperty name=”prod” property=”ProductName” />

<jsp:getProperty name=”prod” property=”ProductPrice” />

%>Data stored in jsp<br>

For adding new data <a href=”newproduct.html”>click</a>




     To develop reusable pages we can use the following actions

     <jsp:include>

     <jsp:forward>




     Documentation By C.Veera Sekhar Reddy                                       Page 22
                                      Java Server Pages

Ex:

One.jsp
              This is first line from one.jsp

              <jsp:include page=”two.jsp”/>

              This is last line from one.jsp


Two.jsp
               This is first line from two.jsp

               This is last line from two.jsp



What is the output when u run the above one.jsp?

The output is
            This is first line from one.jsp

            This is first line from two.jsp
                                                 thes lines are coming from two .jsp
            This is last line from two.jsp

            This is last line from one.jsp




What will happened when you run the one.jsp:

1.when u send the request one.jsp the server will create the 2 objects
namely request and response

2.the above created request and response will havdover to service()
method of one.jsp

3.the one.jsp create the context object and it will handover to one.jsp

4.the server will execute the template text and output stored in the
servers memory

Documentation By C.Veera Sekhar Reddy                                                  Page 23
                                 Java Server Pages

5.the server will execute rd.include() and handover same request and
response object to the two.jsp

6.once if we give request to two.jsp it execute jsp service()and two.jsp
create the pagecontext object

7.the code in the two.jsp will be executed and the output will return
back to one.ksp

8.the server will remove the two.jsp pagecontext object

9.the server will continue the execution of one.jsp

10.All the output will be accumulated together and send output to the
user

11.once the one.jsp is executed finish, the pagecontext object of
one.jsp is removed.

Note: the process of sending one request and execute more than
servlet or jsp is called servlet chaining

<jsp:forward>

Note: in case of jsp forward the controller will not return back to caller
method.




Documentation By C.Veera Sekhar Reddy                               Page 24

				
DOCUMENT INFO
Shared By:
Stats:
views:12
posted:12/3/2011
language:English
pages:24