# Understanding JSP

### &#x20;CASE 1: Try to create method inside <% ,.... %>

```markup
<%@ 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>
```

![](https://1449372731-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LTkdt3HaaBdyfrO73EV%2F-LeSUAV5W9bHgkkOIBXw%2F-LeSYrPGDKnj67QP0gXE%2FScreen%20Shot%202019-05-09%20at%2010.35.35%20PM.png?alt=media\&token=6c229af7-38e9-4b88-936e-73b313670a68)

#### We cannot use methods inside <%%>

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

```markup
<%@ 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>
```

![](https://1449372731-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LTkdt3HaaBdyfrO73EV%2F-LeSUAV5W9bHgkkOIBXw%2F-LeSZtsaWV4vxKAmoXiQ%2FScreen%20Shot%202019-05-09%20at%2010.40.45%20PM.png?alt=media\&token=4f8372cc-331b-4723-ad0e-467a1aac28d3)

### Behind the scene :

#### JSP is converted to a class so this test.jsp is converted to  a java class&#x20;

#### Java class is basically a servlet

#### Every jsp is a servlet

#### When we run it on server (tomcat) , tomcat  converts jsp to servlet&#x20;

#### 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 : <%!..%>&#x20;
