Declarations

Declaration is used to declare variables and methods in a JSP page’s scripting language. All variables and methods in JSP declaration would be translated into declaration inside respective Servlet class.

JSP declaration syntax

<%! scripting language declaration %>

JSP declaration sample code (github)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>jsp.ourownjava.com</title>
</head>
<body>

<!-- jsp declaration example-->
<%! 
public int sum(final int x, final int y){
    return x + y;
}
%>

<!-- calling method -->
<% out.println("sum of 10, 10 is "+sum(10, 10));%>

</body>
</html>

How to run the JSP declaration sample program?

Leave a comment

Your email address will not be published. Required fields are marked *