You are on page 1of 60

JSP

Java Server Pages (JSP ) is Sun's solution for developing dynamic web sites. JSP enable the developers to directly insert java code into Html file, this makes the development process very simple and its easy to maintain. JSP's are internally converted to Servlet and compiled by container. We use JSP for presentation, where there is lot of display & less of business logic. Saved as .jsp file directly under context root folder along with HTML.

JSP LifeCycle
1. First the JSP file is translated to java file by the container. 2. Java file is compiled to .class file by the container. 3. Class file is loaded by container 4. Instance of the servlet created. 5. The container calls the servlets JSP Init() 6. The container creates a new thread to handle the clients request and the servlets jspService() is called 7. jspDestroy() when the servlet is destroyed.

Servlet Vs JSP
Basically servlet is a JSP but differs as follows Servlets
HTML script embedded in java code. Compiled and deployed Should be configured in web.xml Suitable for business logic and controller operations. JSP - Java code within HTML file - Automatic compilation - Translate compile- execute on the fly - Suitable for presentation logic

JSP Scripting Element


Expressions : To place any expression use <%= %> Ex <%= new java.util.Date()%> <% = ++count %> Note: Do not put semicolon at the end of expression.

Scriptlet :Consists of valid java code snippets that are enclosed within <% %>. <% JavaCode %> Ex <% for(int i=1;i<=10;i++) { out.println(5*i); } %>

Declaration : Provide a mechanism to define variables and methods. Declarative statements always ends with semicolon. Ex : <%! int count=0;%> JSP Comment : The page developer can provide comments in <% -- -- %> they are stripped out of translated page. Ex: <%-- This is a JSP Page --%> HTML Comment : <!-- HTML Comment -->

JSP Directives
JSP directives serve as messages to the JSP container from the JSP. They do not directly produce any visible output, but tell the container what to do with the rest of the JSP page A directive affects the whole JSP file, and only that JSP file Directives are of three types Page Directive Include Directive TagLib directive

Include Directive
Include: Include is used to include a file in the JSP page. Example: <%@ include file="/header.jsp" %>

Page Directive
Defines attribute that notify JSP container about the general settings of a JSP page. The page directive is found at the top of almost all of your JSP pages Page directive helps to import classes Handle error messages Define if the JSP is thread safe Set the page content type Define if the session object is available.

<%@ page [ language="java" ] [ extends="package.class" ] [ import="{package.class | package.*}" ] [ session="true | false" ] [ isThreadSafe="true | false" ] [ info="text" ] [ errorPage="relativeURL" ] [ contentType="mimeType ] [ isErrorPage="true | false" ]

Attributes language="java" The scripting language used in scriptlets, declarations, and expressions in the JSP file and any included files. In this release, the only allowed value is java. extends="package.class" The fully qualified name of the superclass of the Java class file this JSP file will be compiled to.

import="{package.class | package.* }, ..." A comma-separated list of Java packages that the JSP file should import. The packages (and their classes) are available to scriptlets, expressions, and declarations within the JSP file. If you want to import more than one package, you can specify a comma-separated list after import or you can use import more than once in a JSP file.

session="true | false" Whether the client must join an HTTP session in order to use the JSP page. If the value is true, the session object refers to the current or new session. errorPage="relativeURL" A pathname to a JSP file that this JSP file sends exceptions to. If the pathname begins with a /, the path is relative to the JSP application's document root directory and is resolved by the Web server. If not, the pathname is relative to the current JSP file.

isErrorPage="true | false" Whether the JSP file displays an error page. If set to true, you can use the exception object in the JSP file. If set to false (the default value), you cannot use the exception object in the JSP file. info="text" A text string that is incorporated into the compiled JSP page. You can later retrieve the string with the Servlet.getServletInfo() method.

Implicit Objects

Implicit Objects
Several predefined variables are available to scriptlets and expressions for a JSP page. Implicit objects are available as local variables within jspservice() that gets generated when JSP is translated to Servlet. User defined methods will not be able to access these implicit objects as they are local to jspService() method. Can be passed as parameter to userdefined methods to use them locally in the function.

Some of the implicit objects are - out, config, request, response, page, pagecontext, session , application, exception. out : Is used to write the content to response. It displays anything with delimiters. Out object is of type : javax.servlet.jsp.JspWriter Ex : out.println(Welcome to JSP);
Config : Is used to get information regarding the servlet configuration, stored in the config object. Config object is of type : javax.servlet.ServletConfig

Request is an implicit object of class HttpServletRequest class and using this object request parameters can be accessed. The request object is of type javax.servlet.http.HttpServletRequest Ex : request.getParameter(username); Response is an implicit object of class HttpServletResponse class and using this object response parameters can be set/modified. The request object is of type javax.servlet.http.HttpServletResponse Ex : response.setBuffereSize(50);

Session is an implicit object of class HttpSession class and used to maintain session information across multiple page requests. It stores information as namevalue pair. The Session object is of type javax.servlet.http.HttpSession Ex : session.setAttribute(name,James); Application object is used to share the data with all application pages. This object belongs to class ServletContext and used to maintain information throughout the scope of application. Application object is of type javax.servlet.ServletContext Ex : Application.setAttribute(servername, www.myserver.com);

Page : Object denotes the JSP page. The page object is of type javax.servlet.JSP.HttpJspPage. PageContext : Used to access all the page attributes and responsible for generating all the implicit objects. PageContext object is of type javax.servlet.JSP.PageContext. Exception: Represents throwable expression in JSP page. Is of type java.lang.Throwable.

web.xml file <web-app> <servlet> <servlet-name>config implicit example</servlet-name> <jsp-file> /configwelcome.jsp</jsp-file> <init-param> <param-name>dname</param-name> <param-value>ABC Pvt. Ltd.</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>config implicit example</servlet-name> <url-pattern>/configwelcome</url-pattern> </servlet-mapping> </web-app>

<servlet> <servlet-name>application implicit example</servlet-name> <jsp-file>/applicationwelcome.jsp</jsp-file> </servlet> <servlet-mapping> <servlet-name>application implicit example</servlet-name> <url-pattern>/applicationwelcome</url-pattern> </servlet-mapping> <context-param> <param-name>d2name</param-name> <param-value>Hot Driver</param-value> </context-param>

sessionsetimplicit.jsp <body> <% String s1 = request.getParameter("uname"); out.println("welcome "+s1); session.setAttribute("cool",s1); %> <a href = "sessiongetimplicit.jsp"> sessiongetimplicit </a> </body> sessiongetimplicit.jsp <body> <% String name = (String)session.getAttribute("cool"); out.println(name); %> </body>

Class PageContext - static int SESSION_SCOPE Session scope (only valid if this page participates in a session): the named reference remains available from the HttpSession (if any) associated with the Servlet until the HttpSession is invalidated.

JSP Action tags


Servlet container provides many built in functionality to ease the development of the applications. Programmers can use these functions in JSP applications. JSP Actions tags enables the programmer to use these functions.

jsp:forward
The jsp:forward tag is used to hand off the request and response to another JSP or servlet. In this case the request never return to the calling JSP page. Without parameter <jsp:forward page= "relativeURL | <%= expression %>" />

With parameter
<jsp:forward page= "relativeURL | <%= expression %>" />
<jsp:param name="parameterName value=parameterValue | <%= expression %>" />

</jsp:forward>

Examples <jsp:forward page="login"> <jsp:param name="username" value="jsmith" /> </jsp:forward> The <jsp:forward> element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file.

jspforward1.jsp <html> <body> <h2>this is index page</h2> <!-- Example1 is a servlet file --> <jsp:forward page="Example1" /> <%--<jsp:forward page="jspforward2.jsp" />--%> </body> </html> jspforward2.jsp <html> <body> <% out.print("Today is:" + java.util.Calendar.getInstance().getTime()); %> </body> </html>

jspforward3.jsp <html> <body> <h2>this is index page</h2> <jsp:forward page="jspforward4.jsp" > <jsp:param name="name" value="qwerty" /> </jsp:forward> </body> </html> <html> jspforward4.jsp <body> <% out.print("Today is:" + java.util.Calendar.getInstance().getTime()); %> parameter name is: <%=request.getParameter("name")%> </body> </html>

jsp:include
The jsp:include action work as a subroutine, the Java servlet temporarily passes the request and response to the specified JSP/Servlet. Control is then returned back to the current JSP page. Without parameter <jsp:include page= "relativeURL | <%= expression %>" /> With parameter <jsp:include page= "relativeURL | <%= expression %>" />
<jsp:param name="parameterName value=parameterValue | <%= expression %>" />

</jsp:include>

jspinclude1.jsp <html> <body> <h2>this is index page</h2> <jsp:include page="jspinclude2.jsp" > <jsp:param name="uname" value="cool" /> </jsp:include> <h2>this is end of index page</h2> </body> </html> <html> jspinclude2.jsp <body> <% out.print("Today is:" + java.util.Calendar.getInstance().getTime()); %> parameter name is: <%=request.getParameter("uname")%> </body> </html>

jsp:useBean The jsp:useBean tag is used to instantiate an object of Java Bean or it can re-use existing java bean object. jsp:getProperty The jsp:getProperty is used to get specified property from the JavaBean object.
jsp:setProperty The jsp:setProperty tag is used to set a property in the JavaBean object.

useBean.jsp <body> <jsp:useBean id="obj" class="com.jft.Calculator" /> <% int m = obj.cube(5); out.print("cube of 5 is " + m); %> </body> package com.jft; public class Calculator{ public int cube(int n){ return n*n*n; }

setgetpropertyinput.html
<body> <form action="setget.jsp" > Enter Name: <input type="text" name="name" /> <input type="text" name="password" /> <input type="submit" value="go" /> </form> </body>

Setget.jsp
<body> <jsp:useBean id="obj" class="com.jft.User" /> <jsp:setProperty name="obj" property="*" /> Welcome, <jsp:getProperty name="obj" property="name" /> <jsp:getProperty name="obj" property="password" /> </body> package com.jft; public class User{ private String name; private String password; public void setName(String name){ this.name=name; } public String getName(){ return name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }

How does a JSP convert to Servlet?


All the static html out.println() directly into service method. <%= count %> :Expression tag will goto into service method as out.println(). <%! count=0%> :Declaration tag contains multiple java lines inside class but outside service method. <% count++; out.println(count); %> Scriptlet tags plugged into service directly. (copy and paste)

Beans and Form processing


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". Java bean is ordinary java class - to hold the input data.

Rules to build bean class


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. The class fields must have getters" that match the names of the form fields. The setter parameter type should be same as getter return type. Public no argument constructor

<HTML> <BODY> <FORM METHOD=POST ACTION="SaveName.jsp"> What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20><BR> What's your e-mail address? <INPUT TYPE=TEXT NAME=email SIZE=20><BR> What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4> <P><INPUT TYPE=SUBMIT> </FORM> </BODY> </HTML>

package test; public class Person { String username; String email; int age; public void setUsername( String value ){ username = value; } public void setEmail( String value ) { email = value; } public void setAge( int value ) { age = value; } public String getUsername() { return username; } public String getEmail() { return email; } public int getAge() { return age; } }

<jsp:useBean id=beanie" class=test.Person" scope="session"/> <jsp:setProperty name=" beanie " property="*"/>


<HTML> <BODY> <A HREF="NextPage.jsp">Continue</A> </BODY> </HTML>

The useBean tag will look for an instance of the test.Person" in the session. If the instance is already there, it will update the old instance. Otherwise, it will create a new instance of test.Person (the instance of the test.Person is called a bean), and put it in the session. The setProperty tag will automatically collect the input data, match names against the bean method names, and place the data in the bean!

<jsp:useBean id=beanie" class=" test.Person " scope="session"/> <HTML> <BODY> You entered<BR> Name: <jsp:getProperty name=beanie " property=username"/> <BR> Email: <jsp:getProperty name=beanie " property=email"/> <BR> Age: <jsp:getProperty name=beanie " property=age"/> <BR> </BODY> </HTML>

Taglib Directive
Defines a tag library and prefix for the custom tags used in the JSP page <%@ taglib uri="URIToTagLibrary" prefix="tagPrefix" %> Example: <%@ taglib uri="http://www.jspcentral.com/tags" prefix="public" %> <public:loop> . . </public:loop>

The <%@ taglib %> directive declares that the JSP file uses custom tags, names the tag library that defines them, and specifies their tag prefix.

You might also like