Declaration of variables & methods
Scripting Elements- Declaration of variables:
Variables declared within <% and %> will be local to the service method of the generated servlet and each request will have a separate copy of this variable .
<%
int data;
%>
Variable declared within <%! and %> will be a data member of the generated Servlet class and all the requests wil use the same copy of this variable.
<%!
double amount;
%>
Scripting Elements-Declaration of methods:
o Methods also can be declared using scripting elements
o All the methods should be declared within <%! And %> and they become a method the generated Servlet.
JSP Declarations:
We can declare more than one variable using the following syntax:
<%! declaration; [ declaration; ] ... %>
Ex.
<%! inti= 0; double j=0.0; %>
<%! inta, b, c; %>
<%! Circle a = new Circle(2.0);%>
Ex.
<H1>Some Heading</H1>
<%!
private String randomHeading() {
return("<H2>" + Math.random() + "</H2>");
}
%>
<%= randomHeading() %>
• Better alternative:
–Make random heading a static method in a separate class
JSP Expression:
JSP Expression: <%= Java Expression %>
Result
–Expression evaluated, converted to String, and placed into HTML page at
the place it occurred in JSP page
–That is, expression placed in jspServiceinside out.print
-The expression element should not end an expression with semicolon.
•Examples
Current time: <%= new java.util.Date() %>
Your hostname: <%= request.getRemoteHost() %>
<html>
<head>
<title>Testing JSP Expression</title>
</head>
<body>
<p>
<% String name = “UdayKiran”; %>
Hello<%= name%>
Today's date: <%= new java.util.Date()%>
</p>
</body>
</html>
Scriptlets:
• Format
<% Java Code %>
• Result
–Code is inserted into servlet’s jspService() method
• Example
<%
String queryData= request.getQueryString();
out.println("Attached GET data: " + queryData);
%>
<% response.setContentType("text/plain"); %>
•A scriptlet contains Java code that is executed every time the JSP is invoked.
•By itself a scriptlet does not generate HTML.
•If a scriptlet wants to generate HTML, it can use a implicit variable called "out".This variable is already predefined for scriptlets.
Scripting Elements : Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<%
String bgColor= request.getParameter("bgColor");
if ((bgColor== null)||(bgColor.trim().equals(""))){
bgColor= "WHITE";
}
%>
<body BGCOLOR="<%= bgColor%>">
<H2 ALIGN="CENTER">Testing a Background of "<%= bgColor%>"</H2>
</body>
</html>
Previous
Comments
Post a Comment