To use Java statements in JSP, you can use scripting elements.
1. Scriptlets
2. Expressions
3. Declarations
Syntax | EX: | _jspService(){ |
---|---|---|
<% -- %> |
<% int a = 99; out.println(a); system.out.println(a); %> |
-- int a = 99; out.println(a); system.out.println(a); -- } |
Any valid Java statements are allowed inside the scriptlets.
All the statements of the scriptlet will be stored inside the _jspService() method of the translated servlet.
Syntax | EX: | class show_jsp { |
---|---|---|
<% ! -- %> |
<% ! String str=”JTC”; void m1(){ … } %> |
String str=”JTC”; void m1(){ … } … _jspService(){ … } |
Expression is a short-cut form of out.print( exp).
All the expressions will be converted to out.print(...) and will be printed inside the
_jspService() method of the translated servlet.
Expression should not end with ; (semicolon).
<%= "hello"; %> out.print("hello";); // INVALID
Files Required For Program
1. hello.jsp
2. web.xml
1. hello.jsp
<%@ page import="java.util.Date,java.io.*"
isErrorPage="true"
session="false" %>
<!DOCTYPE html>
<html>
<body>
<h3> Welcome to JTC</h3>
<%
int a=10;
int b=20;
int sum = a+b;
show();
%>
<h3> Hello Guys !!!</h3>
<h3> Sum : <%= sum %> </h3>
<h3> Hai Guys !!!</h3>
<%!
int x=99;
static int y=88;
public void show(){
System.out.println("I am show()");
}
%>
</body>
</html>
2. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app …>
<display-name>Lab2</display-name>
<welcome-file-list>
<welcome-file>hello.jsp</welcome-file>
</welcome-file-list>
</web-app>
Syntax | EX: | class hellojsp { |
---|---|---|
<% ! java Declaration %> |
<% ! String str=”JTC”; void m1(){ } %> |
String str=”JTC”; void m1(){ } } |
Methods, Blocks, Constructors, Class level variables are allowed inside theDeclaration Tag.
All the statements inside the Declaration Tag will be placed directly insidethe translate servlet class.