Saturday 3 January 2015

Inheritance and constructor overloading in JSP

Inheritance is probably the back bone of OOPS.
I have done it so many times in Java, C++, even python also. But this is my first time in JSP. Alas I am not writing any servlet!. This is just a JavaServer Page.

And this is how I did it. Use this code, build your own JSP. Just remember one thing that when you write your class do it within <%!  %> instead of <%  %>. Copy paste the code and save it with .jsp extension.

//---------------------------------------------------------------------------------------------------------------------

<html>
<head>
<%@ page language="java" import ="java.lang.*,java.io.*" %>
<%!
class Shape
{
 int Radius;
 int Width;
 int Height;
 Shape()
 {
  this.Width=0;
  this.Height=0;
  this.Radius=0;
 }
 Shape(int Radius)
 {
  this.Radius=Radius;
 }

 Shape(int Width,int Height)
 {
  this.Width=Width;
  this.Height=Height;
 }
}

class Circle extends Shape
{
 Circle()
 {
  super();
 }
 Circle(int Radius)
 {
  super(Radius);
 }
 double Area()
 {
  return Math.round(Math.PI*Radius*Radius * 100.00)/100.00;
 }
}

class Rectangle extends Shape
{
 Rectangle()
 {
  super();
 }
 Rectangle(int Width,int Height)
 {
  super(Width,Height);
 }
 double Area()
 {
  return Math.round(Width*Height * 100.00)/100.00;
 }
}
%>
</head>
<body>
<form action="classexample.jsp" method="post">
<select id="choice" onchange="displayelement()">
 <option>Circle</option>
 <option>Rectangle</option>
</select>
<div id="inputdiv"></div>
<script>
function displayelement()
{
obj=document.getElementById("choice");
if(obj.value=="Circle")
 inputdiv.innerHTML="Enters Radius : <input name='rad1' type=text value='' /><br><input type='submit' value='Calculate' />";
else if(obj.value=="Rectangle")
 inputdiv.innerHTML="Enter Width : <input name='width1' type=text value='' /><br>Enter Height     : <input name='height1' type=text value='' /><br><input type='submit' value='Calculate' />";
}
</script>
</form>
<form>
<%
 if(request.getParameter("rad1")!=null)
 {
  int rad=Integer.parseInt(request.getParameter("rad1"));
  Circle c = new Circle(rad);
  %><div><%= c.Area() %></div> <%
 }
 else if(request.getParameter("height1")!=null&&request.getParameter("width1")!=null)
 {
  int width=Integer.parseInt(request.getParameter("width1"));
  int height=Integer.parseInt(request.getParameter("height1"));
  Rectangle r = new Rectangle(width,height);
  %><div><%= r.Area() %></div> <%
 }
%>
</form>
</head>

No comments: