Demo Programs: (To Be Explained and Shown in The Class) JSP PRG 1.example For Displaying Date and Time

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 16

DEMO PROGRAMS

(To be explained and shown in the Class)

JSP PRG 1.EXAMPLE FOR DISPLAYING DATE AND TIME

<%@ page import="java.util.Date" %>


<html>
<head><title>First JSP</title></head>
<body><b>
Hello, Current Date and Time:<br>
<%=new Date()%></b>
</body>
</html>

JSP PRG 2. EXAMPLE FOR GETTING PARAMETERS FROM HTML

<form name=f1 action="http://localhost:8090/sun/ff.jsp">


NAME : <input type=text name=name>
<input type=submit value="LOGIN">
</form>
ff.jsp

<html>
<head>
<title>Hello</title>
</head>
<body bgcolor = "cyan">
<h1>
<font face =Arial>
<%
String s1=request.getParameter("name");
if(s1.equals("sunitech"))
out.println("Hello World");
else
out.println("Hello, "+s1);
%>
</font>
</h1>
</body>
</html>

JSP PRG 3. EXAMPLE FOR SUM OF TWO NUMBERS


f22.jsp

<html>
<pre>
<h3>Sum</h3>
<form action='http://localhost:8090/sun/f22.jsp'>
<% if ((request.getParameter("t1")!= null) && (request.getParameter("t2")!=null))
{%>

<% int bn=(Integer.parseInt(request.getParameter("t1"))


+Integer.parseInt(request.getParameter("t2")));
%>
No1:<input type=text name="t1" value=<%=request.getParameter("t1")%>>
No2:<input type=text name="t2" value=<%=request.getParameter("t2")%>>
Sum:<input type=text value=<%=bn %>>
<%}
else
{%>
No1:<input type=text name="t1" >
No2:<input type=text name="t2" >
Sum:<input type=text>
<%}%>
<input type="submit" value="Click to sum">
</form>
</pre>
</html>

JSP PRG 4. EXAMPLE FOR DEMONSTRATING ERRORPAGES


<!-- Program to demonstrate the error pages --!>
<!-- Declare the error page Attributes --!>
<%@
page import="java.util.*"
session="false"
contentType="text/html"
errorPage="errorpage.jsp"
%>
<html>
<body>
<%
int a=10;
int b=0;
int c=a/b;
%>
</body>
</html>
errorpage.jsp

<%@ page isErrorPage="true" %>


<html>
<head><title>Example For Error Handling</title></head>
<body>
<b>
<%=exception.getMessage()%>
<br>error occured
</b>
</body> </html>

JSP PRG 5. EXAMPLE FOR HTML COMMENTS AND JSP COMMENTS

<%@
page import="java.util.*"
session="false"
contentType="text/html"
errorPage="ERRORPAGE.jsp"
%>
<html>
<body>
<%!
int fact(int n)
{
int s=1;
for(int i=1;i<=n;i++)
s=s*i;
return s;
}
%>
<!-- Factorials --!>
10! = <%= fact(5) %><br>
20! = <%= fact(6) %><br>
<%--
30! = <%= fact(7) %><br>
40! = <%= fact(8) %><br>
50! = <%= fact(9) %><br> --%>
</body></html>

JSP PRG 6. EXAMPLE FOR FORWARDING AND INCLUDING A PAGE IN JSP


<jsp:forward page="fwd.jsp" /> save it in fwd.jsp
<h1> The output below is from a HTML Page : </h1>
<jsp:include page="xyz.html" flush ="true" /> save it in incl.jsp

<hr>
<h2> <i>
I am from SuniTech save it in xyz.html
</i></h2>
<hr>

<html> save it in id.jsp


<head><title>Include Directive</title></head>
<body bgcolor = "cyan">
<h2>
<% out.println("Hello Jsp World");%>
</h2>
<%@ include file = "xyz.html" %>
<hr>
</body>
</html>

JSP PRG 7. EXAMPLE FOR PARAMETER PASSING IN JSP


<html> param.html
<body>
<pre>
<form action="param.jsp">
<h2>Select The Courses And Improve Your Career</h2>
<input type=checkbox name=course value=Java>Java from Sun iTech
<input type=checkbox name=course value=J2EE>J2EE from Sun iTech
<input type=checkbox name=course value=Linux>Linux from Sun iTech
<input type=checkbox name=course value=Hardware>Hardware from Sun iTech
<input type=submit>
</form>
</pre>
</body>
</html>

<%@ page import="javax.servlet.http.*" %> param.jsp


<%@ page import="java.io.*" %>
<%@ page import="javax.servlet.jsp.*" %>
<html>
<body>
<h1> Welcome to Sun iTech </h1><br>
<ul>
<%!
void getdata(HttpServletRequest request,JspWriter out)throws
IOException,ServletException
{
int i;
for(i=0;i<request.getParameterValues("course").length;i++)
{
out.println("<li>" + request.getParameterValues("course")[i]);
}
}
%>
<% getdata(request,out); %>
</body>
</html>
JSP PRG 8. EXAMPLE FOR SESSION DEMO IN JSP
<%@ page session = "true" %>
<% int cnt = 0;
if(session.isNew())
{
%>
<form action=SessionDemoJSP.jsp>
<h1>Name :
<input type = text name=nam >
<br> Color :
<br> <input type=radio name=clr value=gray> Gray
<br> <input type=radio name=clr value=pink> Pink
<br> <input type=radio name=clr value=wheat> Wheat
<br> <input type=radio name=clr value=mistyrose> Misty Rose
<br> <input type = submit value = 'Next Page'>
</h1> </form>
<%
}
else
{
String n = request.getParameter("nam");
String c = request.getParameter("clr");
String logoff = request.getParameter("out");
if(logoff != null && logoff.equals("yes"))
{
session.invalidate();
out.println("<h1><a href=SessionDemoJSP.jsp>Back To First

Screen</a></h1>");
}
else
{
if(n!=null && c!= null )
{
session.putValue("name", n);
session.putValue("bgcolor", c);
}
else
{
n = (String)session.getValue("name");
c = (String)session.getValue("bgcolor");
cnt = ((Integer)session.getValue("count")).intValue();
}
session.putValue("count", new Integer(++cnt));
%>
<body bgcolor= <%= c %> >
<h1> Hello <%= n %>
U requested this page <%= cnt %> times. </h1>
<h3> See, I've Remembered So Much ! </h3>
<h2> <a href=SessionDemoJSP.jsp > Next Page </a>
<p><a href=SessionDemoJSP.jsp?out=yes > Log Off </a></h2></body>
<%
}
}
%>

JSP PRG 9. EXAMPLE FOR SHOPPING SITE IN JSP


<%@ page import="java.util.*" %> list.jsp
<html>
<body>
<pre>
<form>
<h2>Select The Items</h2>
<table border=2>
<th>
<th>Books
<th>Price
<tr><td><input type=checkbox name=item1 value="Java"><td>Java<td>500RS
<tr><td><input type=checkbox name=item2 value="C++"><td>C++<td>250RS
<tr><td><input type=checkbox name=item3 value="Linux"><td>Linux<td>450RS
<tr><td><input type=checkbox name=item4
value="Networking"><td>Networking<td>400RS
</table>
<input type=submit name="Add" value="AddToCart"><input type=submit
name="View" value="ViewCart"><input type=submit name="Check"
value="CheckOut">
</form>
</pre>
<%
String addaction=request.getParameter("Add");
if(addaction!=null) {
if(addaction.equals("AddToCart")) {
String paramname,paramval;
Enumeration em = request.getParameterNames();
while (em.hasMoreElements())
{
paramname = (String) em.nextElement();
paramval = request.getParameter(paramname);
session.setAttribute(paramname,paramval);
}
}
}
String viewaction=request.getParameter("View");
if(viewaction!=null)
if (viewaction.equals("ViewCart")){
%>
<jsp:forward page="viewcart.jsp"/>
<% }
String checkaction=request.getParameter("Check");
if(checkaction!=null)
if (checkaction.equals("CheckOut")){
%>
<jsp:forward page="checkout.html"/>

<% }
%>
</body>
</html>
<%@ page import="java.util.*"%> viewlist.jsp
<html>
<body>
<h3>You Have Purchased the Following Items:</h3>
<table border=1 bordercolor=red>
<%
Enumeration enum=session.getAttributeNames();
while(enum.hasMoreElements()){
String name=(String)enum.nextElement();
String val =(String) session.getAttribute(name);
out.println("<tr><td>" + name + "<td>" + val);
}
%>
</table>
<a href="list.jsp">Continue Shopping</a> <a href="logout.html">Finalize
Order</a><br>
</body>
</html>
<html> logout.html
<body>
<pre>
<form action="logout.jsp">
Name :<input type=text name="name">
CreditCard Number:<input type=text name="cardno">
Shipment Address :<textarea rows=5 cols=20></textarea>
<input type=submit>
</pre>
</body>
</html>

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


<%
String cname=request.getParameter("name");
%>
<html>
<body>
<h3>Dear <%= cname %><br>
You Have Purchased the Following</h3>
<table border=1 bordercolor=red>
<%
Enumeration enum=session.getAttributeNames();
while(enum.hasMoreElements()){
String name=(String)enum.nextElement();
String val =(String) session.getAttribute(name);
out.println("<tr><td>" + name + "<td>" + val);
}
%>
</table>
<h3><i> Thank You for purchasing .. please visit again</i></h3>
</body>
</html>

JSP PRG 10. EXAMPLE FOR GETTING EMPLOYEE LIST FROM DATABASE
<html>
<%@ page import="java.sql.*" %>
<pre><center>
<h3>Employee Details</h3>
<table border=1 bgcolor=yellow>
<%
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:sun");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from emp");
%>
<%
out.println("<tr><th>EmpNo</th><th>Name</th><th>Age</th><th>Dept</th></tr>");
while(rs.next())
{
out.println("<tr><td>" + rs.getString(1)+"</td><td>"+
rs.getString(2)+"</td><td>"+rs.getString(3)+"</td><td>"+rs.getString(4)+"</td></tr>");
}
%>
</table>
</pre></center>
</html>

JSP PRG 11. EXAMPLE FOR SETTING AND READING BEAN PROPERTIES
FROM JSP.
<%
response.setHeader("Cache-Control","no-cache");
%>
<jsp:useBean id="MyBean" class="sunitech.MyBean" />
<b>Get Property 1</b> <jsp:getProperty name="MyBean" property="name" /> <br>
<%-- Setting Bean Properties --%>
<jsp:setProperty name="MyBean" property="name" value="xxx
" /> <br>
<%-- Reading Bean Properties --%>
<b>Get Property 2 (getProperty way) : </b> <jsp:getProperty name="MyBean"
property="name" /> <br>
<b>Get Property 3 (getName way) : </b> <%=MyBean.getName()%>

JSP PRG 12. EXAMPLE FOR ASSIGNING PARAMETERS TO BEAN


<%
response.setHeader("Cache-Control","no-cache");
%>
<jsp:useBean id="MyBean" class="sunitech.MyBean" >
<jsp:setProperty name="MyBean" property="name" param="name"/>
<jsp:setProperty name="MyBean" property="desig" param="desig"/>
</jsp:useBean>
<%-- Reading Bean Properties --%>
<b>Get Name : </b> <%=MyBean.getName()%> <br>
<b>Get Designation : </b> <%=MyBean.getDesig()%>
go to browser and type http://localhost:8080/sunn/beanprops1.jsp?name=xxx&desig=yyy

JSP PRG 13. EXAMPLE FOR BEAN IN THE SESSION SCOPE


<%
response.setHeader("Cache-Control","no-cache");
%>
<jsp:useBean id="MyBean" scope="session" class="sunitech.MyBean" >
<jsp:setProperty name="MyBean" property="*" />
</jsp:useBean>
<h2>Bean placed in SESSION</h2>

JSP PRG 14. EXAMPLE FOR GETTING BEAN VALUE FROM SESSION AND
STOPSESSION.
<%
response.setHeader("Cache-Control","no-cache");
%>
<jsp:useBean id="MyBean" scope="session" class="sunitech.MyBean" />
<b>Propery value NAME from Session bean : </b> <%=MyBean.getName()%>
<b>Propery value DESIGNATION from Session bean : </b> <%=MyBean.getDesig()
%>

<% sessioninvalidate.jsp
response.setHeader("Cache-Control","no-cache");
session.invalidate();
%>
<h2>Session Invalidated</h2>

JSP PRG 15. EXAMPLES FOR CUSTOM TAGS IN JSP

15a:
jsp file inside ec\1.jsp
tag handler file inside ec\WEB-INF\classes\hello\hai\one.java
tag description inside ec\WEB-INF\sun.tld

1.jsp
<%@ taglib uri="/WEB-INF/sun.tld" prefix="sunworld" %>
<html>
<body>
<center>
<h2>Custom Tag Example</h2>
<sunworld:1 />
</center>
</body>
</html>

one.java
package hello.hai;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
public class one extends TagSupport {
public int doStartTag() {
try {
JspWriter out = pageContext.getOut();
out.print("<font color=red size=+3>Sun iTech</font>");
} catch(IOException e)
{
System.out.println("Error" +e);
}
return(SKIP_BODY);
}
}

sun.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC
"-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>
<tag>
<name>1</name>
<tagclass>hello.hai.one</tagclass>
<info>Outputs Sun iTech in Blue</info>
</tag>

</taglib>

15b:

jsp file inside ec\2.jsp


tag handler file inside ec\WEB-INF\classes\hello\hai\two.java
tag description inside ec\WEB-INF\sun.tld

2.jsp
<%@ taglib uri="/WEB-INF/sun.tld" prefix="sunworld" %>
<html>
<body>
<center>
<h2>Custom Tag Demo</h2>
<sunworld:2 size="7" />
</center>
</body>
</html>

sun.tld
<tag>
<name>2</name>
<tagclass>hello.hai.two</tagclass>
<info>Outputs Sun iTech in Red</info>
<attribute>
<name>size</name>
<required>false</required>
</attribute>
</tag>

two.java
package hello.hai;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
public class two extends TagSupport {
private int size = 3;
public int doStartTag() {
try {
JspWriter out = pageContext.getOut();
out.print("<font color=blue size=+" + size + ">Sun
iTech</font>");
} catch(IOException e)
{
System.out.println("Error: " +e);
}
return(SKIP_BODY);
}
public void setSize(String s) {
try {
size = Integer.parseInt(s);
} catch(Exception e)
{
}
}

15c:
jsp file inside ec\3.jsp
tag handler file inside ec\WEB-INF\classes\hello\hai\three.java
tag description inside ec\WEB-INF\sun.tld

three.jsp
<%@ taglib uri="/WEB-INF/sun.tld" prefix="sunworld" %>
<html>
<body>
<center>
<h2>Custom Tag Demo</h2>
<sunworld:repeatTag times="7"><font size=+3>Sun
iTech</font><br></sunworld:repeatTag>
</center>
</body>
</html>

sun.tld
<tag>
<name>repeatTag</name>
<tagclass>hello.hai.RepeatTag</tagclass>
<bodycontent>JSP</bodycontent>
<attribute>
<name>times</name>
<required>false</required>
</attribute>
</tag>

three.java
package hello.hai;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
public class three extends TagSupport
{
private int times = 3;
public void setTimes(int l) {
times = l;
}
public int doStartTag() {
if (times >= 1)
return EVAL_BODY_INCLUDE;
else
return SKIP_BODY;
}
public int doAfterBody() {
if ( times-- > 1 )
return EVAL_BODY_AGAIN;
else
return SKIP_BODY;
}
}

JSP PRG 16. EXAMPLES FOR MVC ARCHETECTURE

login.html
<html>
<body>
<form action="http://localhost:8070/sun/mark" method="get">
<pre>
Enter Batch Code :<input type="text" name="c"><br>
Enter Marks :<input type="text" name="m"><br>
<input type="submit">
</pre>
</form>
</body>
</html>

inside WEB-INF/StudentsData/ save the following three jsp pages

InvalidStudent.jsp
<b><h1>YOU ARE NOT A STUDENT!!!!!!!!!<h1></b>

NegativeMark.jsp
<b> <h1>MARK IS TOO LOW PLEASE WRITE RE-EXAM</h1></b>

GoodMark.jsp
<b><h1> Good!!!! Placement Department is waiting 4 u---</h1></b>

inside classes folder Marks.java

Marks.java
import DB.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Marks extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws
ServletException, IOException
{
String code=(String)req.getParameter("c");
Student s=Student.getCode(code);
String m="";
m=(String)req.getParameter("m");
if(!m.equals("")){
s.setMark(Integer.parseInt(m.trim()));
}
String ad="";
PrintWriter out=res.getWriter();
if (s.getCode().equals(""))
{
ad = "/WEB-INF/StudentDetails/InvalidStudent.jsp";
}
else if (s.getMark() < 0 || s.getMark() <=60)
{
ad = "/WEB-INF/StudentDetails/NegativeMark.jsp";
req.setAttribute("badStudent", s);
}
else if ( s.getMark() > 60)
{
ad = "/WEB-INF/StudentDetails/GoodMark.jsp";
}
if(ad.equals(""))
{
ad= "/login.html";
}
RequestDispatcher dispatcher =req.getRequestDispatcher(ad);
dispatcher.forward(req, res);
}
}

inside classes/DB/Student.java

Student.java
package DB;
public class Student {
private String c;
private int mark;
public Student(String co) {
c = co;
mark=0;
}
public String getCode() {
return c;
}
public int getMark() {
return mark;
}
public void setCode(String v) {
c = v;
}
public void setMark(int v) {
mark = v;
}
public static Student getCode(String code)
{
return new Student(code);
}
}

You might also like