3

Before the translation phase, there was a <%! .... %> code line in my JSP page. I know that this would be run only once in the translated servlet. Does it mean that the servlet engine puts the code in the init() method in the servlet?

What I want to learn is: which kinds of code go to which methods after translation?

Thanks in advance.

Scott Buchanan
  • 1,163
  • 1
  • 11
  • 28
Erdal76t
  • 113
  • 1
  • 9

2 Answers2

5

Here is an example:

This JSP code:

<%@ page import="java.util.*" %> <!-- 1 -->
<%! private Date date; %>        <!-- 2 -->
<% date = new Date(); %>         <!-- 3 -->
Current date: <%= date %>        <!-- 4 -->

Will get translated to:

import java.util.*; // 1

public class ServletAbc extends GenericServlet {

    private Date date; // 2

    public void service(ServletRequest request,ServletResponse response)
                throws IOException,ServletException{

        PrintWriter out=response.getWriter();

        date = new Date(); // 3

        out.println("Current date: "); // 4
        out.println(date);
    }
}

Note that minor parts of the translation are container-depended. E.g. the out.println() statements might be translated to out.println("Current date: " + date); as well.

Uooo
  • 6,204
  • 8
  • 36
  • 63
  • would the class level parameters be private all the times? – Erdal76t Mar 18 '13 at 13:38
  • @Erdal76t sorry forgot the `private` keyword in the JSP. The code inside `<%! ... %>` will be inserted as is on class level. You can also declare static variables and methods there. – Uooo Mar 18 '13 at 13:43
2

At the time of code compilation code containing inside <%! .... %> this tag is consider as class member of servlet.

and

code containing inside <% .... %> this tag goes into the service() method of servlet.

If you want to see the generated java file, go to tomcat/work/..... directory.

File will be created with name as JspFileName_jsp.java and JspFileName_jsp.class

For better understandings visit this link

Sagar Dalvi
  • 200
  • 1
  • 9