Wednesday, 19 June 2013

JSP Tutorial for Beginner Part II

JSP Tutorial for Beginners Part II

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("ApplicationValue");
   
    application.setAttribute("ApplcationVariable",parameterValue);
    String getApplicationVariable=(String)application.getAttribute("ApplcationVariable");
%>
<html>
<head>
<title>Applcation object in JSP</title>
</head>

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


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

Method
Return
Description
equals(Object obj)
Objects
Matching objects
getAttribute(String str)
Objects
Getting value through application objects
getAttributeNames()
Enumeration
an Enumeration of attribute names
getContext(String str)
ServletContext

getContextPath()
String

getInitParameter(String str)
String

getInitParameterNames()
Enumeration

getMajorVersion()
int

getMimeType(String str)
String

getMinorVersion()
int

getNamedDispatcher(String str)
RequestDispatcher

getRealPath(String str)
String

getRequestDispatcher(String str)
RequestDispatcher

getResource(String str)
URL

getResourceAsStream(String str)
InputStream

getResourcePaths(String str)
Set

log(String str)
void

log(String str, Throwable t)
void

removeAttribute(String str)
void

setAttribute(String str, Object obj)
void

toString()
String


JSP Include Files 

The include directive is used to include any file’s content into other desired file. This process is useful when need a separate header, footer, menu bar, or any common content need to reuse on other pages.
This JSP include can be static or dynamic.
Static include in JSP does include one file content into desired file at translation time, after that JSP page is compiled.
Dynamic include in JSP
Dynamic include is used in javabean as <jsp:include>. This include execute first file and then output of this file include in desired file.
Include is useful for common and reusable code function method, variable.

Syntax for Including 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%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td colspan="3" align="center"><%@ include file="header.jsp"%></td>
  </tr>
  <tr>
    <td width="16%" height="138">&nbsp;</td>
    <td width="65%" align="center">This is Home page and having
     header and footer included by include of JSP 
 </td>
<td width="19%">&nbsp;</td>
  </tr>
  <tr>
    <td colspan="3" align="center"><%@ include file="footer.jsp"%></td>
  </tr>
</table>

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




<%@ 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
Return
Description
addCookie(Cookie cookie)
void
Add specified cookies to response object 
addDateHeader(String name,long date)
void
Adds response header with given name and date value
addHeader(String name,String value)
void
Adds response header with given name and value
encodeRedirectURL(String URL)
String
Encode specified URL for sendRedirect method
encodeURL(String URL)
String
Encode specified URL with session ID, if not unchanged URL return
flushBuffer()
void
Forces any content in buffer to be written in client
getBufferSize()
int
Returns actual buffer size used for response
getCharacterEncoding()
String
Returns character encoding for page in response MIME type charset=iso-8859-1
getContentType()
String
Returns MIME type used for body in response text/html;
getOutputStream()
ServletOutputStream
Returns ServletOutputStream binary data stream to written in response
getWriter()
PrintWriter
Returns a PrintWriter object that can send character text to client
isCommitted()
boolean
Returns a Boolean, if response has been commited
resetBuffer()
void
Clear content in buffer of response without clearing header and status
sendRedirect(String location)
void
Sends a redirect response to client with redirect specified URL location. Contain Relative path
setBufferSize(int size)
void
Set a preferred buffer size for the body of response
setCharacterEncoding(String charset)
void
Set a character encoding for send to client response body charset=iso-8859-1
setContentLength(int length)
void
Set a length of content body in response
setContentType(String contentType)
void
Set a content Type of response being sent to client, if response is yet not committed
setHeader(String name, String value)
void
Set a response header with given name and value
Example of ContentType in JSP response object
setContentType.jsp
<%@page language="java"%>
<%response.setContentType("text/html");%>
<html>
<head>
<title>Response object set Content type</title>
</head>

<body>
This is setting content type of JSP page
</body>
</html>
if documentation is in PDF format then setContentType as
<%response.setContentType("application/pdf");%>
For Microsoft word document
<%
response.setContentType("application/msword");
%>
For Microsoft excel document
<%response.setContentType("application/vnd.ms-excel");%>
or
<%@page contentType="text/html; charset=iso-8859-1" language="java"%>
Example of control page into cache
cacheControl.jsp

<%@page language="java"%>
<%
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 in JSP

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
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(""+queryString);
%>
</body>
</html>
We can get single id and value instead of using getQueryString method of request.
Query String example with getParameter
queryStringParameter.jsp

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

<body>
<a href="queryString.jsp?id=9&name=joe">This is data inside query string</a>
<%
String queryStringVariable1=request.getParameter("id");
String queryStringVariable2=request.getParameter("name");
out.print("<br/>"+queryStringVariable1);
out.print("<br/>"+queryStringVariable2);
%>
</body>
</html>
Form 
Form is most important part of request object in JSP. It takes value from user and sends it to server for further processing. Suppose we have a registration form, and value in field have to save in database. We need to get these values from browse and get in server side; once we get this value in java, we can save in database through JDBC or any database object. Form in html has two properties get or post method, get method send information to server in query string. Post method doesn’t send data in query string in to server. When data is sent to server it is not visible on browser. Post method as compare to get method is slower. Get method has a limit of string length in some kilobytes.
Form Example in JSP with request objec

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("Field 1 :"+queryStringVariable1);
out.print("Field 2 :"+queryStringVariable2);

%>

<form method="get" name="form1">
Name <input type="text" name="name"> 
Class <input type="text" name="className"> 
<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("Field 1 :"+queryStringVariable1);
   
    for(int i=0;i<=queryStringVariable2.length;i++){
     out.print("Check box Field "+i+" :"+queryStringVariable2[i]);
    }
}
catch(Exception e)
{
 e.printStackTrace();
}

%>
<br>
<br>
<form method="get" name="form1">
Name <input type="text" name="name"> 
 class 1
 <input type="checkbox" name="className" value="c1">
 class 2 <input type="checkbox" name="className" value="c2">
<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("Field 1 :"+inputVariable);
   
    for(int i=0;i<=radioVariable.length;i++){
     out.print("Check box Field "+i+" :"+radioVariable[i]);
    }
}
catch(Exception e)
{
 e.printStackTrace();
}

%>
<br>
<br>
<form method="get" name="form1">
Name <input type="text" name="name"> 
 class 1 <input type="radio" name="className" value="c1">
 class 2 <input type="radio" name="className" value="c2">
<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 : <%=request.getCharacterEncoding()%>
Context Path : <%=request.getContextPath()%>

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

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

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

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

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

URI : <%=request.getRequestURI()%>

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

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

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

Servlet path current File name : <%=request.getServletPath()%>
</body>
</html>
Properties and method of Request objects
Method
Return
Description
equals(Object obj)
Objects
Matching objects
getAttribute(String str)
Objects
Returns the String associated with name in the request scope
getAttributeNames()
Enumeration
an Enumeration of attribute names
getAuthType()
String

getCharacterEncoding()
String
Returns character encoding for page in request MIME type charset=iso-8859-1
getContentLength()
int
get length of content body in request
getContentType()
String

getContextPath()
String

getCookies()
Cookie[]

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

getHeaders(String str)
Enumeration

getInputStream()
ServletInputStream

getIntHeader(String str)
int

getLocalAddr(String str)
String

getLocale(String str)
Locale

getLocales()
Enumeration

getLocalName()
String

getLocalPort()
int

getMethod()
String

getParameter(String str)
String

getParameterMap()
Map

getParameterNames()
Enumeration

getParameterValues(String str)
String

getPathInfo()
String

getPathTranslated()
String

getProtocol()
String

getQueryString()
String

getReader()
BufferedReader

(D) getRealPath()
String

getRemoteAddr()
String

getRemoteHost()
String

getRemotePort()
int

getRemoteUser()
String

getRequestDispatcher(String str)
RequestDispatcher

getRequestedSessionId()
String

getRequestURI()
String

getRequestURL()
StringBuffer

getScheme()
String

getServerName()
String

getServerPort()
int

getServletPath()
String

getSession()
HttpSession

getSession(boolean true|false)
HttpSession

getUserPrincipal()
Principal

hashCode()
int

isRequestedSessionIdFromCookie()
boolean

isRequestedSessionIdFromURL()
boolean

isRequestedSessionIdValid()
boolean

isSecure()
boolean

isUserInRole()
boolean

removeAttribute(String str)
void

setAttribute(String str, Object obj)
void

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






The include directive is used to include any file’s content into other desired file. This process is useful when need a separate header, footer, menu bar, or any common content need to reuse on other pages.
This JSP include can be static or dynamic.
Static include in JSP does include one file content into desired file at translation time, after that JSP page is compiled.
Dynamic include in JSP
Dynamic include is used in javabean as <jsp:include>. This include execute first file and then output of this file include in desired file.
Include is useful for common and reusable code function method, variable.

Syntax for Including 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%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td colspan="3" align="center"><%@ include file="header.jsp"%></td>
  </tr>
  <tr>
    <td width="16%" height="138">&nbsp;</td>
    <td width="65%" align="center">This is Home page and having
                    header and footer included by include of JSP </td>
    <td width="19%">&nbsp;</td>
  </tr>
  <tr>
    <td colspan="3" align="center"><%@ include file="footer.jsp"%></td>
  </tr>
</table>

</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
Return
Description
addCookie(Cookie cookie)
void
Add specified cookies to response object 
addDateHeader(String name,long date)
void
Adds response header with given name and date value
addHeader(String name,String value)
void
Adds response header with given name and value
encodeRedirectURL(String URL)
String
Encode specified URL for sendRedirect method
encodeURL(String URL)
String
Encode specified URL with session ID, if not unchanged URL return
flushBuffer()
void
Forces any content in buffer to be written in client
getBufferSize()
int
Returns actual buffer size used for response
getCharacterEncoding()
String
Returns character encoding for page in response MIME type charset=iso-8859-1
getContentType()
String
Returns MIME type used for body in response text/html;
getOutputStream()
ServletOutputStream
Returns ServletOutputStream binary data stream to written in response
getWriter()
PrintWriter
Returns a PrintWriter object that can send character text to client
isCommitted()
boolean
Returns a Boolean, if response has been commited
resetBuffer()
void
Clear content in buffer of response without clearing header and status
sendRedirect(String location)
void
Sends a redirect response to client with redirect specified URL location. Contain Relative path
setBufferSize(int size)
void
Set a preferred buffer size for the body of response
setCharacterEncoding(String charset)
void
Set a character encoding for send to client response body charset=iso-8859-1
setContentLength(int length)
void
Set a length of content body in response
setContentType(String contentType)
void
Set a content Type of response being sent to client, if response is yet not committed
setHeader(String name, String value)
void
Set a response header with given name and value
Example of ContentType in JSP response object
setContentType.jsp
<%@ page language="java" %>
<%
response.setContentType("text/html");
%>
<html>
<head>
<title>Response object set Content type</title>
</head>

<body>
This is setting content type of JSP page
</body>
</html>
if documentation is in PDF format then setContentType as
<% response.setContentType("application/pdf"); %>
For Microsoft word document
<%
response.setContentType("application/msword");
%>
For Microsoft excel document
<%
response.setContentType("application/vnd.ms-excel");
%>
or
<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>
Example of control page into cache
cacheControl.jsp

<%@ page language="java" %>
<%
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 in JSP

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
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 doesn’t send data in query string in to server. When data is sent to server it is not visible on browser. Post method as compare to get method is slower. Get method has a limit of string length in some kilobytes.
Form Example in JSP with request object
formGetMethod.jsp

<%@ page  language="java" import="java.sql.*" %>
<%
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
Return
Description
equals(Object obj)
Objects
Matching objects
getAttribute(String str)
Objects
Returns the String associated with name in the request scope
getAttributeNames()
Enumeration
an Enumeration of attribute names
getAuthType()
String

getCharacterEncoding()
String
Returns character encoding for page in request MIME type charset=iso-8859-1
getContentLength()
int
get length of content body in request
getContentType()
String

getContextPath()
String

getCookies()
Cookie[]

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

getHeaders(String str)
Enumeration

getInputStream()
ServletInputStream

getIntHeader(String str)
int

getLocalAddr(String str)
String

getLocale(String str)
Locale

getLocales()
Enumeration

getLocalName()
String

getLocalPort()
int

getMethod()
String

getParameter(String str)
String

getParameterMap()
Map

getParameterNames()
Enumeration

getParameterValues(String str)
String

getPathInfo()
String

getPathTranslated()
String

getProtocol()
String

getQueryString()
String

getReader()
BufferedReader

(D) getRealPath()
String

getRemoteAddr()
String

getRemoteHost()
String

getRemotePort()
int

getRemoteUser()
String

getRequestDispatcher(String str)
RequestDispatcher

getRequestedSessionId()
String

getRequestURI()
String

getRequestURL()
StringBuffer

getScheme()
String

getServerName()
String

getServerPort()
int

getServletPath()
String

getSession()
HttpSession

getSession(boolean true|false)
HttpSession

getUserPrincipal()
Principal

hashCode()
int

isRequestedSessionIdFromCookie()
boolean

isRequestedSessionIdFromURL()
boolean

isRequestedSessionIdValid()
boolean

isSecure()
boolean

isUserInRole()
boolean

removeAttribute(String str)
void

setAttribute(String str, Object obj)
void

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



 JSP Error Handling

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

<%@ page isErrorPage="true" %>
<%@ page language="java"  errorPage="error.jsp" %>
try catch block is important feature to caught exception in JSP page, do according to programmer specification.
Example of try catch Error Handling in JSP
tryCatch.jsp

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

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

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

1. out

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

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

2. page

   page is used by java.lang.Object class. Page is instance of  JSP page’s Servlet.
<%
    Object page = this; 
%>

3. pageContext

    pageContext instance that contains all data’s information, which is associated with JSP   page. This helps to access attribute and other field’s object set in JSP page. pageContext is injavax.servlet.jsp.PageContext class. pageContext is to managed various scope of attribute in shared information object.
Method of pageContext are following:
Method
Return
Description
pageContext.findAttribute(String Name)
Object
Search for named attribute in JSP page Request,session, application scope  
pageContext.forward(String relativeURLPath)
void
This method is used to redirect or forward the current ServletRequest or ServletResponse to another active component
pageContext.getAttribute(String Name)
Object
Returns the object associated with name in the page scope
pageContext.getAttributesScope(String Name)
int
Get the scope where a given attribute is defined
pageContext.getErrorData()
ErrorData
Provide access to error information
pageContext.getException()
Exception
Get current value of the exception Object
pageContext.getOut()
JspWriter
Get current value of out object
pageContext.getRequest()
ServletRequest
Get current value of request object
pageContext.getResponse()
ServletResponse
Get current value of response object
pageContext.getServletConfig()
ServletConfig
Get any initialization parameters and startup configuration for this servlet
pageContext.getServletContext()
ServletContext
Gets the context from the servlet's ServletConfig object
pageContext.getSession()
HttpSession
Return the current value of session object

4. request

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

5. response

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

6. session

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

7. config

    config object is related to get servlet’s configuration information. It is in javax.servlet.ServletConfiginterface. 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)
         {    
            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:declaration>

JSP Directives

JSP directive allow us to define our page information of JSP and translate these information to JSP engine. According to this page information, JSP engine process further task. This can be an importing java packages into JSP for processing java classes and method, enabling session for current JSP page, making thread safe, limiting buffer size, setting error page.
JSP Directive tags is 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  language="java"  %>
extends
extends=”class.package.ClassName”
extends is used to override the class hierarchy provided by JSP container. It is something like to deploy own our classes instead of using JSP container classes. It should be used with precaution unless you know it clearly. It is used when we need tag libraries.
<%@ page  extends="com.myapp.ClassName"  %>
info
info=”String”
info is used to provide a String particular to JSP page. This can be a comment on page or any information related to page, this information can get by getServletInfo method of servlet.
<%@ page  info="This page is made on 01-May-2011"  %>
pageEncoding
pageEncoding=”character set”
pageEncoding attribute is used to define character encoding for the page. This encoding can be UTF-8, ISO-8859-1. If it is not included, default encoding takes ISO-8859-1.
<%@ page  pageEncoding="ISO-8859-1"  %>


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

2. Forward action tag

Forward action tag in JSP transfer the control of one JSP page to another JSP with specify URL. Forward also can be static or dynamic as include action. When we use param tags, it is dynamic forward with having values. Static forward is simple forward without having param tags.Forward is used when we need to jump from one page to another if error occur or if work is completed in parent page. E.g we are inserting data in database with using insert statement. After finishing insert, control of page should go to successful insertion of data in database page or failure of insertion go to error page. This can be done forward action tag.
<jsp:forward page="relativeURL | or <%= expression %>" />
e.g
<jsp:forward page="success.jsp" />
This is static forward, dynamic forward
<jsp:forward page="relativeURL">
&l use for Java Beans. First we know little about Java Bean  what is Java Bean, Java Bean is simple java class having number of method and  can have business logic code inside method of Java Bean. These components can  be reusable by different number of JSPs as per requirement. Java bean can have  simple getter setter method or complex business logic. Java beans are not more  than a plain java class and help to separate a design code and logic code. Java  bean need to compile manually as java compiler does.
 
 
Simple java bean example java bean should copy in webapps/jsp/WEB-INF/classes/com/myApp of tomcat
 
 
Example of java bean with useBean action tag in JSP
 
 
FirstBean.java
 
 
 
 
package com.myApp;
 
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.
 





No comments:

Post a Comment