Understanding JSP

CASE 1: Try to create method inside <% ,.... %>

<%@ 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>Insert title here</title>
</head>
<body>
	<h1>Hello</h1>
	<%!public int sum(int a, int b) {
		return a + b;
	}%>

	Value of sum of 67 and 89 is
	<%=sum(67, 89)%>
	<br>
	<%
	public int sum1(int a, int b) {
	
	}
		return a + b;
		int i = 3;
		int j = 8;
		int k = i + j;
		out.println("Value of k is " + k);
	%>
	<br>

	<%
		int l = 3;
		int m = 12;
		int n = l + m;
	%>
	Value of n is
	<%=n%>

</body>
</html>

We cannot use methods inside <%%>

CASE 2: We can add html code between the JSP scriplets.

<%@ 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>Insert title here</title>
</head>
<body>
	Simple for loop
	<br>
	<% for(int i = 0; i<5; i++) { %>
	
		<br>
		Value of i is = <%=i %>
	
	<%} %>
	
</body>
</html>

Behind the scene :

JSP is converted to a class so this test.jsp is converted to a java class

Java class is basically a servlet

Every jsp is a servlet

When we run it on server (tomcat) , tomcat converts jsp to servlet

Default is get method , Every <%...%> is converted added to doGet method of the servlet class is generated from JSP.

All the HTML code will be put into out.write() by tomcat

Thats why method declared inside <%..%> gives the compilation as we cannot define a method inside a method for that we need : <%!..%>

Last updated

Was this helpful?