[go: up one dir, main page]

0% found this document useful (0 votes)
130 views22 pages

Jspexample1.Jsp: 1. JSP Example Simple Print On Browser

The document provides examples of using different data types, control structures, and forms in JavaServer Pages (JSP). It includes examples of printing text, dates, and variables; using strings, integers, floats, and booleans; iterating over arrays; and using if/else, for, while, and do-while loops. It also demonstrates getting form input through request parameters, including text, radio buttons, checkboxes; and validating user input. Finally, it shows how to access objects like request, application, and session across JSP pages.

Uploaded by

Alok Nayak
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
130 views22 pages

Jspexample1.Jsp: 1. JSP Example Simple Print On Browser

The document provides examples of using different data types, control structures, and forms in JavaServer Pages (JSP). It includes examples of printing text, dates, and variables; using strings, integers, floats, and booleans; iterating over arrays; and using if/else, for, while, and do-while loops. It also demonstrates getting form input through request parameters, including text, radio buttons, checkboxes; and validating user input. Finally, it shows how to access objects like request, application, and session across JSP pages.

Uploaded by

Alok Nayak
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

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>

1. String variable Example in JSP

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

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

2. Int variable Example in JSP

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

jspInt.jsp
<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>
<%
int iVariable=5;
%>

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

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

4. float variable Example in JSP

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

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

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

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


<%
boolean checkCondition=false;
%>

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

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


<%
String[] stArray={"bob","riche","jacky","rosy"};
%>

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

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


<%
String[] stArray=new String[4];
stArray[0]="bob";
stArray[1]="riche";
stArray[2]="jacky";
stArray[3]="rosy";
%>

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

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


<%
int[] intArray={23,45,13,54,78};
%>

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

<%@ page import="java.util.Vector" language="java" %>


<%
Vector vc=new Vector();
vc.add("bob");
vc.add("riche");
vc.add("jacky");
vc.add("rosy");
%>

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

ArrayList.jsp

<%@ page import="java.util.ArrayList" language="java" %>


<%
ArrayList ar=new ArrayList();
ar.add("bob");
ar.add("riche");
ar.add("jacky");
ar.add("rosy");
%>

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

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

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

<body>
<%
String sName="joe";
String sSecondName="noe";

if(sName.equals("joe")){
out.print("if condition check satisfied JSP count :"+sName+"<br>");
}

if(sName.equals("joe") && sSecondName.equals("joe"))


{
out.print("if condition check if Block <br>");
}
else
{
out.print("if condition check else Block <br>");
}
%>
</body>
</html>

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

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>
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 be left blank");
document.frm.username.focus();
return false;
}
else if(document.frm.pwd.value=="")
{
alert("Password should be left blank");
document.frm.pwd.focus();
return false;
}
}
</script>
</head>
<body>
<form name="frm" method="get" action="validateInput.jsp" onSubmit="return
validateForm()">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="22%">&nbsp;</td>
<td width="78%">&nbsp;</td>
</tr>
<tr>
<td>UserName </td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" name="pwd" /></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="submit" value="Submit"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
</table>
</form>
</body>
</html>

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>

JSP Error Handling

Request object

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>

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>

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>

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>

Response object in JSP

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 Session Object

JSP Example of Creating session and retrieving session

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

session.setMaxInactiveInterval(2700);

session.setMaxInactiveInterval(2700), this use to set maximum session time. 2700 is time in


number. In this period, if user don’t do anything session get expired automatically.

Remove JSP Session Variables or Expire JSP Session

When session is no long needed, should be removed forcefully by user. This can be done by
calling session method of invalidate 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 Cookies

1. JSP Example of creating Cookie

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

createNewCookie.jsp

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


<%
String cookieSet=request.getParameter("cookieSet");

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


response.addCookie(cookie);
%>

<html>
<head>
<title>Cookie Create Example</title>
</head>
<body>
<%
Cookie[] cookies = request.getCookies();

for (int i=0; i<cookies.length; i++) {


out.println(cookies[i].getName()+" : "+cookies[i].getValue()+"<br/>");
}
%>
</body>
</html>

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

We are creating new object of cookie class.


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

Expire JSP cookie

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


cookie setMaxAge(0);

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

Retrieve cookie from JSP

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

Cookie[] cookies = request.getCookies();

for (int i=0; i<cookies.length; i++) {


      out.println(cookies[i].getName()+" : "+cookies[i].getValue()+"<br/>");
}

JSP File handling Object

Example Reading text file in JSP

fileRead.jsp

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


<html>
<head>
<title>File Handling in JSP</title>
</head>

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

File f=new File(fileName);

InputStream in = new FileInputStream(f);

BufferedInputStream bin = new BufferedInputStream(in);

DataInputStream din = new DataInputStream(bin);

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

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

Create new file through JSP

createNewFile.jsp

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


<html>
<head>
<title>File Handling in JSP</title>
</head>

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

File f=new File(fileName);

f.createNewFile();

%>
</body>
</html>

Examples of Delete file in JSP

This example delete file from defined path.

deleteFile.jsp

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


<html>
<head>
<title>File Handling in JSP</title>
</head>

<body>
<%
String fileName=getServletContext().getRealPath("test.txt");
//// If you know path of the file, can directly put path instead of
///filename e.g c:/tomcat/webapps/jsp/myFile.txt
File f=new File(fileName);
boolean flag=f.delete();
///return type is boolean if deleted return true, otherwise false

%>
</body>
</html>

Can check file exists or not is directory, or file

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

fileType.jsp

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


<html>
<head>
<title>File Handling in JSP</title>
</head>

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

File f=new File(fileName);

out.print("File exists : "+f.exists()+"<br>");


/// return type is boolean exists return true else false

out.print("File is Directory : "+f.isDirectory()+"<br>");


/// return type is boolean exists return true else false

out.print("File is File : "+f.isFile()+"<br>");


/// return type is boolean exists return true else false

out.print("File is creation Date : "+f.lastModified()+"<br>");


/// return type is boolean exists return true else false

%>
</body>
</html>

Example of Rename file in JSP

renameFile.jsp

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


<html>
<head>
<title>File Handling in JSP</title>
</head>

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

boolean flag=f.renameTo(new
File(getServletContext().getRealPath("myJsp.txt")));
%>
</body>
</html>

You might also like