You are on page 1of 18

1 JSP Introduction A web application consists of number of web pages.

These web pages are generally developed using HTML. But pages developed using HTML produce static output or they have passive behavior. But at times you want to give different output to users by changing only a small part of the page. For example, if you want to display date and time or hit-count require a very small change in web page. To provide dynamic behavior to it, small programs can be included in HTML. This makes web pages to give different output for different users. Thus the behavior of the page becomes active. Java Server Pages (JSP) is a Java-based technology that simplifies the process of developing dynamic web-sites using JSP, web designers & developer can quickly incorporate dynamic elements into web pages using embedded Java & markup tags. The tags allow the user to present data & java object (Applet/JDBC/Java bean/servlet etc) allow storing business logic. JSP specification is a standard extension defined on top of the servlet API. JSPs are text files with .jsp extension, which includes HTML/XML tags along with embedded java code. Advantage Of JSP Technology 1. Portability

Since it is based on Java, JSP technology is platform independent. To run .jsp files, we need a JSP engine (programs used to run .jsp files). This engine can be built for different type of web-servers to make them execute jsp files. 2. Reuse of Components & Tag Libraries

JSP technology emphasizes the use of reusable component such as Java Bean Components, Enterprise Java Bean Components etc. Data is the main reason of dynamic contents. The components may contain the code to obtain the data from databases or text files thus offering different contents to JSP files. It supports different type of markup languages such as HTML/DHTML/XML. JSP also supports user-defined tags. For user-defined tags, the control is transferred to classes that contain the code, which should be executed. Any type of code such as JDBC, File Handling etc can be included in these classes. Thus a JSP page developer need not have considerable knowledge of Java. 3. Separation of static & Dynamic Content

Using HTML pages, we can send only static contents to web clients. If we use servlets, then the entire HTML code is required to be written in println statement, which is tedious. It also makes the entire page to be dynamic. JSP allows you to include dynamic content into the static contents separating the two from each other. The static contents are provided using HTML tags and dynamic contents are generated using scriptlets, userdefined tags etc. It also follows popular MVC (Model-View-Control) Design Pattern.

2 Fig.

4.

Suitable for N-Tier Architecture

Because of features such as, platform-independence, support for different types of servers(web servers, database servers etc), markup languages, reuse of objects in the form of components etc. it is best suited for N-Tier architecture. 5. Performance

JSP pages are automatically compiled before execution. So it frees the job of programmer to explicitly compile the program. After compilation, the page is kept in memory for certain duration to serve for next requests. Thus the compilation activity is not done for every request(unless there are modifications in the page). ASP VS JSP Category Platform Support Type Memory requirements Web Server Support Reusable objects Scripting Languages Customizable tags Memory leak protection Servlets VS JSP Servlets 1. Servlets are less efficient in generating dynamic contents. 2. Servlets files must be compiled by user. 3. Developers need to have significant knowledge of Java. 4. Management of beans is done using java code JSP 1. JSP offers a clear separation of static and dynamic contents. 2. JSP files are automatically compiled. 3. Developers need not have significant knowledge of Java. 4. Management of beans is done using tags. ASP Windows only Interpreted for every request Loaded for each request IIS, PWS COM / DCOM NBScript, Java script Cannot use custom tag libraries and is not extensible. No JSP All java enabled platforms Compiled once executed again and again Loaded only once in memory Any web server Apache, Netscape, IIS etc Java Beans, Servlets, EJB Java / Java script Extensible with custom tag libraries. Yes

3 One.jsp <html> <body> Hello. <% String uname=request.getParameter(name); if(uname==null) uname=world; %> Hello, <%= uname %>! </body> </html> <% .%> <%=%> request JSP Execution When a server receives a request for JSP file, the request is sent to the JSP engine. The JSP engine checks whether it already exists in memory or not. If it doesnt, then the engine compiles the JSP file into a special servlet file. The servlet is executed and the response object generated by it is sent to the client through the web server. Thus, when a JSP file is accessed for the first time, it requires some time to get the response. If the file is already present in the memory, then the engine checks whether the original JSP file is modified or not. If it is modified, then the JSP file is recompiled and executed. Otherwise it is just executed again. Thus JSP files are automatically recompiled, but pure servlet files should be explicitly recompiled. Fig. includes JSP/Java codes(Scriplet) includes variables Http request object

The JSP page class file extends HttpJspBase which in turn implements the Servlet interface. It contains 3 methods. i. ii. iii. jspInit : performs the initialization of a servlet. This method can be overridden. _jspService: executed for every request. jspDestroy: gets executed when servlet is removed by the server. This method can be overridden.

4 Just as a web server needs a servlet container to provide an interface to servlets, the server needs a JSP container to process JSP pages. The JSP container is responsible for intercepting requests for JSP pages. To process all JSP elements in the page, the container first turns the JSP page into a servlet (known as the [JSP page implementation class). The conversion is pretty straightforward; all template text is converted to println( ) statements similar to the ones in the handcoded servlet, and all JSP elements are converted to Java code that implements the corresponding dynamic behavior. The container then compiles the servlet class. Converting the JSP page to a servlet and compiling the servlet form the translation phase. The JSP container initiates the translation phase for a page automatically when it receives the first request for the page. Since the translation phase takes a bit of time, the first user to request a JSP page notices a slight delay. The translation phase can also be initiated explicitly; this is referred to as precompilation of a JSP page. Precompiling a JSP page is a way to avoid hitting the first user with this delay. The JSP container is also responsible for invoking the JSP page implementation class (the generated servlet) to process each request and generate the response. This is called the request processing phase. The two phases are illustrated in the following figure -

As long as the JSP page remains unchanged, any subsequent request goes straight to the request processing phase (i.e., the container simply executes the class file). When the JSP page is modified, it goes through the translation phase again before entering the request processing phase. The JSP container is often implemented as a servlet configured to handle all requests for JSP pages. In fact, these two containers -- a servlet container and a JSP container -- are often combined in one package under the name web container. JSP Access Model / JSP Architecture These are based on the location at which the bulk of the request process is preformed. 1. Model 1 (Page Centric Design)

5 Fig.

In this type, the incoming request from a web browser is sent directly to the JSP page, which is responsible for processing it & replaying back to the client. There is still separation of using beans. Although, Model 1 architecture is suitable for simple application, it may not be desirable for complex implementation. This architecture usually leads to significant amount of script-lets embedded within a JSP Page. This may cause problems for web developers who dont know much about Java, but required to develop large websites. The other disadvantage of this architecture is that each JSP page is individually responsible for managing application state & verifying authentication & security. 2. Model 2 (Servlet-Centic Design)

The Model-2 architecture is a server-side implementation of the popular MVC design pattern. Here the processing is divided between the presentation and front component. Presentation component are JSP pages that generate the HTML/XML response that determines the user interface when viewed by the browser. Front component controller do not handle any presentation issues, but process all the HTTP requests. Here, they are responsible for creating any beans or objects used by the presentation components, as well as deciding, depending on the users act which presentation components to forward the request to. Front components can be implemented as either a servlet or JSP page. The advantage of this architecture is that, there is no processing logic within the presentation component itself, it is simply responsible for retrieving any objects or beans that may have been previously created by the controller and extracting the dynamic content within for insertion within its static templates. This separation of roles and responsibilities of developers and page designers. Another advantage of this approach is that the front component present a single point of entry into the application thus making the management of application state, security and presentation uniform and easier to maintain.

6 JSP Syntax Basics 1. Declarations

JSP Declarations lets you define page level variables or methods. These are like variables or methods declared as class-level member. You can declare static or instance variables or methods. It is declared using <%!....%>. For eg <%! int i=0;%> or <%! public void test(){..}%> numsq.html <html> <form method=get action=http://localhost:8080/ty/numsq.jsp> Enter Num : <input type=text name=t1> <input type=submit> </form> </html> numsq.jsp <html> Sq:<%=getsq(request)%> </html> <%! public int getsq( HttpServletRequest req) { int i=Integer.parseInt (req.getParameter(t1)); return i*i; } %> 2. Expression

They are included <%=.%>. The results of evaluating the expression are converted to a string & directly included within the output page. These are used to display simple variables or return values of methods. For example <%= i %> or <%= bean1.getname() %>

3.

Scriplets

JSP code fragments or scriplets are included in<%.....%>. The code declared within these tags goes into service method. It includes java code which is to be executed by the server. For example:<%for (int i=1; i<=4;i++) { %>

7 <H <%=i%>>Hello</H<%=i%>> <%}%> o/p <H1> Hello </H1> <H2> Hello </H2> <H3> Hello </H3> <H4> Hello </H4> 4. Comments

<%-- ................. --.%> represents server-side comment. 5 Directives

JSP directives are messengers for the JSP Engine. They dont directly produce any visible O/P but tell the engine what to do with the JSP page. They are included in < %@.... %> tag. They are used to set the content type, import packages, control buffering, session management etc. The general syntax for directives are:<%@ directive attribute name = value..%> There are 3 types of directives :1. Page directives- It defines a no. of important attributes that affect the whole page directives is as follows : (a) contentType sets the MIME content-type <%@ page contentType = text/plain %>

(b) import specifies a list of classes & packages, the generated servlet should import. By default, java.lang.*, javax.servlet.*; javax.servlet.http.* & javax.servlet.jsp.* are automatically imported. <%@ page import = java.io.*, java.util.* %> (c) buffer specifies the minimum requirement size of the response in KBs. A special value none indicates that content should be passed directly to the underlying PrintWriter object. Default is 8Kb. <%@page buffer = 12Kb %> (d) autoFlush specifies if the buffer should be flushed when its filled or IO exception should be thrown. Default is true, because if this attributes is false, then a programmer should manually flush the buffer. <%@ page autoFlush = true %>

8 (e) session indicates the page want to have access to users session. Default is true. <%@ page session = true %> (f) errorPage specifies a page to display if an exception occurs within the JSP page. <%@ page errorPage = /error.jsp %> (g) isErrorpage indicates the page is intended to be used as the target on the errorpage. <%@ page isErrorPage=true %> (h) language specifies the scripting language used to write the code. Default is java. <%@ page language =javascript%>. 2. Include Directive

The include directive lets you separate your content into more manageable elements/files. For example, you can design separate html files that display common header/footer and include it in a jsp page. It includes the contents of given file in a current jsp page. For example, <%@ include file=copyright.html %> 3. Taglib Directive

This directive allows the page to use custom user-defined tags with the specified tag library name. The files have tld(tag library descriptor) extension. These files contain the specification of which classes should be executed when a user-defined tag is encountered. For example <%@ taglib uri=/WEB-INF/struts.tld prefix=struts %> Every user-defined tag is prefixes by a string specified by prefix attribute to avoid problems of tag-name clashes. For example, you can have your own tag called html with a prefix to differentiate it from HTMLs html tag. For example <user:html> .. </user:html> pagedemo.jsp <%@page contentType="text/html" import="java.util.Date" session="true" %> Hello, User!!! <br> Current time is <b> <%= new Date( ) %> </b> <%@ include file="register.html" %> <br> Session ID = <b> <%= session.getId( ) %> </b> <br> Context Parameter : <b> <%= application.getInitParameter("country") %> </b>

9 JSP Implicit objects JSP container makes available implicit objects to be used within scriptlets and expressions, without the programmer first having to first create them. These objects act as wrappers around underlying java classes and interfaces defined in servlet API. They are as follows 1. request : represents HttpServletReqeust object used to access clients info. 2. response : represents HttpServletResponse object used to send data to client. 3. out : represents JspWriter object that writes into the output stream. 4. config : represents ServletConfig object used to read initialization parameters. 5. session : represents HttpSession object used to identify a client and associate info with it. 6. page : represents HttpJspPage object. Alternatively, you can use this operator to refer to current page. This object is used in custom tag handler classes. 7. application : represents object of ServletContext which is used to obtain information about servlets that are running. 8. pageContext : represents object of PageContext which is used to access context data for page execution. 9. exception : represents Throwable object to handle uncaught errors and exceptions. Synchronization Issue By default, the service method of the JSP page implementation class that services the client request is multithreaded. Thus, it is the responsibility of the JSP page author to ensure that access to shared variable is synchronized .The other way to use is Thread Safe attribute of page directive <%@ page isThread Safe=false %> The above declaration causes the JSP pages implementation class to implement single thread model interface, and having multiple instances of servlets to be loaded in the memory. The concurrent client requests are then submitted to individual servlet. Servlet Instance 1 Servlet Instance 2 Servlet Instance n
Req, Res --------------Req, Res --------------Req, Res ---------------

Servlet Container

The disadvantage of using the above Servlet Pool method is when large number of concurrent requests are received, the total number of servlet-instances loaded at a time are limited. So a client may have to wait for some time to get a free servlet. Thats why a better approach is to use isThreadSafe to be true (by default, it is true) and to explicitly control access to shared objects.

10 counter.jsp <html> <%! Integer count = new Integer(0); %> <% synchronized(this) { try { int I = count.intValue(); I++; out.println(this servlet has been accessed + I + number of times); count = new Integer(I); } catch(Exception e) {} } %> </html> Session Management By default, all JSP pages participate in an HttpSession. Session is used for the purpose to identify a session and to associate information with it to be used for multiple requests coming from same browser window. Sessions are good place for storing beans and objects that need to be shared across other JSP pages and servlets, that may be accessed by the user. The session object is identified by a session id and stored into browser as a cookie. If cookies are not supported by the browser, then the session id may be maintained by URL rewriting a(modifying URL explicitly to include name-value pairs, for example http://localhost:8080/ty/servlet/ser1?t1=1) . You cannot add primitive data types into the session. You can only store valid java objects identified by a unique key. UserCounter.jsp <html> <% int j = 0; out.println( "<br> Session id : " + session.getId() + "<br>"); if( (Object) session.getAttribute("ucounter") == null) { j = 1; session.setAttribute("ucounter", new Integer(1)); } else { Integer k = (Integer) session.getAttribute("ucounter"); j = k.intValue() + 1; session.setAttribute("ucounter", new Integer(j)); }

11 %> You accessed this page for <%= j %> times <br><a href=http://localhost:8080/milind/UserCounter.jsp> Click </a> </html> Handling Exceptions When you are creating an application using JSP, you need to make sure that your application handles the errors properly. There are 2 types of errors or exceptions that can generally occur 1. Translation Time Errors

Since JSP pages are compiled automatically by Web server, translation errors can occur during the page compilation. This results in an internal server error ( Error Code 500). The specific error messages displayed as a translation time error which are sent and displayed on the browser. 2. RunTime Exceptions

These errors occur during the execution of a JSP page. Most of the times, it occurs because of invalid client input. Most of the rime, it results in a stack dump on the client side. In JSP, this can be avoided using error pages as shown below cal.jsp <html> <%@ page errorPage = error.jsp %> <% int j = 4/0; %> </html> arith.jsp <html> <%@ page errorPage = error.jsp %> <% int ar [] ={1,2,3}; out.println(ar[6]); %> </html> error.jsp <html> <%@ page isErrorPage = true %> <% if ( exception instanceof ArithmeticException ) { out.println(invalid arithmetic operation ); } else

12 if(exception instanceof ArrayIndexOutOfBoundsException ) { out.println(invalid array subscript); } %> </html>

Forwards This is similar to forwarding using RequestDispatcher. Syntax <jsp:forward page=uri /> You can also specified parameters using <jsp:param> tags user.html <form method=get action=user.jsp> Name : <input type=text name=t1> <br> <input type=submit> </form> user.jsp <% request.setAttribute("pass","admin"); %> <jsp:forward page="info.jsp" /> info.jsp Hello, <%= request.getParameter("t1") %> <br> Your pass is : <%= request.getAttribute("pass") %> Including Beans JSP allows programmers to make use of beans in them. It is a part of jsp action category. Actions allow programmers to specify how to forward pages, specify java applets, include beans etc. Actions support XML-based syntax. The syntax for including beans is as follows <jsp:useBean id=BeanName class=ClassName scope=scopevalue /> The main attributes are as follows i) id specified name using which the bean can be accessed, ii) class- specified java class name

13 iii) scope specified scope (application /request/session/page) To access the properties of bean, the syntax is as follows <jsp:getProperty name=BeanName property=PropertyName /> To set the properties of bean, the syntax is as follows <jsp:setProperty name=BeanName property=PropertyName value=Newvalue/>

14 Object Scope JSP pages include java objects. These objects are either implicit or can be created by the user. These objects can be associated with a scope attribute defining the visibility of that object in different parts of JSP pages or through out the application. We have already studied that there are objects like ServletConext, request, session etc which can hold objects using setAttribute method. In this case, we first declare the objects and then specify where they should be added using scope. You can define objects with following scope--1) application :- identifies objects accessible from pages that belong to the same application (Client independent). The objects with application scope are added into ServletContext. 2) session:- identifies objects accessible from pages that belonging to the same session as the one in which they were created.(life of user session, multiple requests from same browser window). The objects with session scope are added intoHttpSession. 3) request:- objects accessible from pages processing the request where they were created(before response is sent, accessible also in any included or forwarded pages). The objects with request scope are added into HttpServletRequest. 4) page :-objects accessible only within pages where they were created.(current page until it is displayed or control is forwarded to new page). The objects with page scope are added into PageContext. PageContext object is used to store contextual information to be accessed in Tag-Handler classes which are written for custom tags written in JSP. The scope of implicit objects is as follows---Scope 1) application 2) request 3) page 4) session Note :--- 1) All implicit objects are only visible within the system generated _jspService method. They are not visible within methods that you define yourself in declarations. 2) 4 JSP implicit objects(request, session, application, pageContext) have the ability to store and retrieve attribute names and values .These are used to share information among jsp and servlets. Implicit objects ---------- application ---------- request ---------- response, pageContext, out, config, page, exception -------- session

15 i) ii) iii) iv) setAttribute(String key,Object val) String [] getAttributeNames( ) Object getAttribute(String key) removeAttribute(String key)

Bean Demo It shows creation of bean and how values can be assigned to the properties of bean and then how they can be used. The program contains a data-entry form accepting roll, name and marks whose input is taken from two files. Step 1 : Create a class called student, compile it and store the class file in classes folder. student.java public class student { private int roll; private String name; private float marks; public student() { roll = 0; name = "XYZ"; marks = 0; } public int getRoll() { return roll; } public void setRoll(int r) { if(r>0) roll = r; } public String getName() { return name; } public void setName(String r) { name = r; } public float getMarks() { return marks; } public void setMarks(float f) { if(f>0)

16 marks = f; } } Step 2 : s1.html <html> <form method=get action=s1.jsp> enter roll : <input type=text name=t1> <br> enter name : <input type=text name=t2> <br> <input type=submit value=Next> </html> s1.jsp <jsp:useBean class="student" id="s" scope="session"/> <% int roll = Integer.parseInt(request.getParameter("t1")); %> <% String name = request.getParameter("t2"); %> <jsp:setProperty name="s" property="roll" value = "<%= roll %>" /> <jsp:setProperty name="s" property="name" value = "<%= name%>" /> <jsp:forward page="s2.jsp" /> </html> s2.jsp <html> <form method=get action="s3.jsp" > Marks : <input type=text name=t3 > <input type=submit value=Last> </form> </html> s3.jsp <html> <% float f = Float.parseFloat(request.getParameter("t3")) ; %> <jsp:setProperty name="s" property="marks" value = "<%= f %>" /> <br> Roll : <jsp:getProperty name="s" property="roll" /> <br> Name : <jsp:getProperty name="s" property="name" /> <br> Marks : <jsp:getProperty name="s" property="marks" /> </html> Now you create HTML/JSP files.

17 Creating Custom Tags Step 1 : Define Tag Library Descriptor(tld) file This file contains the definition of new tags and their attributes. It also contains the names of tag handler classes which should be called on occurrence of these tags in JSP file. web-inf \ mytags.tld <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>mytag</shortname> <tag> <name>showtab</name> <tagclass>showtable</tagclass> <attribute> <name>dsn</name> </attribute> <attribute> <name>table</name> </attribute> </tag> </taglib> Step 2. Define JSP file Then write the jsp file. To use the customs tags, it should include the tag library descriptor file which contains the definition of the tags which are written in JSP. tables.jsp <%@ taglib uri="web-inf/mytags.tld" prefix="mytag" %> <html> <mytag:showtab dsn="k" table="users" /> </html> Step 3. Write tag handler class Now write the code of tag handler class. The tag handler class should implement Tag interface or should extends TagSupport class located in javax.servlet.jsp.tagext package. It contains setter methods for every attribute that is defined in the tag. The above example is of a tag that does not have body.

18 showtable.java import java.io.*; import java.sql.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class showtable extends TagSupport { private String dsn,table; public showtable() { super( ); } public void setDsn(String d) { dsn = d; } public void setTable(String d) { table = d; } public int doEndTag() { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:" + dsn); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select * from " + table); if(rs!=null) { JspWriter jspout = pageContext.getOut(); jspout.println("<h3> Showing 1st column of " + table + "</h3>"); while(rs.next()) { jspout.println("<br> " +rs.getString(1)); } } con.close(); } catch(Exception e) { System.out.println(e); } return EVAL_PAGE; } } Step 5. Compile tag handler class and execute the JSP file

You might also like