Вы находитесь на странице: 1из 43

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 doesnt go to server for process. It process almost on clients side on clients 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 users 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.


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 programming All 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> <%="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 datas type what is this. It may be a string, may be a int (integer), or float

1. String variable Example in JSP


jspString.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" %>

<% 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 dont 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 JSP This is same as float variable; it can store more bytes than float variable. In double we dont need to put f character

6. Boolean variable Example in JSP


This is useful when we need to check condition. Lets 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"); } %> </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 name Fruits 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 } %> </body> </html>

:"+stArray[i]+"<br/>");

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++)

out.print("stArray Elements } %> </body> </html>


Integer Array in JSP intArray.jsp

:"+stArray[i]+"<br/>");

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 } %> </body> </html>

:"+intArray[i]+"<br/>");

Dynamic arrays are automatically growable and reduceable according to per requirement. We dont 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 } %> </body> </html>

:"+vc.get(i)+"<br/>");

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 } %> </body> </html>

:"+ar.get(i)+"<br/>");

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>

<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.g http://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 only http://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>

<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 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.

Lets 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> <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 users 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> </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.

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 users 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 applications 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> <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 dont 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 method session.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. Loop in JSP can be for, while, do while Look 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> <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 JSP Conditional check means check condition and if it satisfies condition then block below execute otherwise block will not execute. Unconditional checks those check that dont 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 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("Applicatio nValue"); application.setAttribute("ApplcationVariable",parameterValue); String getApplicationVariable=(String)application.getAttribute("ApplcationVari able"); %> <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 equals(Object obj) getAttribute(String str) getAttributeNames() getContext(String str) getContextPath() getInitParameter(String str) getInitParameterNames() getMajorVersion() getMimeType(String str) getMinorVersion() getNamedDispatcher(String str) Return Objects Objects Enumeration ServletContext String String Enumeration int String int RequestDispatcher Description Matching objects Getting value through application objects an Enumeration of attribute names

getRealPath(String str) getRequestDispatcher(String str) getResource(String str) getResourceAsStream(String str) getResourcePaths(String str) log(String str) log(String str, Throwable t) removeAttribute(String str) setAttribute(String str, Object obj) toString()

String RequestDispatcher URL InputStream Set void void void void String

JSP Including Files


The include directive is used to include any files 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 Files Let 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%" <tr> <td colspan="3" </tr> <tr> <td width="16%" <td width="65%" border="0" cellspacing="0" cellpadding="0"> align="center"><%@ include file="header.jsp"%></td>

height="138">&nbsp;</td> 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>

</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>

<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 this http://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 addCookie(Cookie cookie) addDateHeader(String name,long date) addHeader(String name,String value) encodeRedirectURL(String URL) encodeURL(String URL) flushBuffer() getBufferSize() getCharacterEncoding() getContentType() getOutputStream() getWriter() isCommitted() resetBuffer() Return void void void String String void int String String ServletOutputStream PrintWriter boolean void Description Add specified cookies to response object Adds response header with given name and date value Adds response header with given name and value Encode specified URL for sendRedirect method Encode specified URL with session ID, if not unchanged URL return Forces any content in buffer to be written in client Returns actual buffer size used for response Returns character encoding for page in response MIME type charset=iso-8859-1 Returns MIME type used for body in response text/html; Returns ServletOutputStream binary data stream to written in response Returns a PrintWriter object that can send character text to client Returns a Boolean, if response has been commited Clear content in buffer of response without clearing

header and status sendRedirect(String location) setBufferSize(int size) setCharacterEncoding(String charset) setContentLength(int length) void void void void Sends a redirect response to client with redirect specified URL location. Contain Relative path Set a preferred buffer size for the body of response Set a character encoding for send to client response body charset=iso-8859-1 Set a length of content body in response Set a content Type of response being sent to client, if response is yet not committed Set a response header with given name and value

setContentType(String contentType) void setHeader(String name, String value) void

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" %> <% 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 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 doesnt 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.*" %> <% 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> <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>
Cookies Cookies use request object to get values through in cookie file. It uses request.getCookies() method to get cookie and return in cookie[] array.

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 equals(Object obj) Return Objects Description Matching objects

getAttribute(String str) getAttributeNames() getAuthType() getCharacterEncoding()

Objects Enumeration String String

Returns the String associated with name in the request scope an Enumeration of attribute names

Returns character encoding for page in request MIME type charset=iso8859-1 get length of content body in request

getContentLength() getContentType() getContextPath() getCookies() getDateHeader(String str) getHeader(String str) getHeaderNames() getHeaders(String str) getInputStream() getIntHeader(String str) getLocalAddr(String str) getLocale(String str) getLocales() getLocalName() getLocalPort() getMethod() getParameter(String str) getParameterMap() getParameterNames() getParameterValues(String str) getPathInfo() getPathTranslated() getProtocol() getQueryString() getReader() (D) getRealPath() getRemoteAddr() getRemoteHost() getRemotePort() getRemoteUser() getRequestDispatcher(String str) getRequestedSessionId() getRequestURI() getRequestURL() getScheme() getServerName() getServerPort()

int String String Cookie[] long String Enumeration Enumeration ServletInputStream int String Locale Enumeration String int String String Map Enumeration String String String String String BufferedReader String String String int String RequestDispatcher String String StringBuffer String String int

get request header with given name and date value get request header with given name and value

getServletPath() getSession() getSession(boolean true|false) getUserPrincipal() hashCode() isRequestedSessionIdFromCookie() isRequestedSessionIdFromURL() isRequestedSessionIdValid() isSecure() isUserInRole() removeAttribute(String str) setAttribute(String str, Object obj) setCharacterEncoding(String str)

String HttpSession HttpSession Principal int boolean boolean boolean boolean boolean void void void Set a character encoding for send to client request body charset=iso8859-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> </html>


This will show Error caught by Catch block is :/ by zero java.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. 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(); %> </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.txt File 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 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. include 2. forward 3. 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>


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> <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"> <jsp:param name="variable1" <jsp:param name="variable2" <jsp:param name="variable3" <jsp:param name="variable4" <jsp:param name="variable5" <jsp:param name="variable6" <jsp:param name="variable7" </jsp:include> </body> </html>
2. Forward action tag

value="Home" /> value="Products" /> value="Services" /> value="Company Profile" /> value="Register" /> value="Login" /> value="About Us" />

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/WEBINF/classes/com/myApp of tomcat

Example of java bean with useBean action tag in JSP

FirstBean.java

package com.myApp; 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); %> <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 dont 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 pages Servlet.

<% %> Object page = this;

3. pageContext

pageContext instance that contains all datas information, which is associated with JSP page. This helps to access attribute and other fields 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 pageContext.findAttribute(String Name) Return Object Description Search for named attribute in JSP page Request,session, application scope This method is used to redirect or forward the current ServletRequest or ServletResponse to another active component Returns the object associated with name in the page scope Get the scope where a given attribute is defined Provide access to error information Get current value of the exception Object Get current value of out object Get current value of request object Get current value of response object Get any initialization parameters and startup configuration for this servlet Gets the context from the servlet's ServletConfig object Return the current value of session object

pageContext.forward(String relativeURLPath) void

pageContext.getAttribute(String Name) pageContext.getAttributesScope(String Name) pageContext.getErrorData() pageContext.getException() pageContext.getOut() pageContext.getRequest() pageContext.getResponse() pageContext.getServletConfig() pageContext.getServletContext() pageContext.getSession()
4. request

Object int ErrorData Exception JspWriter ServletRequest ServletResponse ServletConfig ServletContext HttpSession

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

config object is related to get servlets 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> 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) {

} </jsp:declaration>

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;

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 following 1. Page 2. Include 3. taglib Include directive are More 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 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. If isThreadSafe 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
extends

language="java"

%>

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
info

extends="com.myapp.ClassName"

%>

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
pageEncoding

info="This page is made on 01-May-2011"

%>

pageEncoding=character set pageEncoding attribute is used to define character encoding for the page. This encoding can be UTF-8, ISO-88591. 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

Вам также может понравиться