viernes, 24 de marzo de 2017

Hackerank

Most HackerRank challenges require you to read input from stdin (standard input) and write output to stdout (standard output).
One popular way to read input from stdin is by using the Scanner class and specifying the Input Stream as System.in. For example:
Scanner scanner = new Scanner(System.in);
String myString = scanner.next();
int myInt = scanner.nextInt();
scanner.close();

System.out.println("myString is: " + myString);
System.out.println("myInt is: " + myInt);
The code above creates a Scanner object named  and uses it to read a String and an int. It then closes the Scanner object because there is no more input to read, and prints to stdout using System.out.println(String). So, if our input is:
Hi 5
Our code will print:
myString is: Hi
myInt is: 5

import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int a = scan.nextInt();
        int b = scan.nextInt();
        int c = scan.nextInt();
        scan.close();
        // Complete this line
        // Complete this line

        System.out.println(a);
        System.out.println( b);
        System.out.println( c);
        // Complete this line
        // Complete this line
    }
}




Triki part nextLine() toma los expacios tambien, cosa que next no lo hace

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package hackerrank1;

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Hackerrank1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
            int i = 4;
        double d = 4.0;
        String s = "HackerRank ";

        Scanner scan = new Scanner(System.in);
        int j=0;

String e="hello";

int myInt = scan.nextInt();
int myInt2 = scan.nextInt();
scan.nextLine();
String myString = scan.nextLine();

scan.close();


double e1= myInt2*1.0;

System.out.println(i+ myInt);
System.out.println(d+ e1);
System.out.println("myString is: " + myString);




    }

**************************

otro ejemplo
import java.util.Scanner;

public class CadenaDeCaracteres2 {
    public static void main(String[] ar) {
        Scanner teclado=new Scanner(System.in);
        String apenom1,apenom2;
        int edad1,edad2;
        System.out.print("Ingrese el apellido y el nombre:");
        apenom1=teclado.nextLine();
        System.out.print("Ingrese edad:");
        edad1=teclado.nextInt();
        System.out.print("Ingrese el apellido y el nombre:");
        teclado.nextLine();
        apenom2=teclado.nextLine();
        System.out.print("Ingrese edad:");
        edad2=teclado.nextInt();
        System.out.print("La persona de mayor edad es:");
        if (edad1>edad2) {
            System.out.print(apenom1);
        } else {
            System.out.print(apenom2);
        }
    }
}

jueves, 23 de marzo de 2017

JAVA INTERVIEW TOP QUESTIONS

Interview 


1.- Checked exceptions are checked at compile-time and Unchecked exceptions are not checked at compile time.  It means that the unchecked exceptions occur at runtime.

2.-  The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.
If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

3.- Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrown by the overridden method.


4.- A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data.
5.-Marker interface in Java is interfaces with no field or methods or in simple word empty interface in java is called marker interface.

6.-
Shallow cloning is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.
A deep cloning copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.



The rules for overriding a method are as follows:
¡ The argument list must exactly match that of the 
overridden method.
¡ The return type must exactly match that of the 
overridden method.
¡ The access level must not be more restrictive than that 
of the overridden method.
¡ The access level can be less restrictive than that of 
the overridden method.
¡ The overriding method must not throw new or broader 
checked exceptions

The rules for overloading a method are as follows:
¡ Overloaded methods must change the argument list.
¡ Overloaded methods can change the return type.
¡ Overloaded methods can change the access modifier.
¡ Overloaded methods can declare new or broader checked 
exceptions.
¡ A method can be overloaded in the same class or in a 
subclass.

Restriction imposed on Method Overloading are 
a) should done with in a same class.
b) it should have same name of overloading method.
c) its arguments or parameter should be different 
irrespective of return type.

Restriction imposed on Method Overriding are
a) should done with its derived class 
b) should have same name of parent method and arguments 
too.


Race condition in Java is a type of concurrency bug or issue which is introduced in your program because  parallel execution of your program by multiple threads at same time, Since Java is a multi-threaded programming language hence risk of Race condition is higher in Java which demands clear understanding of what causes a race condition and how to avoid thatAnyway Race conditions are just one of hazards or risk presented by  use of multi-threading in Java just like deadlock in JavaRace conditions occurs when two thread operate on same object without proper synchronization and there operation interleaves on each other. Classical example of Race condition is incrementing a counter since increment is not an atomic operation and can be further divided into three steps like read, update and write. if two threads tries to increment count at same time and if they read same value because of interleaving of read operation of one thread to update operation of another thread, one count will be lost when one thread overwrite increment done by other thread. atomic operations are not subject to race conditions because those operation cannot be interleaved. This is also a popular multi-threading interview questions during core java interviews. In this article we will see how to find race condition in Java and  two sample code patterns which often causes race conditions in Java.


I know what is marker interface - An interface with no methods. Example: Serializable, Remote, Cloneable.
Marker interface in Java is interfaces with no field or methods or in simple word empty interface in java is called marker interface.
Your understanding is correct. The marker interface also defines a type. It can thus be used in method signatures. For example, Hibernate's Session.get() method takes a Serializable as argument. It avoids passing a primary key that would not be serializable as argument.
Note that Cloneable is, retrospectively, seen as a bad design choice.
Serializable could certainly have been implemented with an annotation if those had existed when serialization was implemented.
Marker interfaces are, most of the time, an anti-pattern. An interface should define a polymorphic behaviour. A marker interface can be replaced by an annotation.




Preguntas
JSP implicit objects
Directivas

Ciclo de vida

Jsp Implicit Objects
BY CHAITANYA SINGH | FILED UNDER: JSP TUTORIAL
These objects are created by JSP Engine during translation phase (while translating JSP to Servlet). They are being created inside service method so we can directly use them within Scriptlet without initializing and declaring them. There are total 9 implicit objects available in JSP.
Implicit Objects and their corresponding classes:
out
javax.servlet.jsp.JspWriter
request
javax.servlet.http.HttpServletRequest
response
javax.servlet.http.HttpServletResponse
session
javax.servlet.http.HttpSession
application
javax.servlet.ServletContext
exception
javax.servlet.jsp.JspException
page
java.lang.Object
pageContext
javax.servlet.jsp.PageContext
Config
javax.servlet.ServletConfig
1.    Out: This is used for writing content to the client (browser). It has several methods which can be used for properly formatting output message to the browser and for dealing with the buffer.
Read full article here » 
OUT implicit object with examples.
2.    Request: The main purpose of request implicit object is to get the data on a JSP page which has been entered by user on the previous JSP page. While dealing with login and signup forms in JSP we often prompts user to fill in those details, this object is then used to get those entered details on an another JSP page (action page) for validation and other purposes.
Read full article here » 
Request implicit object with examples.
3.    Response: It is basically used for modfying or delaing with the response which is being sent to the client(browser) after processing the request.
Read full article here » 
Response implicit object with examples.
4.    Session: It is most frequently used implicit object, which is used for storing the user’s data to make it available on other JSP pages till the user session is active.
Read full article here » Session implicit object with examples.
5.    Application: This is used for getting application-wide initialization parameters and to maintain useful data across whole JSP application.
Read full article here » 
Application implicit object with examples.
6.    Exception: Exception implicit object is used in exception handling for displaying the error messages. This object is only available to the JSP pages, which has isErrorPage set to true.
Read full article here » 
Exception implicit object with examples.
7.    Page: Page implicit object is a reference to the current Servlet instance (Converted Servlet, generated during translation phase from a JSP page). We can simply use this in place of it. I’m not covering it in detail as it is rarely used and not a useful implicit object while building a JSP application.
8.    pageContext: It is used for accessing page, request, application and session attributes.
Read full article here » pageContext implicit object with examples.
9.    Config: This is a Servlet configuration object and mainly used for accessing getting configuration information such as servlet context, servlet name, configuration parameters etc.
Read full article here » Config implicit object with examples.

JavaServer Pages

JavaServer Pages:EME
Desarrollador(es)
Información general
2.3
?
?
JavaServer Pages (JSP) es una tecnología que ayuda a los desarrolladores de software a crear páginas web dinámicas basadas en HTML y XML, entre otros tipos de documentos. JSP es similar a PHP, pero usa el lenguaje de programación Java.
Para desplegar y correr JavaServer Pages, se requiere un servidor web compatible con contenedores servlet como Apache Tomcat o Jetty.
TagLibs -> JSP -> Servidor Aplicaciones (Servlets) -> Cliente (Navegador)
El rendimiento de una página JSP es el mismo que tendría el servlet equivalente, ya que el código es compilado como cualquier otra clase Java. A su vez, la máquina virtual compilará dinámicamente a código de máquina las partes de la aplicación que lo requieran. Esto hace que JSP tenga un buen desempeño y sea más eficiente que otras tecnologías web que ejecutan el código de una manera puramente interpretada.
La principal ventaja de JSP frente a otros lenguajes es que el lenguaje Java es un lenguaje de propósito general que excede el mundo web y que es apto para crear clases que manejen lógica de negocio y acceso a datos de una manera prolija. Esto permite separar en niveles las aplicaciones web, dejando la parte encargada de generar el documento HTML en el archivo JSP.
Otra ventaja es que JSP hereda la portabilidad de Java, y es posible ejecutar las aplicaciones en múltiples plataformas sin cambios. Es común incluso que los desarrolladores trabajen en una plataforma y que la aplicación termine siendo ejecutada en otra.
Los servlets y Java Server Pages (JSPs) son dos métodos de creación de páginas web dinámicas en servidor usando el lenguaje Java. En ese sentido son similares a otros métodos o lenguajes tales como el PHP, ASP o los CGIs, programas que generan páginas web en el servidor. Sin embargo, se diferencian de ellos en otras cosas.
Para empezar, los JSPs y servlets se ejecutan en una máquina virtual Java, lo cual permite que, en principio, se puedan usar en cualquier tipo de ordenador, siempre que exista una máquina virtual Java para él. Cada servlet (o JSP, a partir de ahora lo usaremos de forma indistinta) se ejecuta en su propio hilo, es decir, en su propio contexto; pero no se comienza a ejecutar cada vez que recibe una petición, sino que persiste de una petición a la siguiente, de forma que no se pierde tiempo en invocarlo (cargar programa + intérprete). Su persistencia le permite también hacer una serie de cosas de forma más eficiente: conexión a bases de datos y manejo de sesiones, por ejemplo.
Las JSPs son en realidad una forma alternativa de crear servlets ya que el código JSP se traduce a código de servlet Java la primera vez que se le invoca y en adelante es el código del nuevo servlet el que se ejecuta produciendo como salida el código HTML que compone la página web de respuesta.

Índice

  [ocultar] 
·         1Descripción
·         2Ejemplo de documento JSP
·         3Sintaxis
o    3.2Directivas
o    3.4Scriptlets
o    3.6Etiquetas
·         4Véase también
·         5Enlaces externos

Descripción[editar]

JSP puede ser visto como una abstracción de alto nivel de los servlets Java. Las JavaServer Pages son traducidas a servlets en tiempo real; cada servlet es guardado en caché y reusado hasta que la JSP original es modificada.

Ejemplo de documento JSP[editar]

Ejemplo de código de una página JSP:
<%@ page errorPage="myerror.jsp" %>
<%@ page import="com.foo.bar" %>
<html>
<head>
<%! int serverInstanceVariable = 1;%>
<%! int localStackBasedVariable = 1;%>
Ejemplo de una compilación o "salida" JSP:
package jsp_servlet;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import com.foo.bar; //importado como resultado de <%@ page import="com.foo.bar" %>
import …
class _myservlet implements javax.servlet.Servlet, javax.servlet.jsp.HttpJspPage {
        //insertado como
        //resultado de <%! int serverInstanceVariable = 1;%>
        int serverInstanceVariable = 1; 
        …
        public void _jspService( javax.servlet.http.HttpServletRequest request,
               javax.servlet.http.HttpServletResponse response )
               throws javax.servlet.ServletException,
               java.io.IOException
        {
               javax.servlet.ServletConfig config = ...;//obtener la configuración del servlet
               Object page = this;
               PageContext pageContext = …;//obtener el contexto de la página para esta petición 
               javax.servlet.jsp.JspWriter out = pageContext.getOut();
               HttpSession session = request.getSession( true );
               …
Para ejecutar las páginas JSP, se necesita un servidor Web con un contenedor Web que cumpla con las especificaciones de JSP y de Servlet. Tomcat 5 es una completa implementación de referencia para las especificaciones Java Servlet 2.2 y JSP 1.1.

Sintaxis[editar]

Variables implícitas[editar]

Las páginas JSP incluyen ciertas variables privilegiadas sin necesidad de declararlas ni configurarlas:
Variable
Clase
pageContext
javax.servlet.jsp.PageContext
request
javax.servlet.http.HttpServletRequest
response
javax.servlet.http.HttpServletResponse
session
javax.servlet.http.HttpSession
config
javax.servlet.ServletConfig
application
javax.servlet.ServletContext
out
javax.servlet.jsp.JspWriter
page
java.lang.Object
exception
java.lang.Exception

Directivas[editar]

Son etiquetas a partir de las cuales se genera información que puede ser utilizada por el motor de JSP. No producen una salida visible al usuario sino que configura cómo se ejecutará la página JSP.
Su sintaxis es:
 <%@ directiva atributo="valor" %>
 
Las directivas disponibles son:
·         include: Incluye el contenido de un fichero en la página mediante el atributo file.
<%@ include file="cabecera.html" %>
·        taglib: Importa bibliotecas de etiquetas (Tag Libraries)
<%@ taglib uri="/tags/struts-html" prefix="html" %>
·         page: Especifica atributos relacionados con la página a procesar. Los atributos son:
Atributo
Sintaxis
Utilización
import
<%@ page import="class; class" %>
Importa clases y paquetes Java para ser utilizadas dentro del fichero JSP.
session
<%@ page session="false" %>
Especifica si utiliza los datos contenidos en sesión; por defecto "true".
contentType
<%@ page contentType="class; class" %>
Especifica el tipo MIME del objeto "response"; por defecto "text/html; charset=ISO-8859-1".
buffer
<%@ page buffer="12KB" %>
Buffer utilizado por el objeto writer "out"; puede tomar el valor de "none"; por defecto "8KB".
errorPage
<%@ page errorPage="/path_to_error_page" %>
Especifica la ruta de la página de error que será invocada en caso de producirse una excepción durante la ejecución de este fichero JSP.
isErrorPage
<%@ page isErrorPage="true" %>
Determina si este fichero JSP es una página que maneja excepciones. Únicamente a este tipo de páginas pueden acceder a la variable implícita "exception", que contiene la excepción que provocó la llamada a la página de error.

Declaraciones[editar]

Nos permiten declarar variables, funciones y datos estáticos.
 <%! int maxAlumnosClase = 30; %>
 

Scriptlets[editar]

Los scriptlets son partes de código Java incrustadas entre los elementos estáticos de la página....
 <% ... código Java ... %>
 

Expresiones[editar]

Las expresiones se evalúan dentro de la servlet. No deben acabar en ";".
 <%= maxAlumnosClase + 1%>
 
El siguiente ejemplo pondría como título de la página el atributo "titulo" contenido en el objeto request:
 <%
   String titulo = "";
   if (request.getAttribute("titulo") != null) {
     titulo = (String) request.getAttribute ("titulo");
   }
 %>
 ...
 <title><%=titulo%></title>
 ....
 

Etiquetas[editar]

Etiquetas JSP para simplificar el código y dar mayor funcionalidad.
Desarrollar sitios web utilizando etiquetas presenta ciertas ventajas como:
·         facilitar el aprendizaje.
·         facilitar el mantenimiento.
·         fomentar la modularidad y la reutilización.
·         simplificar el código y reducir el número de líneas necesarias.
Su sintaxis sería:
 <%@ taglib uri="/taglib/lycka" prefix="lycka" %>
 ...
 <lycka:hola/>
 ...
 
A la hora de generar el código Java de la Servlet, esta etiqueta hola será interpretada por el Servidor de Aplicaciones como perteneciente a la biblioteca de etiquetas (Tag Library) lycka. Esta biblioteca estará identificada en el fichero descriptor de nuestra aplicación (web.xml) con el nombre de recurso (URI) /taglib/lycka.
 <taglib-uri>/taglib/lycka</taglib-uri>
 <taglib-location>/WEB-INF/tags/lycka.tld</taglib-location>
 
Una implementación de este fichero descriptor, /WEB-INF/tags/lycka.tld podría ser:
 <?xml version="1.0" encoding="ISO-8859-1" ?>
 <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" 
    "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
 
 <taglib>
   <tlibversion>1.0</tlibversion>
   <jspversion>1.1</jspversion>
   <shortname>simp</shortname>
   <uri>http://www.hachisvertas.net/jcs/taglibs/lycka</uri>
   <info>A simple sample tag library</info>
 
   <tag>
     <name>hola</name>
     <tagclass>org.lcyka.taglibs.miEtiqueta</tagclass>
     <bodycontent>empty</bodycontent>
     <info>Alaba la belleza de mi gata.</info>
   </tag>
 </taglib>
 
Y por fin, el servidor de aplicaciones sustituirá la etiqueta por su código Java asociado, org.lcyka.taglibs.miEtiqueta:
 package org.lcyka.taglibs;
 import ...;
 public class miEtiqueta extends TagSupport {
   public int doStartTag {
     try {
       pageContext.getOut().print("Mi gata es preciosa");
     } catch (IOException ioe) {
     }
     return SKIP_BODY;
   }
 
Y finalmente el navegador mostraría:
 Mi gata es preciosa

Etiquetas JSP[editar]

Son las etiquetas pertenecientes a la especificación JSP. Proporcionan una funcionalidad básica.
Un primer grupo de etiquetas proporciona funcionalidad a nivel de la página de una manera muy simple:
·         <jsp:forward>, redirige la request a otra URL
·         <jsp:include>, incluye el texto de un fichero dentro de la página
·         <jsp:plugin>, descarga un plugin de Java (una applet o un Bean).
Un segundo grupo permite manipular componentes JavaBean sin conocimientos de Java.
·         <jsp:useBean>, permite manipular un Bean (si no existe, se creará el Bean), especificando su ámbito (scope), la clase y el tipo.
·         <jsp:getProperty>, obtiene la propiedad especificada de un bean previamente declarado y la escribe en el objeto response.
·         <jsp:setProperty>, establece el valor de una propiedad de un bean previamente declarado.

Etiquetas JSTL[editar]

Son proporcionadas por Sun dentro de la distribución de JSTL.
·         core, iteraciones, condicionales, manipulación de URL y otras funciones generales.
·         xml, para la manipulación de XML y para XML-Transformation.
·         sql, para gestionar conexiones a bases de datos.
·         i18n, para la internacionalización y formateo de las cadenas de caracteres como cifras.

Etiquetas Struts TagLib[editar]

Distribuidas por Apache para funcionar junto con el Framework de Struts.
·         PHP
·         Bean
·         HTML
·         Logic
·         Nested
·         vjgp

Etiquetas personalizadas[editar]

Anteriormente hemos visto un ejemplo para crear una etiqueta personalizada almacenada en nuestra propia biblioteca de etiquetas.
Para desarrollar etiquetas personalizadas, utilizaremos la API de las bibliotecas de etiquetas (Tag Libraries).
La API de las Servlet de Java es:
 javax.servlet.*
 
La API de JSP extiende de esta API,
 javax.servlet.jsp.*
 
Finalmente, la API de las bibliotecas de etiquetas (Tag Libraries) extiende de esta última,
 javax.servlet.jsp.tagext.*
 
Lo más relevante de esta API son:
·         Las interfaces
·         Tag, que todas las etiquetas deben implementar.
·         BodyTag, extiende a la anterior y define métodos adicionales para inspeccionar el cuerpo de una etiqueta.
·         Las clases
·         BodyContent, un manejador (handler) para leer y escribir en el cuerpo de una etiqueta.
·         BodyTagSupport, que implementa la interfaz BodyTag.
·         TagAttributeInfo, para obtener la información de los atributos de la etiqueta declarados en el TLD.
·         TagData, que contiene los valores de los atributos.
·         TagExtraInfo, para especificar información extra de una etiqueta, como las variables que introduce en el código o los atributos que serán validados.
·         TagInfo, basado en la información de la TLD.
·         TagLibraryInfo, representa la información de una TLD.
·         TagSupport, implementa la interfaz Tag.
·         VariableInfo, contiene información como el tipo y ámbito de las variables creadas o modificadas por la etiqueta.
Otro ejemplo de etiqueta podría ser el siguiente código Java:
 package org.lycka.taglibs;
 import ...;
 public class LowerCaseTag extends BodyTagSupport {
   public int doAfterBody() throws JspException {
     try {
       BodyContent body = getBodyContent();
       JspWriter writer = body.getEnclosingWriter();
       String bodyString = body.getString();
       if ( bodyString != null ) {
         writer.print( bodyString.toLowerCase());
       }
     } catch(IOException ioe) {
       throw new JspException("Error: IOException while writing to the user");
     }
     return SKIP_BODY;
   }
 }
 
Al encontrar el inicio de la etiqueta, el runtime primero se invocará el método doStart() una vez instanciada la clase. Puede devolver uno de los siguientes valores:
·         SKIP_BODY, no procesa el contenido del cuerpo de la etiqueta.
·         EVAL_BODY_INCLUDE , evalúa el cuerpo de la etiqueta.
·         EVAL_BODY_TAG , evalúa el cuerpo de la etiqueta y lanza el resultado a otro stream almacenado en una propiedad de la etiqueta.
El método doAfterBody() después de procesar el cuerpo de la etiqueta.
Finalmente se invocará el método doEndTag(). Puede devolver:
·         EVAL_PAGE, para seguir procesando la página JSP
·         SKIP_PAGE, para dejar de procesar la página JSP, para por ejemplo redirigir la página
Declarado en el descriptor de la biblioteca como
 <tag>
   <name>lowercase</name>
   <tagclass>org.lycka.taglibs.LowerCaseTag</tagclass>
   <bodycontent>JSP</bodycontent>
   <info>Put body in lowercase.</info>
 </tag>
 
Utilizado en la página JSP
 <%@ taglib uri="/taglib/lycka" prefix="lycka" %>
 ...
 <lycka:lowercase>Esto es un EJEMPLO</lycka:lowercase>
 
Y su salida sería
 esto es un ejemplo

Véase también[editar]

·         Tomcat
·         Sun Microsystems
·         Servidor HTTP Apache

Enlaces externos[editar]

·         Sun Microsystem
·         Página oficial de JSP
·         Apache
·         Tomcat
·         Estándares programación JSP

The key to understanding the low-level functionality of JSP is to understand the simple life cycle they follow.
A JSP life cycle can be defined as the entire process from its creation till the destruction which is similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet.
The following are the paths followed by a JSP
·        Compilation
·        Initialization
·        Execution
·        Cleanup
The four major phases of JSP life cycle are very similar to Servlet Life Cycle and they are as follows:

JSP Compilation:

When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.
The compilation process involves three steps:
·        Parsing the JSP.
·        Turning the JSP into a servlet.
·        Compiling the servlet.

JSP Initialization:

When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to perform JSP-specific initialization, override the jspInit() method:
public void jspInit(){
  // Initialization code...
}
Typically initialization is performed only once and as with the servlet init method, you generally initialize database connections, open files, and create lookup tables in the jspInit method.

JSP - Directives


Advertisements


JSP directives provide directions and instructions to the container, telling it how to handle certain aspects of JSP processing.
A JSP directive affects the overall structure of the servlet class. It usually has the following form:
<%@ directive attribute="value" %>
Directives can have a number of attributes which you can list down as key-value pairs and separated by commas.
The blanks between the @ symbol and the directive name, and between the last attribute and the closing %>, are optional.
There are three types of directive tag:
Directive
Description
<%@ page ... %>
Defines page-dependent attributes, such as scripting language, error page, and buffering requirements.
<%@ include ... %>
Includes a file during the translation phase.
<%@ taglib ... %>
Declares a tag library, containing custom actions, used in the page

The page Directive:

The page directive is used to provide instructions to the container that pertain to the current JSP page. You may code page directives anywhere in your JSP page. By convention, page directives are coded at the top of the JSP page.
Following is the basic syntax of page directive:
<%@ page attribute="value" %>
You can write XML equivalent of the above syntax as follows:
<jsp:directive.page attribute="value" />

Attributes:

Following is the list of attributes associated with page directive:
Attribute
Purpose
buffer
Specifies a buffering model for the output stream.
autoFlush
Controls the behavior of the servlet output buffer.
contentType
Defines the character encoding scheme.
errorPage
Defines the URL of another JSP that reports on Java unchecked runtime exceptions.
isErrorPage
Indicates if this JSP page is a URL specified by another JSP page's errorPage attribute.
extends
Specifies a superclass that the generated servlet must extend
import
Specifies a list of packages or classes for use in the JSP as the Java import statement does for Java classes.
info
Defines a string that can be accessed with the servlet's getServletInfo() method.
isThreadSafe
Defines the threading model for the generated servlet.
language
Defines the programming language used in the JSP page.
session
Specifies whether or not the JSP page participates in HTTP sessions
isELIgnored
Specifies whether or not EL expression within the JSP page will be ignored.
isScriptingEnabled
Determines if scripting elements are allowed for use.
Check more detail related to all the above attributes at Page Directive.

The include Directive:

The include directive is used to includes a file during the translation phase. This directive tells the container to merge the content of other external files with the current JSP during the translation phase. You may code include directives anywhere in your JSP page.
The general usage form of this directive is as follows:
<%@ include file="relative url" >
The filename in the include directive is actually a relative URL. If you just specify a filename with no associated path, the JSP compiler assumes that the file is in the same directory as your JSP.
You can write XML equivalent of the above syntax as follows:
<jsp:directive.include file="relative url" />
Check more detail related to include directive at Include Directive.

The taglib Directive:

The JavaServer Pages API allows you to define custom JSP tags that look like HTML or XML tags and a tag library is a set of user-defined tags that implement custom behavior.
The taglib directive declares that your JSP page uses a set of custom tags, identifies the location of the library, and provides a means for identifying the custom tags in your JSP page.
The taglib directive follows the following syntax:
<%@ taglib uri="uri" prefix="prefixOfTag" >
Where the uri attribute value resolves to a location the container understands and the prefix attribute informs a container what bits of markup are custom actions.
You can write XML equivalent of the above syntax as follows:
<jsp:directive.taglib uri="uri" prefix="prefixOfTag" />
Check more detail related to taglib directive at Taglib Directive.
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin.
There is only one syntax for the Action element, as it conforms to the XML standard:
<jsp:action_name attribute="value" />
Action elements are basically predefined functions and there are following JSP actions available:
Syntax
Purpose
jsp:include
Includes a file at the time the page is requested
jsp:useBean
Finds or instantiates a JavaBean
jsp:setProperty
Sets the property of a JavaBean
jsp:getProperty
Inserts the property of a JavaBean into the output
jsp:forward
Forwards the requester to a new page
jsp:plugin
Generates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin
jsp:element
Defines XML elements dynamically.
jsp:attribute
Defines dynamically defined XML element's attribute.
jsp:body
Defines dynamically defined XML element's body.
jsp:text
Use to write template text in JSP pages and documents.

Common Attributes:

There are two attributes that are common to all Action elements: the id attribute and the scope attribute.
·        Id attribute: The id attribute uniquely identifies the Action element, and allows the action to be referenced inside the JSP page. If the Action creates an instance of an object the id value can be used to reference it through the implicit object PageContext
·        Scope attribute: This attribute identifies the lifecycle of the Action element. The id attribute and the scope attribute are directly related, as the scope attribute determines the lifespan of the object associated with the id. The scope attribute has four possible values: (a) page, (b)request, (c)session, and (d) application.

The <jsp:include> Action

This action lets you insert files into the page being generated. The syntax looks like this:
<jsp:include page="relative URL" flush="true" />
Unlike the include directive, which inserts the file at the time the JSP page is translated into a servlet, this action inserts the file at the time the page is requested.
Following is the list of attributes associated with include action:
Attribute
Description
page
The relative URL of the page to be included.
flush
The boolean attribute determines whether the included resource has its buffer flushed before it is included.

Example:

Let us define following two files (a)date.jsp and (b) main.jsp as follows:
Following is the content of date.jsp file:
<p>
   Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
Here is the content of main.jsp file:
<html>
<head>
<title>The include Action Example</title>
</head>
<body>
<center>
<h2>The include action Example</h2>
<jsp:include page="date.jsp" flush="true" />
</center>
</body>
</html>
Now let us keep all these files in root directory and try to access main.jsp. This would display result something like this:
 

The include action Example

 
   Today's date: 12-Sep-2010 14:54:22
 

The <jsp:useBean> Action

The useBean action is quite versatile. It first searches for an existing object utilizing the id and scope variables. If an object is not found, it then tries to create the specified object.
The simplest way to load a bean is as follows:
<jsp:useBean id="name" class="package.class" />
Once a bean class is loaded, you can use jsp:setProperty and jsp:getProperty actions to modify and retrieve bean properties.
Following is the list of attributes associated with useBean action:
Attribute
Description
class
Designates the full package name of the bean.
type
Specifies the type of the variable that will refer to the object.
beanName
Gives the name of the bean as specified by the instantiate () method of the java.beans.Beans class.
Let us discuss about jsp:setProperty and jsp:getProperty actions before giving a valid example related to these actions.

JSP Implicit Objects

  1. JSP Implicit Objects
  2. out implicit object
  3. Example of out implicit object
There are 9 jsp implicit objects. These objects are created by the web container that are available to all the jsp pages.
The available implicit objects are out, request, config, session, application etc.
A list of the 9 implicit objects is given below:
Object
Type
out
JspWriter
request
HttpServletRequest
response
HttpServletResponse
config
ServletConfig
application
ServletContext
session
HttpSession
pageContext
PageContext
page
Object
exception
Throwable

1) JSP out implicit object

For writing any data to the buffer, JSP provides an implicit object named out. It is the object of JspWriter. In case of servlet you need to write:
1.    PrintWriter out=response.getWriter();  
But in JSP, you don't need to write this code.

Example of out implicit object

In this example we are simply displaying date and time.

index.jsp

1.    <html>  
2.    <body>  
3.    <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>  
4.    </body>  
5.    </html>  



Are methods legal inside JSP scriptlet?


You need to use declaration syntax (<%! ... %>):
<%!
   public String doSomething(String param) {
      //
   }
%>
<%
   String test = doSomething("test");
%>


SQL COUNT() Function


The COUNT() function returns the number of rows that matches a specified criteria.

SQL COUNT(column_name) Syntax

The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column:
SELECT COUNT(column_name) FROM table_name;

SQL COUNT(*) Syntax

The COUNT(*) function returns the number of records in a table:
SELECT COUNT(*) FROM table_name;

SQL COUNT(DISTINCT column_name) Syntax

The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified column:
SELECT COUNT(DISTINCT column_name) FROM table_name;
Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with Microsoft Access.

Demo Database

In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Orders" table:
OrderID
CustomerID
EmployeeID
OrderDate
ShipperID
10265
7
2
1996-07-25
1
10266
87
3
1996-07-26
3
10267
25
4
1996-07-29
1

SQL COUNT(column_name) Example

The following SQL statement counts the number of orders from "CustomerID"=7 from the "Orders" table:

Example

SELECT COUNT(CustomerID) AS OrdersFromCustomerID7 FROM Orders
WHERE CustomerID=7;

SQL COUNT(*) Example

The following SQL statement counts the total number of orders in the "Orders" table:

Example

SELECT COUNT(*) AS NumberOfOrders FROM Orders;

SQL COUNT(DISTINCT column_name) Example

The following SQL statement counts the number of unique customers in the "Orders" table:

Example

SELECT COUNT(DISTINCT CustomerID) AS NumberOfCustomers FROM Orders;

Examples

The following example that uses a simple HAVING clause retrieves the total for each SalesOrderID from the SalesOrderDetail table that exceeds $100000.00.
USE AdventureWorks2012 ;  
GO  
SELECT SalesOrderID, SUM(LineTotal) AS SubTotal  
FROM Sales.SalesOrderDetail  
GROUP BY SalesOrderID  
HAVING SUM(LineTotal) > 100000.00  
ORDER BY SalesOrderID ;  


HAVING clause

A HAVING clause restricts the results of a GROUP BY in a SelectExpression. The HAVING clause is applied to each group of the grouped table, much as a WHERE clause is applied to a select list. If there is no GROUP BY clause, the HAVING clause is applied to the entire result as a single group. The SELECT clause cannot refer directly to any column that does not have a GROUP BY clause. It can, however, refer to constants, aggregates, and special registers.

Syntax

HAVING searchCondition
The searchCondition, which is a specialized booleanExpression, can contain only grouping columns (see GROUP BY clause), columns that are part of aggregate expressions, and columns that are part of a subquery. For example, the following query is illegal, because the column SALARY is not a grouping column, it does not appear within an aggregate, and it is not within a subquery:
-- SELECT COUNT(*)
-- FROM SAMP.STAFF
-- GROUP BY ID
-- HAVING SALARY > 15000
Aggregates in the HAVING clause do not need to appear in the SELECT list. If the HAVING clause contains a subquery, the subquery can refer to the outer query block if and only if it refers to a grouping column.

Example

-- Find the total number of economy seats taken on a flight,
-- grouped by airline,
-- only when the group has at least 2 records. 
SELECT SUM(ECONOMY_SEATS_TAKEN), AIRLINE_FULL
FROM FLIGHTAVAILABILITY, AIRLINES
WHERE SUBSTR(FLIGHTAVAILABILITY.FLIGHT_ID, 1, 2) = AIRLINE
GROUP BY AIRLINE_FULL
HAVING COUNT(*) > 1
Parent topic: SQL clauses

SQL - Having Clause


Advertisements


The HAVING clause enables you to specify conditions that filter which group results appear in the final results.
The WHERE clause places conditions on the selected columns, whereas the HAVING clause places conditions on groups created by the GROUP BY clause.

Syntax:

The following is the position of the HAVING clause in a query:
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY
The HAVING clause must follow the GROUP BY clause in a query and must also precede the ORDER BY clause if used. The following is the syntax of the SELECT statement, including the HAVING clause:
SELECT column1, column2
FROM table1, table2
WHERE [ conditions ]
GROUP BY column1, column2
HAVING [ conditions ]
ORDER BY column1, column2

Example:

Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
+----+----------+-----+-----------+----------+
Following is the example, which would display record for which similar age count would be more than or equal to 2:
SQL > SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMERS
GROUP BY age
HAVING COUNT(age) >= 2;
This would produce the following result:
+----+--------+-----+---------+---------+
| ID | NAME   | AGE | ADDRESS | SALARY  |
+----+--------+-----+---------+---------+
|  2 | Khilan |  25 | Delhi   | 1500.00 |
+----+--------+-----+---------+---------+

SQL GROUP BY Examples



Problem: List the number of customers in each country. Only include countries with more than 10 customers. 


1.  SELECT COUNT(Id), Country 
2.    FROM Customer
3.   GROUP BY Country
4.  HAVING COUNT(Id) > 10


Results: 3 records 

Count
Country
11
France
11
Germany
13
USA


CUSTOMER
Id
FirstName
LastName
City
Country
Phone

Problem: List the number of customers in each country, except the USA, sorted high to low. 
Only include countries with 9 or more customers. 


1.  SELECT COUNT(Id), Country 
2.    FROM Customer
3.   WHERE Country <> 'USA'
4.   GROUP BY Country
5.  HAVING COUNT(Id) >= 9
6.   ORDER BY COUNT(Id) DESC


Results: 3 records 

Count
Country
11
France
11
Germany
9
Brazil


ORDER
Id
OrderDate
OrderNumber
CustomerId
TotalAmount

Problem: List all customer with average orders between $1000 and $1200.



1.  SELECT AVG(TotalAmount), FirstName, LastName
2.    FROM [Order] O JOIN Customer C ON O.CustomerId = C.Id
3.   GROUP BY FirstName, LastName
4.  HAVING AVG(TotalAmount) BETWEEN 1000 AND 1200

SQL HAVING Clause


The HAVING Clause

The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.

SQL HAVING Syntax

SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value;

Demo Database

In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Orders" table:
OrderID
CustomerID
EmployeeID
OrderDate
ShipperID
10248
90
5
1996-07-04
3
10249
81
6
1996-07-05
1
10250
34
4
1996-07-08
2
And a selection from the "Employees" table:
EmployeeID
LastName
FirstName
BirthDate
Photo
Notes
1
Davolio
Nancy
1968-12-08
EmpID1.pic
Education includes a BA....
2
Fuller
Andrew
1952-02-19
EmpID2.pic
Andrew received his BTS....
3
Leverling
Janet
1963-08-30
EmpID3.pic
Janet has a BS degree....

SQL HAVING Example

Now we want to find  if any of the employees has registered more than 10 orders.
We use the following SQL statement:

Example

SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM (Orders
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 10;

The GROUP BY Statement

The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.

SQL GROUP BY Syntax

SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;

Demo Database

In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Orders" table:
OrderID
CustomerID
EmployeeID
OrderDate
ShipperID
10248
90
5
1996-07-04
3
10249
81
6
1996-07-05
1
10250
34
4
1996-07-08
2
And a selection from the "Shippers" table:
ShipperID
ShipperName
1
Speedy Express
2
United Package
3
Federal Shipping
And a selection from the "Employees" table:
EmployeeID
LastName
FirstName
BirthDate
Photo
Notes
1
Davolio
Nancy
1968-12-08
EmpID1.pic
Education includes a BA....
2
Fuller
Andrew
1952-02-19
EmpID2.pic
Andrew received his BTS....
3
Leverling
Janet
1963-08-30
EmpID3.pic
Janet has a BS degree....

SQL GROUP BY Example

Now we want to find the number of orders sent by each shipper.
The following SQL statement counts as orders grouped by shippers:

Example

SELECT Shippers.ShipperName,COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers
ON Orders.ShipperID=Shippers.ShipperID
GROUP BY ShipperName;

GROUP BY More Than One Column

We can also use the GROUP BY statement on more than one column, like this:

Example

SELECT Shippers.ShipperName, Employees.LastName,
COUNT(Orders.OrderID) AS NumberOfOrders
FROM ((Orders
INNER JOIN Shippers
ON Orders.ShipperID=Shippers.ShipperID)
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID)
GROUP BY ShipperName,LastName;

SQL - Group By


Advertisements


The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups.
The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause.

Syntax:

The basic syntax of GROUP BY clause is given below. The GROUP BY clause must follow the conditions in the WHERE clause and must precede the ORDER BY clause if one is used.
SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2

Example:

Consider the CUSTOMERS table is having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
+----+----------+-----+-----------+----------+
If you want to know the total amount of salary on each customer, then GROUP BY query would be as follows:
SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS
     GROUP BY NAME;
This would produce the following result:
+----------+-------------+
| NAME     | SUM(SALARY) |
+----------+-------------+
| Chaitali |     6500.00 |
| Hardik   |     8500.00 |
| kaushik  |     2000.00 |
| Khilan   |     1500.00 |
| Komal    |     4500.00 |
| Muffy    |    10000.00 |
| Ramesh   |     2000.00 |
+----------+-------------+
Now, let us have following table where CUSTOMERS table has the following records with duplicate names:
+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  2 | Ramesh   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  4 | kaushik  |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
+----+----------+-----+-----------+----------+
Now again, if you want to know the total amount of salary on each customer, then GROUP BY query would be as follows:
SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS
     GROUP BY NAME;
This would produce the following result:
+---------+-------------+
| NAME    | SUM(SALARY) |
+---------+-------------+
| Hardik  |     8500.00 |
| kaushik |     8500.00 |
| Komal   |     4500.00 |
| Muffy   |    10000.00 |
| Ramesh  |     3500.00 |
+---------+-------------+


Blogger Widgets