Simple JSP Example with Syntax



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

1. JSP Example Simple Print on browser

jspExample1.jsp


 

<html>

<body>

<%

out.print("Hello World!");

%>

</body>

</html>

2. JSP Example Expression base print on browser

jspExample2.jsp


 

<html>

<body>

<%="Hello World!"%>

</body>

</html>



3. JSP Example Current date print on browser

jspExample3.jsp


 

<%@ 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 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

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

Comma is used to separation between classes and package.

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

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 08-March-2012" %>

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

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

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>

JSP Forms and User Input

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

JSP Example of input text form

html.jsp


 

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

<html>

<body>

<form name="frm" method="get" action="textInput.jsp">

<table width="100%" border="0" cellspacing="0" cellpadding="0">

<tr>

<td width="22%">&nbsp;</td>

<td width="78%">&nbsp;</td>

</tr>

<tr>

<td>Name Student </td>

<td><input type="text" name="studentName"></td>

</tr>

<tr>

<td>&nbsp;</td>

<td><input type="submit" name="submit" value="Submit"></td>

</tr>

<tr>

<td>&nbsp;</td>

<td>&nbsp;</td>

</tr>

</table>

</form>

</body>

</html>

Get these form value in JSP

textInput.jsp


 

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

<%

String studentNameInJSP=request.getParameter("studentName");

%>

<html>

<body>

Value of input text box in JSP : <%=studentNameInJSP%>

</body>

</html>

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

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

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

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

 

JSP Example of radio button form

radio.jsp


 

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

<html>

<body>

<form name="frm" method="get" action="radioInput.jsp">

<table width="100%" border="0" cellspacing="0" cellpadding="0">

<tr>

<td width="22%">&nbsp;</td>

<td width="78%">&nbsp;</td>

</tr>

<tr>

<td>Active <input type="radio" name="active" value="Active"></td>

<td>DeActive <input type="radio" name="active" value="DeActive"></td>

</tr>

<tr>

<td>&nbsp;</td>

<td><input type="submit" name="submit" value="Submit"></td>

</tr>

<tr>

<td>&nbsp;</td>

<td>&nbsp;</td>

</tr>

</table>

</form>

</body>

</html>

radioInput.jsp

 

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

<%

String radioInJSP=request.getParameter("active");

%>

<html>

<body>

Value of radio button box in JSP : <%=radioInJSP%>

</body>

</html>

JSP Example of checkbox button in form

checkbox.jsp


 

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

<html>

<body>

<form name="frm" method="get" action="checkboxInput.jsp">

<table width="100%" border="0" cellspacing="0" cellpadding="0">

<tr>

<td width="22%">&nbsp;</td>

<td width="78%">&nbsp;</td>

</tr>

<tr>

<td>State <input type="checkbox" name="state" value="state"></td>

<td>City <input type="checkbox" name="city" value="city"></td>

</tr>

<tr>

<td>&nbsp;</td>

<td><input type="submit" name="submit" value="Submit"></td>

</tr>

<tr>

<td>&nbsp;</td>

<td>&nbsp;</td>

</tr>

</table>

</form>

</body>

</html>

checkboxInput.jsp

 

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

<%

String checkboxStateInJSP=request.getParameter("state");

String checkboxCityInJSP=request.getParameter("city");

%>

<html>

<body>

Value of checkbox in JSP : <%=checkboxStateInJSP%> <%=checkboxCityInJSP%>


</body>

</html>

JSP Session Object

session.jsp

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

<html>

<body>

<form name="frm" method="get" action="sessionSetRetrieve.jsp">

<table width="100%" border="0" cellspacing="0" cellpadding="0">

<tr>

<td width="22%">&nbsp;</td>

<td width="78%">&nbsp;</td>

</tr>

<tr>

<td>Session value Set </td>

<td><input type="text" name="sessionVariable" /></td>

</tr>

<tr>

<td>&nbsp;</td>

<td>&nbsp;</td>

</tr>

<tr>

<td>&nbsp;</td>

<td><input type="submit" name="submit" value="Submit"></td>

</tr>

<tr>

<td>&nbsp;</td>

<td>&nbsp;</td>

</tr>

</table>

</form>

</body>

</html>



sessionSetRetrieve.jsp

<%@ 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>

Form Validation Javascript with JSP

formValidation.jsp


 

 

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

<html>

<head>

<script>

function validateForm()

{

if(document.frm.username.value=="")

{

alert("User Name should not be left blank");

document.frm.username.focus();

return false;

}

else if(document.frm.pwd.value=="")

{

alert("Password should not be left blank");

document.frm.pwd.focus();

return false;

}

}

</script>

</head>

<body>

<form name="frm" method="get" action="validateInput.jsp" onSubmit="return validateForm()">

<table width="100%" border="0" cellspacing="0" cellpadding="0">

<tr>

<td width="22%">&nbsp;</td>

<td width="78%">&nbsp;</td>

</tr>

<tr>

<td>UserName </td>

<td><input type="text" name="username" /></td>

</tr>

<tr>

<td>Password</td>

<td><input type="password" name="pwd" /></td>

</tr>

<tr>

<td>&nbsp;</td>

<td><input type="submit" name="submit" value="Submit"></td>

</tr>

<tr>

<td>&nbsp;</td>

<td>&nbsp;</td>

</tr>

</table>

</form>

</body>

</html>

taglib Directive:

The JavaServer Pages API allows you to define custom JSP tags that look like HTML or XML tags and a tag library is a set of user-defined tags that implement custom behavior.

The taglib directive declares that your JSP page uses a set of custom tags, identifies the location of the library, and provides a means for identifying the custom tags in your JSP page.

The taglib directive follows the following syntax:

<%@ taglib uri="uri" prefix="prefixOfTag" >

Where the uri attribute value resolves to a location the container understands and the prefix attribute informs a container what bits of markup are custom actions.

You can write XML equivalent of the above syntax as follows:

<jsp:directive.taglib uri="uri" prefix="prefixOfTag" />





include Directive:

The include directive is used to includes a file during the translation phase. This directive tells the container to merge the content of other external files with the current JSP during the translation phase. You may codeinclude directives anywhere in your JSP page.

The general usage form of this directive is as follows:

<%@ include file="relative url" >

The filename in the include directive is actually a relative URL. If you just specify a filename with no associated path, the JSP compiler assumes that the file is in the same directory as your JSP.

You can write XML equivalent of the above syntax as follows:

<jsp:directive.include file="relative url" />



example: include.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Home Page</title>

</head>

<body>

     

    <%@include file="header.html" %>

     

    <hr/>

    <h2>This is main content</h2>

    <hr/>

     

    <%@include file="footer.html" %>

     

</body>

</html>



Code of the header.html page:


<h1>This is header</h1>

 

Code of the footer.html page:


<h5>This is footer</h5>

 


AutoShape 7