+ All Categories
Home > Documents > JSP Tutorial

JSP Tutorial

Date post: 29-Nov-2014
Category:
Upload: vijay-kumar
View: 859 times
Download: 3 times
Share this document with a friend
Popular Tags:
50
http://www.easywayserver.com JSP Introduction In this jsp tutorial we will learn about JSP with less time. This will guide you to write server side scripting. JSP is easiest and powerful scripting language because it is compiled by web container. JSP is used for making dynamic web pages to interaction with end user with the help of JSP form or html form. What is JSP? JSP is java server pages, which is dynamic web pages and used in to build dynamic websites. JSP provides developer to do less hard work with better work output. JSP works with http protocols; it provides tag and tools to make JSP pages. To run jsp, we need web server it can be tomcat provided by apache, it can be jRun, jBoss(Redhat), weblogic (BEA) , or websphere(IBM) JSP Running platform JSP can be run on any platform. Most of web server supports all platforms like linux, Microsoft windows, sun soloris, Macintosh, FreeBSD. JSP takes, advantage of java platform independent . What is a JSP File? JSP is dynamic file which like as HTML file. Html file is static and can not get data from database or fly data. JSP can be interactive pages and communicate with database and more controllable by programmer. JSP is executed on web server with help of java compiler. JSP can contain text, images, hyperlinks and all can be in HTML page. It is saved by extension of .jsp. ASP, JSP, HTML Difference ASP active server pages is given by Microsoft technologies, it needs IIS (Internet Information Services) to run ASP. Mostly it is run on Windows operating systems. If need to run on others operating system rather than windows, needs extra tools. JSP is almost same but provided by sun Microsystems. JSP is first compiled and then make SERVLET. All ASP, JSP take request from browser and process this request by server (web server) and response back to browser. When web server get request, it compile this code (JSP or ASP) and output from this code response back to particular request. HTML having static content and request doesn’t go to server for process. It process almost on clients side on client’s browser (Internet Explorer or firefox browser). What can do with JSP? JSP is used for dynamic programming, mean we can communicate with database, insert, update, select, alter, and delete records from database with JSP. Logic building with JSP, to print data, e.g., if we want to print good morning, good afternoon, good evening at particular slot of time, then we need to make a logic of time 12 am to 12 pm is good morning, 12pm after 4 pm is good after noon, and 4pm to 12 am is good evening. This can be done by if conditions to check current time and if time comes in any slot then print this message. Interact with user, with the help of forms like enquiry form, or submitting user’s data to server. Provide session to individual users. Increase security and privacy of user. JSP code can not view at client or browser. Web server response browser with plain HTML page; send no JSP code, so user can not get code or see JSP code.
Transcript
Page 1: JSP Tutorial

http://www.easywayserver.comJSP Introduction

In this jsp tutorial we will learn about JSP with less time. This will guide you to write server side scripting. JSP is easiest and powerful scripting language because it is compiled by web container. JSP is used for making dynamic web pages to interaction with end user with the help of JSP form or html form.

What is JSP?

JSP is java server pages, which is dynamic web pages and used in to build dynamic websites. JSP provides developer to do less hard work with better work output. JSP works with http protocols; it provides tag and tools to make JSP pages. To run jsp, we need web server it can be tomcat provided by apache, it can be jRun, jBoss(Redhat), weblogic (BEA) , or websphere(IBM)

JSP Running platform

JSP can be run on any platform. Most of web server supports all platforms like linux, Microsoft windows, sun soloris, Macintosh, FreeBSD. JSP takes, advantage of java platform independent.

What is a JSP File?

JSP is dynamic file which like as HTML file. Html file is static and can not get data from database or fly data. JSP can be interactive pages and communicate with database and more controllable by programmer. JSP is executed on web server with help of java compiler. JSP can contain text, images, hyperlinks and all can be in HTML page. It is saved by extension of .jsp.

ASP, JSP, HTML Difference

ASP active server pages is given by Microsoft technologies, it needs IIS (Internet Information Services) to run ASP. Mostly it is run on Windows operating systems. If need to run on others operating system rather than windows, needs extra tools.JSP is almost same but provided by sun Microsystems. JSP is first compiled and then make SERVLET. All ASP, JSP take request from browser and process this request by server (web server) and response back to browser. When web server get request, it compile this code (JSP or ASP) and output from this code response back to particular request. HTML having static content and request doesn’t go to server for process. It process almost on clients side on client’s browser (Internet Explorer or firefox browser).

What can do with JSP?

JSP is used for dynamic programming, mean we can communicate with database, insert, update, select, alter, and delete records from database with JSP. Logic building with JSP, to print data, e.g., if we want to print good morning, good afternoon, good evening at particular slot of time, then we need to make a logic of time 12 am to 12 pm is good morning, 12pm after 4 pm is good after noon, and 4pm to 12 am is good evening. This can be done by if conditions to check current time and if time comes in any slot then print this message. Interact with user, with the help of forms like enquiry form, or submitting user’s data to server. Provide session to individual users. Increase security and privacy of user. JSP code can not view at client or browser. Web server response browser with plain HTML page; send no JSP code, so user can not get code or see JSP code.  JSP code can be put inside HTML code.  Both code work together, JSP code be embedded with scriptlet <% inside this jsp code %>

JSP Setup and Installation

JSP needs any web server; this can be tomcat by apache, WebLogic by bea, or WebSphere by IBM.All jsp should be deployed inside web server. We will use Tomcat server to run JSP, this Tomcat server can run on any platform like windows or linux. Install tomcat with this step

Installation of Tomcat on windows or Installation of Tomcat on linux.

Page 2: JSP Tutorial

Steps to Install tomcat web server on desktop

After successful installation of tomcat and JSP we need IDE integrated development environment. These IDE provide software development facilities, help lots in programming.  This IDE can contain source code editor, debugger, compiler, automatic generation code tools, and GUI view mode tools which show output at a run-time.We suggest using, dreamweaver from adobe, or eclipse with myEclipse plugin, NetBeans from sun. Or sun studio creator from sun. These IDEs help in Visual programmingAll provides, developer license and evaluation version to trial. Free IDE provided by easyeclipse.org and http://www.eclipse.org/europa/ .

File and folder structure of tomcat

Tomcat   Bin   Conf   Lib   Logs   Tmp +Webapps        Doc        Example        File        Host-manager        ROOT        jsp  +Work        Catalina

We will use our own application context, so have to make our own folder in webapps folder with jsp name. All jsp file should be copy in this jsp folder.

Simple JSP Example with Syntax

In tomcat, all JSP code should be copied (Deployed) into webapps folder and create own folder in webapps e.g jsp, in jsp folder copy all your jsp files. Remember, Java is case sensitive language.

1. JSP Example Simple Print on browser

jspExample1.jsp Output  <html><body><% out.print("Hello World!");%></body></html>

2. JSP Example Expression base print on browser

jspExample2.jsp Output 

<html><body>

Page 3: JSP Tutorial

<%="Hello World!"%></body></html>

3. JSP Example Current date print on browser

jspExample3.jsp Output 

<%@ page language="java" import="java.util.*" errorPage="" %><html><body>Current Date time: <%=new java.util.Date()%></body></html>

In above example, we need to add package of date import=”java.util.*”

Run this jsp file on browser with URL path

http://localhost:8080/jsp/jspExample1.jsp

JSP Variables

If you familiar with other programming language, java too has data type variable to identify what data to belongs. This variable stores information of data, and differentiate with others.  E.g. String, int, byte, long, float, double, boolean

Declare a variable

Declaration of variable in JSP is storing information of data. We need to define data’s type what is this. It may be a string, may be a int (integer), or float

1. String variable Example in JSPjspString.jsp Output 

<%@ page language="java" errorPage="" %><%String stVariable="this is defining String variable";%>

<html><body>String variable having value : <%=stVariable%></body></html>

2. Int variable Example in JSP

int can only having numeric values e.g 1,2,3,5

jspInt.jsp Output 

<%@ page contentType="text/html; charset=iso-8859-1" language="java" %><%

Page 4: JSP Tutorial

int iVariable=5;%>

<html><body>int variable having value : <%=iVariable%></body></html>

3. Long variable is same as int variable just long can store more bytes than int.

4. float variable Example in JSP

float variable can be having decimal numbers. E.g 5.6 ,23.455

jspFloat.jsp Output 

<%@ page contentType="text/html; charset=iso-8859-1" language="java" %><%float fVariable=567.345f;%>

<html><body>float variable having value : <%=fVariable%></body></html>

When you work on float variable don’t forget to add f character float fVariable=567.345f, otherwise it will get error of “Type mismatch: cannot convert from double to float”

5. double variable Example in JSPThis is same as float variable; it can store more bytes than float variable. In double we don’t need to put f character

6. Boolean variable Example in JSP

This is useful when we need to check condition. Let’s check in example

jspBoolean.jsp Output 

<%@ page contentType="text/html; charset=iso-8859-1" language="java" %><%boolean checkCondition=false;%>

<html><body> <% if(checkCondition==true) { out.print("This condition is true"); } else { out.print("This condition is false");

Page 5: JSP Tutorial

} %></body></html>

Output this jsp page “This condition is false”

Array in JSP

Array is used to store similar type of data in series. E.g. fruits nameFruits can be a mango, banana, and apple. Name of students in classroom denote to 10th Standard, Bachelor in science can have group of 30 to 40 students.Arrays can be String array, int array, and dynamic arrays are ArrayList, vector

We will look String array in this JSP

simpleArray.jsp Output<%@ page contentType="text/html; charset=iso-8859-1" language="java" %><%String[] stArray={"bob","riche","jacky","rosy"};%>

<html><body> <% int i=0; for(i=0;i<stArray.length;i++) { out.print("stArray Elements :"+stArray[i]+"<br/>"); } %></body></html>

This String Array has four elements. When we go through this array, have to use loop either for or while loop. We are using here for loop, First stArray.length give use total number of elements in array then we fetch one by one for loop iterator. Array starts from zero so here we have only 0,1,2,3 elements if we try to get stArray[4] it will throw

“java.lang.ArrayIndexOutOfBoundsException: 4”. stringArray.jsp Output 

<%@ page contentType="text/html; charset=iso-8859-1" language="java" %><%String[] stArray=new String[4];stArray[0]="bob";stArray[1]="riche";stArray[2]="jacky";stArray[3]="rosy";%>

<html><body> <% int i=0; for(i=0;i<stArray.length;i++) {

Page 6: JSP Tutorial

out.print("stArray Elements :"+stArray[i]+"<br/>"); } %></body></html>

Integer Array in JSP

intArray.jsp Output 

<%@ page contentType="text/html; charset=iso-8859-1" language="java" %><%int[] intArray={23,45,13,54,78};%>

<html><body> <% int i=0; for(i=0;i<intArray.length;i++) { out.print("intArray Elements :"+intArray[i]+"<br/>"); } %></body></html>

Dynamic arrays are automatically growable and reduceable according to per requirement. We don’t need to define it size when declaring array. It takes extra ratio of capacity inside memory and keeps 20% extra.

Vector

ArrayList

vectorArray.jsp Output 

<%@ page import="java.util.Vector" language="java" %><%Vector vc=new Vector();vc.add("bob");vc.add("riche");vc.add("jacky");vc.add("rosy");%>

<html><body> <% int i=0; for(i=0;i<vc.size();i++) { out.print("Vector Elements :"+vc.get(i)+"<br/>"); } %></body></html>

Page 7: JSP Tutorial

ArrayList

ArrayList also same just it is unsynchronized, unordered and faster than vector.

ArrayList.jsp Output 

<%@ page import="java.util.ArrayList" language="java" %><%ArrayList ar=new ArrayList();ar.add("bob");ar.add("riche");ar.add("jacky");ar.add("rosy");%>

<html><body> <% int i=0; for(i=0;i<ar.size();i++) { out.print("ArrayList Elements :"+ar.get(i)+"<br/>"); } %></body></html>

JSP Forms and User Input

JSP form is a way to interact with user input with web server or database server. In this, HTML form tag (e.g <input type=”text” name=”name”>, <input type=”password” name=”name”>, <input type=”radio” name=”name”>, <input type=”checkbox” name=”name”>) is used and values inside this form tag can be retrieved by request objects of JSP engine.

JSP Example of input text form

html.jsp Output  <%@ page contentType="text/html; charset=iso-8859-1" language="java" %><html><body><form name="frm" method="get" action="textInput.jsp"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="22%">&nbsp;</td> <td width="78%">&nbsp;</td> </tr> <tr> <td>Name Student </td> <td><input type="text" name="studentName"></td> </tr> <tr> <td>&nbsp;</td> <td><input type="submit" name="submit" value="Submit"></td> </tr> <tr> <td>&nbsp;</td>

Page 8: JSP Tutorial

<td>&nbsp;</td> </tr></table></form></body></html>

Get these form value in JSP

textInput.jsp Output 

<%@ page contentType="text/html; charset=iso-8859-1" language="java" %><%String studentNameInJSP=request.getParameter("studentName");%><html><body>Value of input text box in JSP : <%=studentNameInJSP%></body></html>

html.jsp is html form having input text box. This input box take input from user and send to action=”textInput.jsp” file. In textInput.jsp file, retrieved value from studentName form field with request.getParameter of JSP. Remember name of input text box should be same when fetching request parameter, otherwise it will give null value.

<input type="text" name="studentName">String studentNameInJSP=request.getParameter("studentName");

<form name="frm" method="get" action="textInput.jsp">In this form, method using get. Get work in query string and display in address bar of browser e.ghttp://localhost:8080/ textInput.jsp?studentName=Johny&submit=Submit

Second one is method=”post”<form name="frm" method="post" action="textInput.jsp">When using post method, user can not see what string variable is passing to server. In, Address bar we will see onlyhttp://localhost:8080/ textInput.jsp

 

JSP Example of radio button form

radio.jsp Output 

<%@ page contentType="text/html; charset=iso-8859-1" language="java" %><html><body><form name="frm" method="get" action="radioInput.jsp"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="22%">&nbsp;</td> <td width="78%">&nbsp;</td> </tr> <tr> <td>Active <input type="radio" name="active" value="Active"></td> <td>DeActive <input type="radio" name="active" value="DeActive"></td> </tr>

Page 9: JSP Tutorial

<tr> <td>&nbsp;</td> <td><input type="submit" name="submit" value="Submit"></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr></table></form></body></html>

radioInput.jsp

 

<%@ page contentType="text/html; charset=iso-8859-1" language="java" %><%String radioInJSP=request.getParameter("active");%><html><body>Value of radio button box in JSP : <%=radioInJSP%></body></html>

JSP Example of checkbox button in form

checkbox.jsp Output 

<%@ page contentType="text/html; charset=iso-8859-1" language="java" %><html><body><form name="frm" method="get" action="checkboxInput.jsp"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="22%">&nbsp;</td> <td width="78%">&nbsp;</td> </tr> <tr> <td>State <input type="checkbox" name="state" value="state"></td> <td>City <input type="checkbox" name="city" value="city"></td> </tr> <tr> <td>&nbsp;</td> <td><input type="submit" name="submit" value="Submit"></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr></table></form></body></html>

checkboxInput.jsp

Page 10: JSP Tutorial

 

<%@ page contentType="text/html; charset=iso-8859-1" language="java" %><%String checkboxStateInJSP=request.getParameter("state");String checkboxCityInJSP=request.getParameter("city");%><html><body>Value of checkbox in JSP : <%=checkboxStateInJSP%> <%=checkboxCityInJSP%>

</body></html>

Form Validation Javascript with JSP

We have discussed lot about JSP, JSP is server side scripting language as we know, but when we do practical real world programming we need more than JSP. Suppose we have an html form (Html form contain only html tags, No JSP code) having username text field, and password field. Before submitting page to web server, it should be validate HTML field data. This validation can be done on client side instead directly to server. It should be done on client side, because it is very faster than server validation. If user data is not of specified range of standard validation program, it should show error at client browser of user. This form will not jump to action page (server) until it fully validated.  

Let’s see in example

formValidation.jsp Output   

<%@ page contentType="text/html; charset=iso-8859-1" language="java" %><html><head><script>function validateForm(){ if(document.frm.username.value=="") { alert("User Name should be left blank"); document.frm.username.focus(); return false; } else if(document.frm.pwd.value=="") { alert("Password should be left blank"); document.frm.pwd.focus(); return false; }}</script></head><body><form name="frm" method="get" action="validateInput.jsp" onSubmit="return validateForm()"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="22%">&nbsp;</td> <td width="78%">&nbsp;</td> </tr>

Page 11: JSP Tutorial

<tr> <td>UserName </td> <td><input type="text" name="username" /></td> </tr> <tr> <td>Password</td> <td><input type="text" name="pwd" /></td> </tr> <tr> <td>&nbsp;</td> <td><input type="submit" name="submit" value="Submit"></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr></table></form></body></html>

When we submit this form to web server, first it will check and validate. onSubmit="return validateForm()" event check validateForm() function in javascript, and if any field find blank it will throw error alert on browser. This submit only when validateForm() function return true. This results in jump to next form validateInput.jsp of JSP page

JSP Cookies

What is a cookie?

Cookie a small data file reside in user’s system. Cookie is made by web server to identify users. When user do any request send to web server and web server know information of user by these cookie. After process request, web server response back to request by knowing through this cookie. JSP provides cookie classes, javax.servlet.http.Cookie, by this classes we can create and retrieve cookie. Once we set value in cookie, it lived until cookie gets expired. Cookie plays a big role in session, because maximum session is tracked by cookie in JSP.

1. JSP Example of creating Cookie

createCookie.jsp Output  <%@ page contentType="text/html; charset=iso-8859-1" language="java" %><html><body><form name="frm" method="get" action="createNewCookie.jsp"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="22%">&nbsp;</td> <td width="78%">&nbsp;</td> </tr> <tr> <td>Cookie value Set </td> <td><input type="text" name="cookieSet" /></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td>

Page 12: JSP Tutorial

</tr> <tr> <td>&nbsp;</td> <td><input type="submit" name="submit" value="Submit"></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr></table></form></body></html>

createNewCookie.jsp

 

<%@ page language="java" import="java.util.*"%><%String cookieSet=request.getParameter("cookieSet");

Cookie cookie = new Cookie ("cookieSet",cookieSet);response.addCookie(cookie);%>

<html><head><title>Cookie Create Example</title></head><body> <% Cookie[] cookies = request.getCookies(); for (int i=0; i<cookies.length; i++) { out.println(cookies[i].getName()+" : "+cookies[i].getValue()+"<br/>"); } %></body></html>

 

Cookie cookie = new Cookie ("cookieSet",cookieSet);

We are creating new object of cookie class.Here new Cookie(“Key”, “value”);Then we are adding in cookie of response object.response.addCookie(cookie); This is adding in cookie object new data.

Expire JSP cookie

Cookie cookie = new Cookie ("cookieSet",cookieSet);

cookie setMaxAge(0);

This will expire cookie.,with 0 second. We can set cookie age who long is reside for user.

Page 13: JSP Tutorial

Retrieve cookie from JSP

Cookie is in array object, we need to get in request.getCookies() of array.

Cookie[] cookies = request.getCookies();

for (int i=0; i<cookies.length; i++) {      out.println(cookies[i].getName()+" : "+cookies[i].getValue()+"<br/>");}

JSP Session Object

Session object is medium to interact with client and server. Session is a connection between user and server, involving exchange of information between user’s computer and server. Server knows information about each other by these session object. Web server put information of user in session object and whenever it needs information gets it from these session objects. This session object stores information in key value pair, just like hashtable. Today programming without session cannot thinkable. Most of web application is user based, somewhat use transaction (credit card, database transaction), shopping cart, email, and this needs session. Web server should know who is doing this transaction. This session object helps to differentiate users with each other, and increase application’s security. Every user have unique session, server exchange information with session objects until it get expired or destroyed by web server.

When JSP Session use

Mostly session is work with user base application, when login screen is used then set session if login is successful. It set for maximum time provided by web server or defined by application.

When JSP Session destroys

When user has done their work and want to close browser, it should be expire or destroy forcefully by user, ensure no other person can use his session.

JSP Store and Retrieve Session Variables

JSP Example of Creating session and retrieving session

session.jsp Output  <%@ page contentType="text/html; charset=iso-8859-1" language="java" %><html><body><form name="frm" method="get" action="sessionSetRetrieve.jsp"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="22%">&nbsp;</td> <td width="78%">&nbsp;</td> </tr> <tr> <td>Session value Set </td> <td><input type="text" name="sessionVariable" /></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td>

Page 14: JSP Tutorial

<td><input type="submit" name="submit" value="Submit"></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr></table></form></body></html>sessionSetRetrieve.jsp Output   

<%@ page language="java" import="java.util.*"%><%String sessionSet=request.getParameter("sessionVariable");session.setAttribute("MySession",sessionSet);/// String getSessionValue= (String)session.getAttribute("sessionSet"); //this is use for session value in String data%>

<html><head><title>Cookie Create Example</title></head><body>Session : <%=(String)session.getAttribute("MySession")%></body></html>

session.setAttribute("MySession",sessionSet) this is use to set new session variable. If we need to retrieve session variable, have to use session.getAttribute. In this we have to get it by session variable name here we are using MySession is session variable as key.

session.setMaxInactiveInterval(2700);

session.setMaxInactiveInterval(2700), this use to set maximum session time. 2700 is time in number. In this period, if user don’t do anything session get expired automatically.

 

Remove JSP Session Variables or Expire JSP Session

When session is no long needed, should be removed forcefully by user. This can be done by calling session method of invalidate methodsession.invalidate();

session.invalidate();

This method expires session for current user, who request for log out.

New session can be find by isNew() method of session, when first time session is created, that is new session.

session.isNew();

Loop, Contents Collection, iterator, conditional checks

JSP provides loop and conditional checks. Loop provides us repetition of content without writing again and again same content.

Page 15: JSP Tutorial

Loop in JSP can be for, while, do whileLook examples of these loops for loop in JSP

Example of for loop in JSP

for.jsp

<%@ page language="java" import="java.sql.*" %><html><head><title>For loop in JSP</title></head>

<body><%for(int i=0;i<=10;i++){ out.print("Loop through JSP count :"+i+"<br/>");}%></body></html>

Example of while loop in JSP

while.jsp

 

<%@ page language="java" import="java.sql.*" %><html><head><title>while loop in JSP</title></head>

<body><%int i=0;while(i<=10){ out.print("While Loop through JSP count :"+i+"<br/>"); i++; }%></body></html>

Example of do-while loop in JSP

doWhile.jsp

 

<%@ page language="java" import="java.sql.*" %><html><head><title>do-while loop in JSP</title></head>

Page 16: JSP Tutorial

<body><%int i=0;do{ out.print("While Loop through JSP count :"+i+"<br/>"); i++; }while(i<=10);%></body></html>

Examples of conditional and unconditional checks in JSPConditional check means check condition and if it satisfies condition then block below execute otherwise block will not execute. Unconditional checks those check that don’t care about condition and execute in every case. Conditional checks are if, if-else, while. These condition use conditional operator like < > or && or || (greater than, less than, and, or condition)

Example of if-else condition

ifelse.jsp

 

<%@ page language="java" import="java.sql.*" %><html><head><title>while loop in JSP</title></head>

<body><%String sName="joe";String sSecondName="noe"; if(sName.equals("joe")){ out.print("if condition check satisfied JSP count :"+sName+"<br>"); }

if(sName.equals("joe") && sSecondName.equals("joe")) { out.print("if condition check if Block <br>"); } else { out.print("if condition check else Block <br>"); }%></body></html>JSP Application Object

JSP application is computer program designed for specific task and solution. This application can contain JSP, Servlet, xml, class files, and jar files. Suppose  a shopping store has a software to sale, buy, purchase, shipping products, payments, upload new products, all these belongs to single store. This single unit is called application. All files (JSP) work together to perform specific task.The application object is used to store and retrieve from any page of JSP or any where in application scope. This is

Page 17: JSP Tutorial

something like session object, but session object is made for per user. And no other user can access session object of other user. Application object is available to all, can be access by all users, because it is single object.

Store and Retrieve Application Variables

JSP use in application objects ServletContext object. This object also contain values of session object and available to all. Another one is application object. We will see in example of this application object in JSP

applicationObject.jsp

<%@ page language="java" import="java.sql.*" %><%String parameterValue="This is application object"; getServletContext().setAttribute("ApplicationValue","This is my Name"); String getValueApplcation=(String)getServletContext().getAttribute("ApplicationValue"); application.setAttribute("ApplcationVariable",parameterValue); String getApplicationVariable=(String)application.getAttribute("ApplcationVariable");%><html><head><title>Applcation object in JSP</title></head>

<body>The value of getting getServletContext application object <%=getValueApplcation%><br>This is application object :<%=getApplicationVariable%></body></html>

Application object handling is same as session object handling. This is done by servlet container

Method Return Description

equals(Object obj) Objects Matching objects

getAttribute(String str) Objects Getting value through application objects

getAttributeNames() Enumeration an Enumeration of attribute names

getContext(String str) ServletContext  

getContextPath() String  

getInitParameter(String str) String  

getInitParameterNames() Enumeration  

getMajorVersion() int  

getMimeType(String str) String  

getMinorVersion() int  

getNamedDispatcher(String str) RequestDispatcher  

Page 18: JSP Tutorial

getRealPath(String str) String  

getRequestDispatcher(String str) RequestDispatcher  

getResource(String str) URL  

getResourceAsStream(String str) InputStream  

getResourcePaths(String str) Set  

log(String str) void  

log(String str, Throwable t) void  

removeAttribute(String str) void  

setAttribute(String str, Object obj) void  

toString() String  

JSP Including Files

The include directive is used to include any file’s content into other desired file. This process is useful when need a separate header, footer, menu bar, or any common content need to reuse on other pages.

This JSP include can be static or dynamic.Static include in JSP does include one file content into desired file at translation time, after that JSP page is compiled.

Dynamic include in JSP

Dynamic include is used in javabean as <jsp:include>. This include execute first file and then output of this file include in desired file.

Include is useful for common and reusable code function method, variable.

 

Syntax for Including FilesLet take a example of include header and footer in home JSP page

home.jsp

<%@ page language="java" import="java.sql.*" %><html><head><title>Include example of JSP</title></head>

<body><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td colspan="3" align="center"><%@ include file="header.jsp"%></td> </tr> <tr> <td width="16%" height="138">&nbsp;</td> <td width="65%" align="center">This is Home page and having header and footer included by include of JSP </td> <td width="19%">&nbsp;</td> </tr> <tr> <td colspan="3" align="center"><%@ include file="footer.jsp"%></td> </tr></table>

Page 19: JSP Tutorial

</body></html>

Including two JSP pages in home page then we need to make two more files.

header.jsp

 

<%@ page language="java" import="java.sql.*" %>

<html><head><title>Header page</title><style>.st{ background-color:#CBE0E7; font-weight:bold; text-align:center}</style></head>

<body><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td class="st">Home</td> <td>&nbsp;</td> <td class="st">Products</td> <td>&nbsp;</td> <td class="st">Services</td> <td>&nbsp;</td> <td class="st">Company Profile</td> <td>&nbsp;</td> <td class="st">Register</td> <td>&nbsp;</td> <td class="st">Login</td> <td>&nbsp;</td> <td class="st">About Us</td> <td>&nbsp;</td> </tr></table>

</body></html>

Now footer file need to include

footer.jsp

 

<%@ page language="java" import="java.sql.*" %><html><head><title>Footer page</title></head>

Page 20: JSP Tutorial

<body><div align="center">Home || Products || Services || Login || About Us</div></body></html>

 

<%@ include file ="relativeURL" %>

Relative URL only can be used to include file. We can not use pathname from http protocol or port or any domain name.

No path like thishttp://domainName:8080/

Only include pathname“Test.jsp”“Header.jsp”“/header.jsp”

“/common/header.jsp”

Response object in JSP

As we know the response, response is a process to responding against it request. Response Object in JSP is used to send information, or output from web server to the user. Response Object sends output in form of stream to the browser. This can be redirecting one file to another file, response object can set cookie, set ContentType, Buffer size of page, caching control by browser, CharSet, expiration time in cache.

Response object tells browser what output has to use or display on browser, and what stream of data contain PDF, html/text, Word, Excel.

Method Return Description

addCookie(Cookie cookie) void Add specified cookies to response object 

addDateHeader(String name,long date)

void Adds response header with given name and date value

addHeader(String name,String value)

void Adds response header with given name and value

encodeRedirectURL(String URL) String Encode specified URL for sendRedirect method

encodeURL(String URL) String Encode specified URL with session ID, if not unchanged URL return

flushBuffer() void Forces any content in buffer to be written in client

getBufferSize() int Returns actual buffer size used for response

getCharacterEncoding() String Returns character encoding for page in response MIME type charset=iso-8859-1

getContentType() String Returns MIME type used for body in response text/html;

getOutputStream() ServletOutputStream Returns ServletOutputStream binary data stream to written in response

getWriter() PrintWriter Returns a PrintWriter object that can send character text to client

isCommitted() boolean Returns a Boolean, if response has been commited

resetBuffer() void Clear content in buffer of response without clearing header and status

Page 21: JSP Tutorial

sendRedirect(String location) void Sends a redirect response to client with redirect specified URL location. Contain Relative path

setBufferSize(int size) void Set a preferred buffer size for the body of response

setCharacterEncoding(String charset)

void Set a character encoding for send to client response body charset=iso-8859-1

setContentLength(int length) void Set a length of content body in response

setContentType(String contentType) void Set a content Type of response being sent to client, if response is yet not committed

setHeader(String name, String value)

void Set a response header with given name and value

Example of ContentType in JSP response object

setContentType.jsp

<%@ page language="java" %><%response.setContentType("text/html");%><html><head><title>Response object set Content type</title></head>

<body>This is setting content type of JSP page</body></html>

if documentation is in PDF format then setContentType as

<% response.setContentType("application/pdf"); %>

For Microsoft word document

<%response.setContentType("application/msword");%>

For Microsoft excel document

<%response.setContentType("application/vnd.ms-excel");%>

or

<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>

Example of control page into cache

cacheControl.jsp

 

<%@ page language="java" %>

Page 22: JSP Tutorial

<%response.setHeader("Cache-Control","no-cache"); /*--This is used for HTTP 1.1 --*/response.setHeader("Pragma","no-cache"); /*--This is used for HTTP 1.0 --*/response.setDateHeader ("Expires", 0); /*---- This is used to prevents caching at the proxy server */%><html><head><title>Response object in cache controlling</title></head>

<body>This is no cache, Can test this page by open this page on browser and then open any other website after press back button on browser, if cacheControl.jsp is reload, it means it is not cached</body></html>

Example of  sendRedirect of Response Object

sendRedirect.jsp

 

<%@ page language="java" %><%response.sendRedirect("http://yahoo.com");/// response.sendRedirect("YouCanSpecifyYourPage.jsp");%><html><head><title>Response object Send redirect</title></head>

<body>This page redirects to specified URL location</body></html>

Request object

Request Object in JSP is most usable object. This request object take information from the user and send to server, then this request is proceed by server and response back to user. The process starts when we write address of any page in browser and press enter to page. Request object can be used in

Query String

When using query String, data is passed to server in form of URL string. This URL string is visible on browser and anyone can see it. E.g

http://www.domainName.com/concerts.jsp ?id=9&type=Exhibition

This is query string after page name. id is key and 9 is value. This query String either self made or can send by form property. This can get with request.getParameter(“Key”) method. This will give us 9.

Query String self made example in JSP

Page 23: JSP Tutorial

queryString.jsp

<%@ page language="java" import="java.sql.*" %><html><head><title>Query String in JSP</title></head>

<body><a href="queryString.jsp?id=9&name=joe">This is data inside query string</a><%String queryString=request.getQueryString();out.print("<br>"+queryString);%></body></html>

We can get single id and value instead of using getQueryString method of request.

Query String example with getParameter

queryStringParameter.jsp

 

<%@ page language="java" import="java.sql.*" %><html><head><title>Query String in JSP</title></head>

<body><a href="queryString.jsp?id=9&name=joe">This is data inside query string</a><%String queryStringVariable1=request.getParameter("id");String queryStringVariable2=request.getParameter("name");out.print("<br>"+queryStringVariable1);out.print("<br>"+queryStringVariable2);%></body></html>

Form Form is most important part of request object in JSP. It takes value from user and sends it to server for further processing. Suppose we have a registration form, and value in field have to save in database. We need to get these values from browse and get in server side; once we get this value in java, we can save in database through JDBC or any database object. Form in html has two properties get or post method, get method send information to server in query string. Post method doesn’t send data in query string in to server. When data is sent to server it is not visible on browser. Post method as compare to get method is slower. Get method has a limit of string length in some kilobytes.

Form Example in JSP with request object

formGetMethod.jsp

 

<%@ page language="java" import="java.sql.*" %>

Page 24: JSP Tutorial

<%String queryStringVariable1=request.getParameter("name");String queryStringVariable2=request.getParameter("className");%><html><head><title>Query String in JSP</title></head>

<body><%

out.print("<br>Field 1 :"+queryStringVariable1);out.print("<br>Field 2 :"+queryStringVariable2);

%>

<form method="get" name="form1">Name <input type="text" name="name"> <br><br>Class <input type="text" name="className"> <br><br><input type="submit" name="submit" value="Submit"></form></body></html>

Request object with Check box form in JSP

formGetParameterValues.jsp

 

<%@ page language="java" import="java.sql.*" %><%String queryStringVariable1=request.getParameter("name");String[] queryStringVariable2=request.getParameterValues("className");%><html><head><title>Query String in JSP</title></head>

<body><%try{ out.print("<br>Field 1 :"+queryStringVariable1); for(int i=0;i<=queryStringVariable2.length;i++){ out.print("<br>Check box Field "+i+" :"+queryStringVariable2[i]); }}catch(Exception e){ e.printStackTrace();}

%><br><br>

Page 25: JSP Tutorial

<form method="get" name="form1">Name <input type="text" name="name"> <br><br> class 1 <input type="checkbox" name="className" value="c1"> class 2 <input type="checkbox" name="className" value="c2"><br><br><input type="submit" name="submit" value="Submit"></form></body></html>

Request object with radio button form in JSP

formGetRadio.jsp

 

<%@ page language="java" import="java.sql.*" %><%String inputVariable=request.getParameter("name");String[] radioVariable=request.getParameterValues("className");%><html><head><title>Query String in JSP</title></head>

<body><%try{ out.print("<br>Field 1 :"+inputVariable); for(int i=0;i<=radioVariable.length;i++){ out.print("<br>Check box Field "+i+" :"+radioVariable[i]); }}catch(Exception e){ e.printStackTrace();}

%><br><br><form method="get" name="form1">Name <input type="text" name="name"> <br><br> class 1 <input type="radio" name="className" value="c1"> class 2 <input type="radio" name="className" value="c2"><br><br><input type="submit" name="submit" value="Submit"></form></body></html>

CookiesCookies use request object to get values through in cookie file. It uses request.getCookies() method to get cookie and return in cookie[] array.

 

Page 26: JSP Tutorial

Server variable

Server variable give server information or client information. Suppose we need to get remote client IP address, browser, operating system, Context path, Host name any thing related to server can be get using request object in JSP.

Server variable example in JSP

serverVariable.jsp

 

<%@ page contentType="text/html; charset=utf-8" language="java" %><html><head><title>Server Variable in JSP</title></head>

<body>Character Encoding : <b><%=request.getCharacterEncoding()%></b><br />

Context Path : <strong><%=request.getContextPath()%></strong><br />

Path Info : <strong><%=request.getPathInfo()%></strong><br />

Protocol with version: <strong><%=request.getProtocol()%></strong><br />

Absolute Path file:<b><%=request.getRealPath("serverVariable.jsp")%></b><br/>

Client Address in form of IP Address:<b><%=request.getRemoteAddr()%></b><br/>

Client Host : <strong><%=request.getRemoteHost()%></strong><br />

URI : <strong><%=request.getRequestURI()%></strong><br />

Scheme in form of protocol : <strong><%=request.getScheme()%></strong><br />

Server Name : <strong><%=request.getServerName()%></strong><br />

Server Port no : <strong><%=request.getServerPort()%></strong><br />

Servlet path current File name : <b><%=request.getServletPath()%></b><br /></body></html>

Properties and method of Request objects

Method Return Description

equals(Object obj) Objects Matching objects

getAttribute(String str) Objects Returns the String associated with name in the request scope

Page 27: JSP Tutorial

getAttributeNames() Enumeration an Enumeration of attribute names

getAuthType() String  

getCharacterEncoding() String Returns character encoding for page in request MIME type charset=iso-8859-1

getContentLength() int get length of content body in request

getContentType() String  

getContextPath() String  

getCookies() Cookie[]  

getDateHeader(String str) long get request header with given name and date value

getHeader(String str) String get request header with given name and value

getHeaderNames() Enumeration  

getHeaders(String str) Enumeration  

getInputStream() ServletInputStream  

getIntHeader(String str) int  

getLocalAddr(String str) String  

getLocale(String str) Locale  

getLocales() Enumeration  

getLocalName() String  

getLocalPort() int  

getMethod() String  

getParameter(String str) String  

getParameterMap() Map  

getParameterNames() Enumeration  

getParameterValues(String str) String  

getPathInfo() String  

getPathTranslated() String  

getProtocol() String  

getQueryString() String  

getReader() BufferedReader  

(D) getRealPath() String  

getRemoteAddr() String  

getRemoteHost() String  

getRemotePort() int  

getRemoteUser() String  

getRequestDispatcher(String str) RequestDispatcher  

getRequestedSessionId() String  

getRequestURI() String  

getRequestURL() StringBuffer  

getScheme() String  

getServerName() String  

getServerPort() int  

getServletPath() String  

getSession() HttpSession  

Page 28: JSP Tutorial

getSession(boolean true|false) HttpSession  

getUserPrincipal() Principal  

hashCode() int  

isRequestedSessionIdFromCookie() boolean  

isRequestedSessionIdFromURL() boolean  

isRequestedSessionIdValid() boolean  

isSecure() boolean  

isUserInRole() boolean  

removeAttribute(String str) void  

setAttribute(String str, Object obj) void  

setCharacterEncoding(String str) void Set a character encoding for send to client request body charset=iso-8859-1

toString() String  

JSP Error Handling

JSP is very mature about handling errors. JSP use Exception handling classes for dealing with error. Every program or code can throw an error; to rectify these errors should know what real problem is. These error classes in JSP tell us what exact problem is where we have to do modify in our code to remove error. This give us detail and deep information of error, can be display on particular error page or put it in error object System.err. JSP provide try catch block to hand run time exception. JSP have property in

 

<%@ page isErrorPage="true" %><%@ page language="java" errorPage="error.jsp" %>

try catch block is important feature to caught exception in JSP page, do according to programmer specification.

Example of try catch Error Handling in JSP

tryCatch.jsp

 

<%@ page language="java" errorPage="" %><html><head><title>Error Handling by try catch block in JSP</title></head>

<body><%try{ int a=0; int b=10; int c=b/a;}catch(Exception e){ e.printStackTrace(); /// This will give detail information of error occur out.print("Error caught by Catch block is : "+e.getMessage());}%></body>

Page 29: JSP Tutorial

</html>

This will show Error caught by Catch block is :/ by zerojava.lang.ArithmeticException: / by zero, a number can be division by zero digits; it is caught by arithmeticException and prints this error.e.printStackTrace(); give us detail error information and can see at tomcat console mode or at logs folder in catalina.out file.Sometimes error handling is useful when we are inserting user data into a registration table with unique field of UserId. If we enter duplicate UserId, sqlException will throw a duplicate row field error. User can know, this UserId is already exists in database.

JSP can use customized error page by setting errorPage="error.jsp".

Example of Error page in JSP

errorPage.jsp

<%@ page language="java" errorPage="" %><html><head><title>Error Handling by try catch block in JSP</title></head>

<body><%try{ int a=0; int b=10; int c=b/a;}catch(Exception e){ e.printStackTrace(); /// This will give detail information of error occur out.print("Error caught by Catch block is : "+e.getMessage());}%></body></html>

second page is error page

error.jsp

<html><head><title>Caught Error in JSP Page</title></head>

<body>Error is found on this page(This is own customized error page)</body></html>

JSP File handling Object

JSP file handling is used to handle file in server and manipulate file related task, e.g copying file to another file, upload images or any file to web server, delete existing file from server, creating new file in web server.

Page 30: JSP Tutorial

In this file handling we have to use input and output of java classes. This can be File, InputStream or with BufferedInputStream. Let take example to understand better.

Example Reading text file in JSP

fileRead.jsp

<%@ page language="java" import="java.io.*" errorPage="" %><html><head><title>File Handling in JSP</title></head>

<body><%String fileName=getServletContext().getRealPath("jsp.txt");

File f=new File(fileName);

InputStream in = new FileInputStream(f);

BufferedInputStream bin = new BufferedInputStream(in);

DataInputStream din = new DataInputStream(bin);

while(din.available()>0) { out.print(din.readLine()); }in.close();bin.close();din.close();%></body></html>

Make a text file name jsp.txt and put in same folder where this jsp file is exists.

Create new file through JSP

createNewFile.jsp

 

<%@ page language="java" import="java.io.*" errorPage="" %><html><head><title>File Handling in JSP</title></head>

<body><%String fileName=getServletContext().getRealPath("test.txt");

File f=new File(fileName);

f.createNewFile();

Page 31: JSP Tutorial

%></body></html>

Examples of Delete file in JSP

This example delete file from defined path.

 

deleteFile.jsp

 

<%@ page language="java" import="java.io.*" errorPage="" %><html><head><title>File Handling in JSP</title></head>

<body><%String fileName=getServletContext().getRealPath("test.txt");//// If you know path of the file, can directly put path instead of ///filename e.g c:/tomcat/webapps/jsp/myFile.txtFile f=new File(fileName);

boolean flag=f.delete(); ///return type is boolean if deleted return true, otherwise false

%></body></html>

Can check file exists or not is directory, or file

Example of checking file type for existing, file or as directory

fileType.jsp

<%@ page language="java" import="java.io.*" errorPage="" %><html><head><title>File Handling in JSP</title></head>

<body><%String fileName=getServletContext().getRealPath("jsp.txt");

File f=new File(fileName);

out.print("File exists : "+f.exists()+"<br>");/// return type is boolean exists return true else false

out.print("File is Directory : "+f.isDirectory()+"<br>");/// return type is boolean exists return true else false

Page 32: JSP Tutorial

out.print("File is File : "+f.isFile()+"<br>");/// return type is boolean exists return true else false

out.print("File is creation Date : "+f.lastModified()+"<br>");/// return type is boolean exists return true else false

%></body></html>

Example of Rename file in JSP

renameFile.jsp

<%@ page language="java" import="java.io.*" errorPage="" %><html><head><title>File Handling in JSP</title></head>

<body><%String fileName=getServletContext().getRealPath("jsp.txt");

File f=new File(fileName);

boolean flag=f.renameTo(new File(getServletContext().getRealPath("myJsp.txt")));

%></body></html>

JSP Action tags

Action tags in JSP are used to perform action on particular page. This Action tags are

1. include2. forward3. useBean

Action tags are used to transfer control from one parent page to another particular page. Action tags are also used in server side inclusion for using javaBean property methods directly in JSP page without using core java code.

1. include action tag

Include action tag is almost similar to include directive. This include can be static or dynamic. This include file is first compiled and output of this file is inserted with parent file.

Static include

<jsp:include page="relativeURL" flush="{true|false}" />

Dynamic include

<jsp:include page="relativeURL" flush="{true|false}"> <jsp:param name="parameterName" value="parameterValue" /></jsp:include>

Page 33: JSP Tutorial

JSP Action tags include can be static or dynamic. Static include is simple and Look like as

<jsp:include page="header.jsp" />

Example of static include in Action tags

header.jsp

<%@ page language="java" import="java.sql.*" %>

<html><head><title>Header page</title><style>.header{ background-color:#CBE0E7; font-weight:bold; text-align:center}</style></head>

<body><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td class="header">Home</td> <td>&nbsp;</td> <td class="header">Products</td> <td>&nbsp;</td> <td class="header">Services</td> <td>&nbsp;</td> <td class="header">Company Profile</td> <td>&nbsp;</td> <td class="header">Register</td> <td>&nbsp;</td> <td class="header">Login</td> <td>&nbsp;</td> <td class="header">About Us</td> <td>&nbsp;</td> </tr></table>

</body></html>

staticAction.jsp

<%@ page language="java" import="java.io.*" errorPage="" %><html><head><title>Static include in Action tags JSP</title></head>

<body>

Page 34: JSP Tutorial

<jsp:include page="header.jsp" /></body></html>

Example of dynamic include action tag in JSP with param tag

header.jsp

<%@ page language="java" %>

<html><head><title>Header page</title><style>.header{ background-color:#CBE0E7; font-weight:bold; text-align:center}</style></head>

<body><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td class="header"><%=request.getParameter("variable1")%></td> <td>&nbsp;</td> <td class="header"><%=request.getParameter("variable2")%></td> <td>&nbsp;</td> <td class="header"><%=request.getParameter("variable3")%></td> <td>&nbsp;</td> <td class="header"><%=request.getParameter("variable4")%></td> <td>&nbsp;</td> <td class="header"><%=request.getParameter("variable5")%></td> <td>&nbsp;</td> <td class="header"><%=request.getParameter("variable6")%></td> <td>&nbsp;</td> <td class="header"><%=request.getParameter("variable7")%></td> <td>&nbsp;</td> </tr></table>

</body></html>

dynamicAction.jsp

<%@ page language="java" errorPage="" %><html><head><title>Dynamic include in Action tags JSP</title></head>

<body><jsp:include page="header.jsp">

Page 35: JSP Tutorial

<jsp:param name="variable1" value="Home" /> <jsp:param name="variable2" value="Products" /> <jsp:param name="variable3" value="Services" /> <jsp:param name="variable4" value="Company Profile" /> <jsp:param name="variable5" value="Register" /> <jsp:param name="variable6" value="Login" /> <jsp:param name="variable7" value="About Us" /></jsp:include></body></html>

2. Forward action tag

Forward action tag in JSP transfer the control of one JSP page to another JSP with specify URL. Forward also can be static or dynamic as include action. When we use param tags, it is dynamic forward with having values. Static forward is simple forward without having param tags.Forward is used when we need to jump from one page to another if error occur or if work is completed in parent page. E.g we are inserting data in database with using insert statement. After finishing insert, control of page should go to successful insertion of data in database page or failure of insertion go to error page. This can be done forward action tag. <jsp:forward page="relativeURL | or <%= expression %>" />

e.g

<jsp:forward page="success.jsp" />

This is static forward, dynamic forward

<jsp:forward page="relativeURL"> &l use for Java Beans. First we know little about Java Bean what is Java Bean, Java Bean is simple java class having number of method and can have business logic code inside method of Java Bean. These components can be reusable by different number of JSPs as per requirement. Java bean can have simple getter setter method or complex business logic. Java beans are not more than a plain java class and help to separate a design code and logic code. Java bean need to compile manually as java compiler does.

Simple java bean example java bean should copy in webapps/jsp/WEB-INF/classes/com/myApp of tomcat

Example of java bean with useBean action tag in JSP

FirstBean.java

package com.myApp;

Page 36: JSP Tutorial

public class FirstBean { public String sName=null; public int iClass=0; public int iMarks=0; public int iMaxMarks=0; public String getSName() { return sName; } public void setSName(String name) { sName = name; } public int getIClass() { return iClass; } public void setIClass(int class1) { iClass = class1; } public int getIMarks() { return iMarks; } public void setIMarks(int marks) { iMarks = marks; } public int getIMaxMarks() { return iMaxMarks; } public void setIMaxMarks(int maxMarks) { iMaxMarks = maxMarks; } public double getDPercent() { double dPer=(double)(iMarks*100)/iMaxMarks; return dPer; } }

useBean.jsp

<%@ page language="java" errorPage="" %><jsp:useBean id="myLog" class="com.myApp.FirstBean" scope="page"/>

<% myLog.setSName("Amit"); myLog.setIClass(10); myLog.setIMarks(89); myLog.setIMaxMarks(120);%>

Page 37: JSP Tutorial

<html><head><title>useBean Action tags JSP</title></head>

<body><%=myLog.getSName() %> Percent is <%=myLog.getDPercent()%></body></html>

scope of bean can

1. page (attribute will work in same page)

2. application (attribute will work in whole application)

3. session (attribute will work in session)

4. request (attribute will work in request one time and destroy)

This useBean create instance of java bean class. The attribute of bean myLog get object of FirstBean after instantiate.

JSP implicit objects

Implicit objects are provided by JSP itself, we don’t need to define it we can simply use these objects by setting values and attributes. JSP container does all work like instantiating, defining and maintenance.

JSP provide following implicit objects

1. out

   out is  javax.servlet.jsp.JspWriter class use for printing. Out is Output Stream use response.getWriter()  to send output to client

 

<% out.write("This is use for print output stream on client");%>

2. page

   page is used by java.lang.Object class. Page is instance of  JSP page’s Servlet.

Page 38: JSP Tutorial

<% Object page = this; %>

3. pageContext

    pageContext instance that contains all data’s information, which is associated with JSP   page. This helps to

access attribute and other field’s object set in JSP page. pageContext is in javax.servlet.jsp.PageContext class. pageContext is to managed various scope of attribute in shared information object.Method of pageContext are following: Method Return Description

pageContext.findAttribute(String Name) Object Search for named attribute in JSP page Request,session, application scope  

pageContext.forward(String relativeURLPath) void This method is used to redirect or forward the current ServletRequest or ServletResponse to another active component

pageContext.getAttribute(String Name) Object Returns the object associated with name in the page scope

pageContext.getAttributesScope(String Name)

int Get the scope where a given attribute is defined

pageContext.getErrorData() ErrorData Provide access to error information

pageContext.getException() Exception

Get current value of the exception Object

pageContext.getOut() JspWriter

Get current value of out object

pageContext.getRequest() ServletRequest

Get current value of request object

pageContext.getResponse() ServletResponse Get current value of response object

pageContext.getServletConfig() ServletConfig

Get any initialization parameters and startup configuration for this servlet

pageContext.getServletContext() ServletContext Gets the context from the servlet's ServletConfig object

pageContext.getSession() HttpSession Return the current value of session object

4. request

    The HttpServletRequest object that javax.servlet.http.HttpServletRequest interface is provided to access request objects in JSP. The HTTP request is send to server through request object. More example request object reference

5. response

The HttpServletResponse object that javax.servlet.http.HttpServletResponse interface is provided to send response object in JSP. The HTTP response is send to client through response object   More example response object reference

6. session

    Session object is used to track information about a user, session is interface and maintain by HttpSession javax.servlet.http.HttpSession.More example of session object reference

7. config

Page 39: JSP Tutorial

    config object is related to get servlet’s configuration information. It is in javax.servlet.ServletConfig interface. Servlet configuration object is used to pass information of servlet to Servlet container during initialization of servlet. This is defined in web.xml file with <init-param> and method is used to get getServletConfig() <servlet> <servlet-name>ServletName</servlet-name> <servlet-class>com.myapp.servlet.ServletName</servlet-class> <init-param> <param-name>dbUserName</param-name> <param-value>root</param-value> </init-param> </servlet>

Method use to get init param is getInitParameter() to get value inside <param-value> and getInitParameterNames() to get name of <param-name>

8. application

    Application object is used to share information for all JSPs and Servlets in the application context. Application is in javax.servlet.ServletContext. More example of application object reference

9. exception

 Exceptions are condition that can be caught and recovered from it. If exception is not caught it should throw on error page. Exception when throw on error page it should be isErrorPage= true at in directive page. <%@ page errorPage="error.jsp" %><%@ page isErrorPage="true" %> 

Example of Exception Implicit object in JSP

exception.jsp

<%@ page language="java" errorPage="error.jsp" %><html><head><title>Implicit Exception object</title></head>

<body><% String a=null; int b=Integer.parseInt(a);%></body></html>

error.jsp

<%@ page language="java" import="java.io.*" isErrorPage="true" %><html><head><title>Implicit Exception Error page</title></head>

<body>The Exception is <strong><%= exception.toString() %></strong><br>

Page 40: JSP Tutorial

Message : <strong><%=exception.getMessage()%></strong><br>

</body></html>JSP declaration Example

Declaration in JSP is way to define global java variable and method. This java variable method in declaration can be access normally. Normally declaration does not produce any output, and access of this code is also limited. The declaration code does not reside inside service method of JSP. Declaration we use method to convert null convert of string in JSP.

Example of Declaration in JSP

declaration.jsp

<%@ page language="java" errorPage="" %><%! public String nullconv(String str) { if(str==null) str=""; else if(str.equals("null")) str=""; else if((str.trim()).equals("")) str=""; else if(str.equals(null)) str=""; else str=str.trim(); return str; }

%>

<% String myVariable=null;%><html><head><title>Declaration in JSP</title></head>

<body>This is null variable : <%=nullconv(myVariable)%></body></html>

We can see declaration code is not used to produce any direct output; it is used for reusable code.

Instead of <%! Declaration code%> can use

<jsp:declaration> public String nullconv(String str) { if(str==null) str=""; else if(str.equals("null"))

Page 41: JSP Tutorial

str=""; else if((str.trim()).equals("")) str=""; else if(str.equals(null)) str=""; else str=str.trim(); return str; }</jsp:declaration>

JSP Directives

JSP directive allow us to define our page information of JSP and translate these information to JSP engine. According to this page information, JSP engine process further task. This can be an importing java packages into JSP for processing java classes and method, enabling session for current JSP page, making thread safe, limiting buffer size, setting error page.

JSP Directive tags is following1. Page2. Include3. taglib

Include directive areMore on include directive

Page directive Page directive are having these attributes

import

Import is used to import java classes and package methods.This translates JSP engine to include classes in JSP servlet. <%@ page import="java.sql.*,java.text.SimpleDateForamt,com.myapp.ClassName"%>

Comma is used to separation between classes and package.

We can use this class as our requirement.

<%! ClassName cn=new ClassName(); cn.MethodName();%>

contentType

content type is used to defined mime type and character set in JSP page. This MIME type define page type as, pdf, html, excel or word file. Character set define charater coding. Different language uses different charset.contentType="MIME Type;charset=characterset"

<%@ page contentType="text/html;charset=ISO-8859-1" %>

errorPage

errorPage=”relativeURL”When an exception is occur in JSP, errorPage transfer the control of page to defined URL which is set in errorPage. This is customized presentation of errors to user. If relativeURL found blank, exception will throw on same page.

 

Page 42: JSP Tutorial

<%@ page errorPage="error.jsp" %>

isErrorPage

 isErrorPage=”false | true”

isErrorPage in JSP translate JSP engine to display exception or not. If set false, we can not use exception objects in JSP page. Default value is true.

<%@ page isErrorPage="true" %>

isThreadSafe

isThreadSafe="true | false"This attribute translate as JSP class is thread safe or not. In multiple threads, concurrent number of users can request to JSP page. JSP process this request, this results in using variable, code at a same time. We can synchronize request to JSP with this attribute. IfisThreadSafe is false, one request process to JSP at same time, and implement as SingleThreadModel. We suggest to use isThreadSafe in rare cases when really need it. <%@ page isThreadSafe="true" %>

Buffer

buffer="none | 8k | size"buffer in page directive specify the buffer size of out object to print on client browser. Default size of buffer is 8k, can change to as requirement. <%@ page buffer="16kb" %>

autoFlush

autoFlush=”true | false”when buffer get full it is automatically flush, if it is set as true. In false case, it throws exception of overflow. <%@ page autoFlush="true" %>

Session

Session=”true | false”Session attribute in page translate to JSP engine to use session object in current JSP page. If session attribute set as false in page directive we can not use session in current JSP.By default it is true. <%@ page session="true" %>

isELIgnored

isELIgnored=”true | false”

Expression language tag use in JSP 2.0 version and allow using custom made tags. This is almost same as old <%%> tag provide more facility and separate java code and html. If attribute set as false then we can not use EL tags in JSP.

language

language=”java”language attribute define core language use in scripting tag. Currently it is java only. <%@ page language="java" %>

extends

extends=”class.package.ClassName”extends is used to override the class hierarchy provided by JSP container. It is something like to deploy own our classes instead of using JSP container classes. It should be used with precaution unless you know it clearly. It is used when we need tag libraries.

Page 43: JSP Tutorial

<%@ page extends="com.myapp.ClassName" %>

info

info=”String”info is used to provide a String particular to JSP page. This can be a comment on page or any information related to page, this information can get by getServletInfo method of servlet. <%@ page info="This page is made on 01-May-2011" %>

pageEncoding

pageEncoding=”character set”pageEncoding attribute is used to define character encoding for the page. This encoding can be UTF-8, ISO-8859-1. If it is not included, default encoding takes ISO-8859-1. <%@ page pageEncoding="ISO-8859-1" %>

JDBC - Java Database Connectivity Tutorials

Java database connectivity (JDBC) tutorial give details SQL operation and java access to database with insert modification delete operations.

Start with introduction of JDBC

This tutorial contains examples and deep understanding about topics.

All commonly used properties, methods are included to easy grip of usability.

JDBC Example

Almost all queries in JDBC covered with full examples.

JDBC Query Example

All update, delete, insert query added with this tutorial

JDBC Insert, JDBC Update, JDBC Delete


Recommended