Tuesday, February 4, 2014

JSP basic


1. Directive
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@page import="java.util.Date" %>

2. Declaration
In JSP, you can declare variables
in three ways:
<% int k = 0; %>
<%! int k = 0; %>
<%! static int k = 0; %>
The first declaration means that a new variable is created for each incoming HTTP client request;
the second one means that a new variable is created for each new instance of the servlet; and the third
one means that the variable is shared among all instances of the servlet.

Normally, Tomcat instantiates each one of these classes only once
and then creates a Java thread for each incoming request. It then executes the same servlet object within
each thread. If the application runs on a distributed environment or for high numbers of requests,
Tomcat can instantiate the same servlet more than once. Therefore, only the third declaration
guarantees that the variable will be shared among all requests.

3. Include another JSP on page
   <jsp:include page="index.jsp"/>

4.Scope
There are four possible scopes. Inorder of increasing generality, they are: page, request, session, and application.

5.Using an Attribute to Enable and Disable Conditional Code
One of the advantages of using JSP is that the web server doesn’t need to reinterpret the source file of a
page every time a client requests that page. The JSP container translates each JSP page into a Java file
and compiles it into a class, but this only happens when you update the JSP source. You might like to be
able to switch on or off some particular functionality for debugging or other purposes, without having to
edit one or more file and force Tomcat to recompile them when you flip the switch. To achieve this
result, you only need to wrap the functionality in question inside a conditional statement, as the

following:




































6. The out Object
The following three lines have exactly the same effect on the response:
<% out.print("abc"); %>
<%="abc"%>
abc

7.MVC
The Model 2 Architecture
A better solution, more suitable for larger applications, is to split the functionality further and use JSP
exclusively to format the HTML pages. This solution comes in the form of the JSP Model 2 architecture,
also known as the model-view-controller (MVC) design pattern (see Figure 3-2).






















No comments:

Post a Comment