Servlet & JSP – 18 – Implicit Object & JSP Lifecycle

Merhaba Arkadaslar,
Onceki bolumde JSP konusuna giris yapmistik. Hatirlayacagimiz gibi JSP Lifecycle’inda JSP dosyalarinin .java dosyalarina donusturulme islemi vardi yani translate islemi.

Nerede bu Java dosyalari ?

JSP dosyalarinin .java dosyalarina donusturulme isleminden bahsettik. Peki bu .java dosyalari nerede bulunmaktadir ?

/webapps/injavawetrust/01_HelloJSP

Dizinine gittigimizde burada 01_HelloJSP dosyamizin JSP halini goruyoruz.  JSP dosyalarimizin .java ve .class hali Tomcat dizinenden work/Catalina/localhost dizininde projemizin context root adresinde /org/apache/jsp klasoru altinda yer alacaktir.

/home/levent/Java/Tomcat/apache-tomcat-7.0.52/work/Catalina/localhost/injavawetrust/org/apache/jsp

 helloJSP_jsp.java

/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/7.0.59
 * Generated at: 2015-02-16 08:13:57 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._01_005fHelloJSP;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.util.List;
import java.util.ArrayList;

public final class helloJSP_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

public int addNumber(int n1, int n2) {
    sum = n1 + n2;
    return sum;
  }

  private int sum = 0;
  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 javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.tomcat.InstanceManager _jsp_instancemanager;

  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
  }

  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("\r\n");
      out.write("<!-- HTML yorum satiri -->\r\n");
      out.write("<!-- @ page satiri JSP dosyasini olusturdugumuzda gelmektedir. \r\n");
      out.write("Burada encoding ve charset ayari yapabiliriz. -->\r\n");
      out.write("\r\n");
      out.write("\r\n");
      out.write("<!--JSP dosyamiza import islemi yapabiliriz. \r\n");
      out.write("Birden fazla import islemi icin araya virgul koyabiliriz.-->\r\n");
      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("\t<!-- JSP Scriptlet kodumuz! -->\r\n");
      out.write("\t");

    System.out.println("Java Scriptlet arasinda Java kodumuzu yazabiliriz");
    for (int i = 0; i < 5; i++) {
      System.out.println("i:" + i);
      out.println("i:" + i);
    }

    List<String> testList = new ArrayList<String>();
    testList.add("levent");
  
      out.write("\r\n");
      out.write("\r\n");
      out.write("\t<br>\r\n");
      out.write("\t");

    String name = "Levent";
    int age = 24;
    out.println(name);
    out.println(age);
  
      out.write("\r\n");
      out.write("\t<br>\r\n");
      out.write("\t\r\n");
      out.write("\t<!--JSP Expression  -->\r\n");
      out.write("\t\r\n");
      out.write("\t");
      out.print(name);
      out.write('\r');
      out.write('\n');
      out.write(' ');
      out.print(age);
      out.write("\r\n");
      out.write("\r\n");
      out.write("\t<br>\r\n");
      out.write("\t");
      out.print(addNumber(5, 5));
      out.write("\r\n");
      out.write("\r\n");
      out.write("\t<!-- JSP Declaration -->\r\n");
      out.write("\t\r\n");
      out.write("\t");
      out.write("\r\n");
      out.write("\r\n");
      out.write("\t<br>\r\n");
      out.write("\t");
      out.print(addNumber(5, 10));
      out.write("\r\n");
      out.write("\r\n");
      out.write("\t");
      out.write("\r\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);
    }
  }
}

helloJSP_jsp.java dosyamizi inceleyelim

  • Oncelikle dikkat edecek olursak JSP dosyamizin ismi helloJSP.jsp ‘di .java dosyasina cevrilirken sonuna _jsp eki geldi.
    Bu sinifimiz org.apache.jasper.runtime.HttpJspBase sinifini kalitmaktadir. Bu sinif Apache Tomcat’e ozel bir siniftir. Baska bir Servlet Container kullanilsa farkli bir sinif olacaktir.
  • Dikkat ederseniz org.apache.jasper.runtime.HttpJspBase sinifi javax.servlet.http.HttpServlet sinifini kalitmakta ve HttpJspPage arabirimini uygulamaktadir ve javax.servlet.jsp.HttpJspPage arabiriminin hiyerarsisine bakalim ;
package org.apache.jasper.runtime;
public abstract class HttpJspBase extends HttpServlet implements HttpJspPage {...}
package javax.servlet.jsp;
public interface HttpJspPage extends JspPage { 
..
}

package javax.servlet.jsp;
public interface JspPage extends Servlet {
}
  • Sonrasinda tanimladigimiz metodu ve instance variable’i goruyoruz, aynen tanimladigimiz haliyle yer almaktadir. _jspInit , _jspDestroy ,  _jspService metotlari JSP lifecycle metotlaridir. _jspService metodunda implicit objelerinin tanimi yapilmaktadir.
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 blogunda sonrasinda bu implicit objelere deger atanma islemi yapiliyor bu implicit objeleri yeri geldikce inceleyecegiz.

JSP implicit objects;

JspWriter out
HttpServletRequest request
HttpServletResponse response
ServletContext application
HttpSession session
ServletConfig config
Throwable exception
PageContext pageContext
Object page
  • Sonrasinda dikkat edecek olursak out.write ve out.print metodu ile tum HTML kodlarini bu metot ile yaziyor. Tanimladigimiz degiskenlerin _jspService metodu icerisinde yer aldigini belirtmistim;
 String name = "Levent";
 int age = 24;

JSP Expression’da out.print metoduna donusturulur.

<%=name %>
out.print(name);

JSP Lifecycle/Yasam Dongusu

JSP lifecycle metotlari ;

  • jspInit() 
  • jspDestroy() 
  • _jspService()

jspInit ve jspDestroy metotlarini override edebiliriz fakat _jspService metodunu override edemeyiz.

package javax.servlet.jsp;
...
public interface JspPage extends Servlet {
    public void jspInit();
    public void jspDestroy();
}

package javax.servlet.jsp;
....
public interface HttpJspPage extends JspPage {
 public void _jspService(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException;

org.apache.jasper.runtime.HttpJspBase abstract sinifini incelersek;

    @Override
    public final void init(ServletConfig config) 
        throws ServletException 
    {
        super.init(config);
        jspInit();
        _jspInit();
    }

    @Override
    public final void destroy() {
        jspDestroy();
        _jspDestroy();
    }

Biz jspInit ve jspDestroy metotlarini override edebiliriz. Tomcat translation isleminde _jspInit ve _jspDestroy metotlarini kullandigi icin bu metotlari override edersek calisma zamaninda hata aliriz.

HTTP Status 500 – Unable to compile class for JSP

_jspService metodunu override etmeye calistigimizda duplicate method hatasini derleme zamaninda aliriz.

public void _jspService(HttpServletRequest request, HttpServletResponse response) 

JSP lifecycle da Servlet lifecycle gibidir.

  • Servlet Container, web.xml dosyasini okur.
  • Sonrasinda ilgili JSP dosyasini calistirdigimizda , JSP dosyamiz .java dosyasina Translate edilir.
  • .java dosyamiz .class uzantili dosyamiza Compile edilir.
  • Sevlet Container, olusturulan Servlet .class dosyasini yukler/ Load.
  • Container, yeni bir obje olusturur ve jspInit metodu cagrilir.
  • Sonrasinda yeni bir thread olusturulur ve _jspService metodu cagrilir.
  • Eger JSP dosyasina ihtiyac kalmazsa jspDestroy metodu cagrilir. Ornegin JSP dosyamizda degisiklik yaparsak tekrar bu yasam dongusu baslayacaktir bu nedenle oncelikle jspDestroy calismalidir.
  • Translation ve Compilation sadece bir kez gerceklestirilir.

WebContent klasoru altina yeni bir klasor ve JSP dosyasi olusturalim ;
02_Lifecycle
lifecycle.jsp

lifecyle.jsp

<%@ 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>Lifecycle</title>
</head>
<body>

  <%!
  
  public void jspInit() {
    ServletConfig config = getServletConfig();

    String email = config.getInitParameter("email");
    String site = config.getInitParameter("site");
    System.out.println("Email:"+email);
    System.out.println("Site:"+site);
    
  }

  public void jspDestroy()
  {
    System.out.println("Destroy");
  }
  // Duplicate Method , derleme hatasi verir!
  //public void _jspService(HttpServletRequest request, HttpServletResponse response) {
  //}
   %>

</body>
</html>

JSP dosyamiz icin init parameter olusturalim ;

	<servlet>
		<servlet-name>Lifecycle</servlet-name>
		<jsp-file>/02_Lifecycle/lifecycle.jsp</jsp-file>
		<init-param>
			<param-name>email</param-name>
			<param-value>erguder.levent@gmail.com</param-value>
		</init-param>

		<init-param>
			<param-name>site</param-name>
			<param-value>www.injavawetrust.com</param-value>
		</init-param>

	</servlet>
	<servlet-mapping>
		<servlet-name>Lifecycle</servlet-name>
		<url-pattern>/lifecycle.jsp</url-pattern>
	</servlet-mapping>

Burada Servlet tanimina benzer sekilde tanimlama yaptik farklilik olarak <jsp-file> etiketini kullandik. JSP dosyamiz 02_Lifecycle klasoru altinda yer almakta bu noktaya dikkat ederek <jsp-file> etiketinde yazmaliyiz.

JSP dosyamizi calistirdigimizda Eclipse Console’da;

Email:erguder.levent@gmail.com
Site:www.injavawetrust.com

Yazimi burada sonlandiriyorum.
Herkese Bol Javali Gunler dilerim.
Be an oracle man , import java.*;
Levent Erguder
OCP, Java SE 6 Programmer
OCE, Java EE 6, Web Component Developer

Print Friendly, PDF & Email

Leave a Reply

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