In the previous example, we have seen that how to write JSPs and write java code inside it. If you have previously worked in Java, you know that in Java, everything is a class. But in JSP, we have not seen anything like that. Let’s have some experiments, to understand it in a little bit of more detail.
Experiment 1
Where to Write method definitions In JSP?
Analysis:
Remove the method from definition tag and add it to the script tag, it will surely give an error as mentioned in the below source.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<%@ 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> <body> <%! // method removed from here %> <h3> First JSP Test...!</h3> <% // Method inserted here public int add(int a,int b){ return a+b; } int i,j,k; i=10;j=4; k=j-i; //out.println("Dynamic Java value : "+k); skipping this line k=add(123,321); %> The value returned from add is : <%=k%> </body> </html> |
Now ignore the error and try to run this JSP file by Right clicking on the file and select “RunAs” then “RunOnServer”. This will give you the 505 Error
Result:
This experiment tells us that we could not have a method defined in the script tag that is <% %>.
Let’s have our correct code back which is shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<%@ 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> <body> <%! public int add(int a,int b){ return a+b; } %> <h3> First JSP Test...!</h3> <% int i,j,k; i=10;j=4; k=j-i; //out.println("Dynamic Jave value : "+k); skiping this line k=add(123,321); %> The value returned from add is : <%=k%> </body> </html> |
Experiment 2
Write plain HTML between JSP script tags:
Question: How to separate Static content from dynamic content?
In this experiment, we will try to find the answer to above question.
Analysis :
Let’s add a for loop to display dynamic values in our source with the help of scripting tag; we can add as many tags as we want according to our needs. Notice the script tag where for loop is implemented in the below source. It has a static and dynamic part in one script tag. You can use the below source and try to run the code. Try to run this JSP file by Right clicking on the file and select “RunAs” -> “RunOnServer”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<%@ 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> <body> <%! public int add(int a,int b){ return a+b; } %> <h3> First JSP Test...!</h3> <% int i,j,k; i=10;j=4; k=j-i; k=add(123,321); %> The value returned from add is : <%=k%> <% for(i=0;i<4;i++){ out.println("<br> Value of i = "+i);// THIS LINE HAS THE STATIC PART } %> </body> </html> |
This will be the output.
Now we will separate the static part from the dynamic path in the source below, by adding more ending and closing scripting tags inside the code. You can notice the line where I have commented in the source.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<%@ 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> <body> <%! public int add(int a,int b){ return a+b; } %> <h3> First JSP Test...!</h3> <% int i,j,k; i=10;j=4; k=j-i; k=add(123,321); %> The value returned from add is : <%=k%> <% //Notice this part of code for(i=0;i<4;i++){ %> <br>Value of i = <%=i%> <% } %> </body> </html> |
Try to run the above JSP file by Right clicking on the file select “RunAs” -> “RunOnServer”
Result:
This tells that we can have static code between two scripting tags, and it will be treated as same.
Combined Results of Exp1 and Exp2:
Above two demonstrations are to describe the two most important behaviors of the scripting tags.
- We couldn’t define a function inside the scripting tag
- We can use simple HTML code between the two scripting tags.
How JSP works?
Let’s explain it a bit more in detail; JSP is a class. Our “FileName.jsp” will we converted into the Java Class by the web container, the Java class that is created is a servlet that runs on the container. Every JSP class that is deployed on the server( in our case tomcat), Tomcat takes the JSP and converts it into a Servlet class. If we have to write all the JSP logic code in the servlet we will do it in the doGet() method. So every scripting code that is in the JSP file will be added in to doGet() Method of the generated servlet and for the static content to display we will use printWriter.println(), so that’s exactly what tomcat does as well, it takes the static content and places it into the printWriter.The println() method of the generated servlet.
So, that is the reason of why we cannot have method definition inside the scripting tag, because scripting tag part will go in the doGet() method of the generated servlet.
We can also access the generated servlet class in the tomcat folder. Go to the tomcat installation directory in my case it is <you tomcat installation directory>\apache-tomcat-7.0.67\work\Catalina\localhost\SimpleServletProject\org\apache\jsp this path may also vary according to the tomcat versions.
This directory has two files till know first is FirstJspFile_jsp.java and the second is FirstJspFile_jsp.class file
You can open the Java file and look into the auto-generated source code; I have also placed the code of “FirstJspFile_jsp.java” below if you could not find the directory in your tomcat installation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 |
/* * Generated by the Jasper component of Apache Tomcat * Version: Apache Tomcat/7.0.67 * Generated at: 2016-07-20 16:25:53 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class FirstJspFile_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { public int add(int a,int b){ return a+b; } private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; private volatile javax.el.ExpressionFactory _el_expressionfactory; private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager; public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public javax.el.ExpressionFactory _jsp_getExpressionFactory() { if (_el_expressionfactory == null) { synchronized (this) { if (_el_expressionfactory == null) { _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); } } } return _el_expressionfactory; } public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() { if (_jsp_instancemanager == null) { synchronized (this) { if (_jsp_instancemanager == null) { _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig()); } } } return _jsp_instancemanager; } public void _jspInit() { } public void _jspDestroy() { } public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { final javax.servlet.jsp.PageContext pageContext; javax.servlet.http.HttpSession session = null; final javax.servlet.ServletContext application; final javax.servlet.ServletConfig config; javax.servlet.jsp.JspWriter out = null; final java.lang.Object page = this; javax.servlet.jsp.JspWriter _jspx_out = null; javax.servlet.jsp.PageContext _jspx_page_context = null; try { response.setContentType("text/html; charset=ISO-8859-1"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\r\n"); out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\r\n"); out.write("<html>\r\n"); out.write("<head>\r\n"); out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">\r\n"); out.write("<title>Insert title here</title>\r\n"); out.write("</head>\r\n"); out.write("<body>\r\n"); out.write("\r\n"); out.write("\r\n"); out.write("<h3> First JSP Test...!</h3>\r\n"); int i,j,k; i=10;j=4; k=j-i; k=add(123,321); out.write("\r\n"); out.write("\r\n"); out.write("The value returned from add is : "); out.print(k); out.write("\r\n"); out.write("\r\n"); //Notice this part of code for(i=0;i<4;i++){ out.write("\r\n"); out.write("\t\t<br>Value of i = "); out.print(i); out.write('\r'); out.write('\n'); } out.write(" \r\n"); out.write("</body>\r\n"); out.write("</html>"); } catch (java.lang.Throwable t) { if (!(t instanceof javax.servlet.jsp.SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { if (response.isCommitted()) { out.flush(); } else { out.clearBuffer(); } } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } } |
Summary:
In this tutorial, we have accomplished following things
- Basic concept of JSP
- JSP tags Explained in detail
- How web Container handles JSP