Академический Документы
Профессиональный Документы
Культура Документы
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 %>
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.
<%@ 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
<%@ page language="java" errorPage="" %> <% String stVariable="this is defining String variable"; %> <html> <body> String variable having value : <%=stVariable%> </body> </html>
<% 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.
<%@ 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
<%@ 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 {
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++)
:"+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/>");
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%"> </td> <td width="78%"> </td> </tr> <tr> <td>Name Student </td> <td><input type="text" name="studentName"></td> </tr> <tr> <td> </td> <td><input type="submit" name="submit" value="Submit"></td> </tr> <tr> <td> </td>
<%@ 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
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%"> </td> <td width="78%"> </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> </td> <td><input type="submit" name="submit" value="Submit"></td> </tr> <tr> <td> </td> <td> </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%"> </td> <td width="78%"> </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> </td> <td><input type="submit" name="submit" value="Submit"></td> </tr> <tr> <td> </td> <td> </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>
<%@ 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%"> </td> <td width="78%"> </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> </td> <td><input type="submit" name="submit" value="Submit"></td> </tr> <tr> <td> </td> <td> </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%"> </td> <td width="78%"> </td> </tr> <tr> <td>Cookie value Set </td> <td><input type="text" name="cookieSet" /></td> </tr> <tr> <td> </td> <td> </td> </tr>
<tr> <td> </td> <td><input type="submit" name="submit" value="Submit"></td> </tr> <tr> <td> </td> <td> </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>
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.
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%"> </td> <td width="78%"> </td> </tr> <tr> <td>Session value Set </td> <td><input type="text" name="sessionVariable" /></td> </tr> <tr> <td> </td> <td> </td> </tr> <tr>
<td> </td> <td><input type="submit" name="submit" value="Submit"></td> </tr> <tr> <td> </td> <td> </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.
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();
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>"); }
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
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"> </td> align="center">This is Home page and having header and footer included by include of JSP </td> <td width="19%"> </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> </td> <td class="st">Products</td> <td> </td> <td class="st">Services</td> <td> </td> <td class="st">Company Profile</td> <td> </td> <td class="st">Register</td> <td> </td> <td class="st">Login</td> <td> </td> <td class="st">About Us</td> <td> </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>
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
<%@ 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
<%@ 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.
<%@ 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]); }
<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
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
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
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>
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");
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")));
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
Dynamic include
<%@ 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> </td> <td class="header">Products</td> <td> </td> <td class="header">Services</td> <td> </td> <td class="header">Company Profile</td> <td> </td> <td class="header">Register</td> <td> </td> <td class="header">Login</td> <td> </td> <td class="header">About Us</td> <td> </td> </tr> </table> </body> </html>
staticAction.jsp
<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> </td> <td class="header"><%=request.getParameter("variable2")%></td> <td> </td> <td class="header"><%=request.getParameter("variable3")%></td> <td> </td> <td class="header"><%=request.getParameter("variable4")%></td> <td> </td> <td class="header"><%=request.getParameter("variable5")%></td> <td> </td> <td class="header"><%=request.getParameter("variable6")%></td> <td> </td> <td class="header"><%=request.getParameter("variable7")%></td> <td> </td> </tr> </table> </body> </html>
dynamicAction.jsp
<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"> &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
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
<% 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>
This useBean create instance of java bean class. The attribute of bean myLog get object of FirstBean after instantiate.
out is javax.servlet.jsp.JspWriter class use for printing. Out is Output Stream use response.getWriter() to send output to client
<% %>
2. page
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.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()
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 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>
declaration.jsp
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>
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.
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"
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.
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.
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.
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.
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.
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.
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
%>
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"
%>
All commonly used properties, methods are included to easy grip of usability.
JDBC Example