소스 파일 최초 업로드

This commit is contained in:
ByeonJungHun
2024-04-05 10:31:45 +09:00
commit 718e6822af
682 changed files with 90848 additions and 0 deletions

View File

@@ -0,0 +1,140 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ResourceBundle;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import util.CookieFilter;
import util.HTMLFilter;
/**
* Example servlet showing request headers
*
* @author James Duncan Davidson <duncan@eng.sun.com>
*/
public class CookieExample extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
ResourceBundle rb = ResourceBundle.getBundle("LocalStrings",request.getLocale());
String cookieName = request.getParameter("cookiename");
String cookieValue = request.getParameter("cookievalue");
Cookie aCookie = null;
if (cookieName != null && cookieValue != null) {
aCookie = new Cookie(cookieName, cookieValue);
aCookie.setPath(request.getContextPath() + "/");
response.addCookie(aCookie);
}
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html><html>");
out.println("<head>");
out.println("<meta charset=\"UTF-8\" />");
String title = rb.getString("cookies.title");
out.println("<title>" + title + "</title>");
out.println("</head>");
out.println("<body bgcolor=\"white\">");
// relative links
// XXX
// making these absolute till we work out the
// addition of a PathInfo issue
out.println("<a href=\"../cookies.html\">");
out.println("<img src=\"../images/code.gif\" height=24 " +
"width=24 align=right border=0 alt=\"view code\"></a>");
out.println("<a href=\"../index.html\">");
out.println("<img src=\"../images/return.gif\" height=24 " +
"width=24 align=right border=0 alt=\"return\"></a>");
out.println("<h3>" + title + "</h3>");
Cookie[] cookies = request.getCookies();
if ((cookies != null) && (cookies.length > 0)) {
HttpSession session = request.getSession(false);
String sessionId = null;
if (session != null) {
sessionId = session.getId();
}
out.println(rb.getString("cookies.cookies") + "<br>");
for (Cookie cookie : cookies) {
String cName = cookie.getName();
String cValue = cookie.getValue();
out.print("Cookie Name: " + HTMLFilter.filter(cName) + "<br>");
out.println(" Cookie Value: "
+ HTMLFilter.filter(CookieFilter.filter(cName, cValue, sessionId))
+ "<br><br>");
}
} else {
out.println(rb.getString("cookies.no-cookies"));
}
if (aCookie != null) {
out.println("<P>");
out.println(rb.getString("cookies.set") + "<br>");
out.print(rb.getString("cookies.name") + " "
+ HTMLFilter.filter(cookieName) + "<br>");
out.print(rb.getString("cookies.value") + " "
+ HTMLFilter.filter(cookieValue));
}
out.println("<P>");
out.println(rb.getString("cookies.make-cookie") + "<br>");
out.print("<form action=\"");
out.println("CookieExample\" method=POST>");
out.print(rb.getString("cookies.name") + " ");
out.println("<input type=text length=20 name=cookiename><br>");
out.print(rb.getString("cookies.value") + " ");
out.println("<input type=text length=20 name=cookievalue><br>");
out.println("<input type=submit></form>");
out.println("</body>");
out.println("</html>");
}
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}

View File

@@ -0,0 +1,79 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ResourceBundle;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* The simplest possible servlet.
*
* @author James Duncan Davidson
*/
public class HelloWorldExample extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
ResourceBundle rb =
ResourceBundle.getBundle("LocalStrings",request.getLocale());
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html><html>");
out.println("<head>");
out.println("<meta charset=\"UTF-8\" />");
String title = rb.getString("helloworld.title");
out.println("<title>" + title + "</title>");
out.println("</head>");
out.println("<body bgcolor=\"white\">");
// note that all links are created to be relative. this
// ensures that we can move the web application that this
// servlet belongs to a different place in the url
// tree and not have any harmful side effects.
// XXX
// making these absolute till we work out the
// addition of a PathInfo issue
out.println("<a href=\"../helloworld.html\">");
out.println("<img src=\"../images/code.gif\" height=24 " +
"width=24 align=right border=0 alt=\"view code\"></a>");
out.println("<a href=\"../index.html\">");
out.println("<img src=\"../images/return.gif\" height=24 " +
"width=24 align=right border=0 alt=\"return\"></a>");
out.println("<h1>" + title + "</h1>");
out.println("</body>");
out.println("</html>");
}
}

View File

@@ -0,0 +1,48 @@
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cookies.cookies=Your browser is sending the following cookies:
cookies.make-cookie=Create a cookie to send to your browser
cookies.name=Name:
cookies.no-cookies=Your browser isn't sending any cookies
cookies.set=You just sent the following cookie to your browser:
cookies.title=Cookies Example
cookies.value=Value:
helloworld.title=Hello World!
requestheader.title=Request Header Example
requestinfo.label.method=Method:
requestinfo.label.pathinfo=Path Info:
requestinfo.label.protocol=Protocol:
requestinfo.label.remoteaddr=Remote Address:
requestinfo.label.requesturi=Request URI:
requestinfo.title=Request Information Example
requestparams.firstname=First Name:
requestparams.lastname=Last Name:
requestparams.no-params=No Parameters, Please enter some
requestparams.params-in-req=Parameters in this request:
requestparams.title=Request Parameters Example
sessions.adddata=Add data to your session
sessions.created=Created:
sessions.data=The following data is in your session:
sessions.dataname=Name of Session Attribute:
sessions.datavalue=Value of Session Attribute:
sessions.id=Session ID:
sessions.lastaccessed=Last Accessed:
sessions.title=Sessions Example

View File

@@ -0,0 +1,22 @@
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cookies.make-cookie=Vytvo\u0159te cookie pro zasl\u00e1n\u00ed do Va\u0161eho prohl\u00ed\u017ee\u010de
requestheader.title=P\u0159\u00edklad hlavi\u010dky dotazu
requestparams.firstname=K\u0159estn\u00ed jm\u00e9no:
requestparams.no-params=\u017d\u00e1dn\u00fd parametr, vlo\u017ete n\u011bjak\u00fd pros\u00edm
requestparams.title=P\u0159\u00edklad parametr\u016f dotazu

View File

@@ -0,0 +1,28 @@
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cookies.make-cookie=Erzeuge ein Cookie um es an deinen Browser zu senden
cookies.name=Name:
requestheader.title=Request-Header Beispiel
requestinfo.label.protocol=Protokoll:
requestinfo.label.requesturi=Anfrage-URI:
requestparams.firstname=Vorname:
requestparams.no-params=Keine Parameter, bitte geben Sie welche ein
requestparams.title=Beispiel f\u00fcr Anfrageparameter
sessions.title=Sessions-Beispiel

View File

@@ -0,0 +1,48 @@
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cookies.cookies=Tu navegador est\u00e1 enviando los siguientes cookies:
cookies.make-cookie=Crea un cookie para enviarlo a tu navegador
cookies.name=Nombre:
cookies.no-cookies=Tu navegador no est\u00e1 enviando cookies
cookies.set=Acabas de enviar a tu navegador estos cookies:
cookies.title=Ejemplo de Cookies
cookies.value=Valor:
helloworld.title=Hola Mundo!
requestheader.title=Ejemplo de Cabecera de Requerimiento:
requestinfo.label.method=M\u00e9todo:
requestinfo.label.pathinfo=Info de Ruta:
requestinfo.label.protocol=Protocolo:
requestinfo.label.remoteaddr=Direccion Remota:
requestinfo.label.requesturi=URI de Requerimiento:
requestinfo.title=Ejemplo de Informacion de Requerimiento:
requestparams.firstname=Nombre:
requestparams.lastname=Apellidos:
requestparams.no-params=No hay p\u00e1rametro. Por favor, usa alguno
requestparams.params-in-req=Par\u00e1metros en este Request:
requestparams.title=Ejemplo de solicitud con par\u00e1metros:
sessions.adddata=A\u00f1ade datos a tu sesi\u00f3n:
sessions.created=Creado:
sessions.data=Lo siguientes datos est\u00e1n en tu sesi\u00f3n:
sessions.dataname=Nombre del atributo de sesi\u00f3n:
sessions.datavalue=Valor del atributo de sesi\u00f3n:
sessions.id=ID de Sesi\u00f3n:
sessions.lastaccessed=Ultimo Acceso:
sessions.title=Ejemplo de Sesiones

View File

@@ -0,0 +1,48 @@
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cookies.cookies=Votre navigateur retourne les cookies suivant :
cookies.make-cookie=Cr\u00e9ation d'un cookie \u00e0 retourner \u00e0 votre navigateur
cookies.name=Nom :
cookies.no-cookies=Votre navigateur ne retourne aucun cookie
cookies.set=Vous venez d'envoyer le cookie suivant \u00e0 votre navigateur :
cookies.title=Exemple d'utilisation de Cookies
cookies.value=Valeur :
helloworld.title=Salut le Monde !
requestheader.title=Exemple d'information sur les ent\u00eates de requ\u00eate
requestinfo.label.method=M\u00e9thode :
requestinfo.label.pathinfo=Info de chemin :
requestinfo.label.protocol=Protocole :
requestinfo.label.remoteaddr=Adresse distante :
requestinfo.label.requesturi=URI de requ\u00eate :
requestinfo.title=Exemple d'information sur la requ\u00eate
requestparams.firstname=Pr\u00e9nom :
requestparams.lastname=Nom :
requestparams.no-params=Pas de param\u00eatre, merci d'en saisir quelques-uns
requestparams.params-in-req=Param\u00eatres dans la requ\u00eate :
requestparams.title=Exemple de Requ\u00eate avec Param\u00e8tres
sessions.adddata=Ajouter des donn\u00e9es \u00e0 votre session
sessions.created=Cr\u00e9e le :
sessions.data=Les donn\u00e9es existantes dans votre session :
sessions.dataname=Nom de l'Attribut de Session :
sessions.datavalue=Valeur de l'Attribut de Session :
sessions.id=ID de Session :
sessions.lastaccessed=Dernier acc\u00e8s :
sessions.title=Exemple de Sessions

View File

@@ -0,0 +1,48 @@
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cookies.cookies=\u3042\u306a\u305f\u306e\u306e\u30d6\u30e9\u30a6\u30b6\u304b\u3089\u6b21\u306eCookie\u304c\u9001\u4fe1\u3055\u308c\u3066\u3044\u307e\u3059\uff1a
cookies.make-cookie=\u30d6\u30e9\u30a6\u30b6\u3078\u9001\u4fe1\u3059\u308b cookie \u3092\u4f5c\u6210\u3057\u307e\u3059\u3002
cookies.name=Name:
cookies.no-cookies=\u3042\u306a\u305f\u306e\u30d6\u30e9\u30a6\u30b6\u306f\u30af\u30c3\u30ad\u30fc\u3092\u9001\u4fe1\u3057\u3066\u3044\u307e\u305b\u3093\u3002
cookies.set=\u30d6\u30e9\u30a6\u30b6\u306b cookie \u3092\u9001\u4fe1\u3057\u307e\u3057\u305f\u3002
cookies.title=Cookie \u4f8b
cookies.value=\u5024\uff1a
helloworld.title=Hello World!
requestheader.title=\u30ea\u30af\u30a8\u30b9\u30c8\u30d8\u30c3\u30c0\u4f8b
requestinfo.label.method=\u30e1\u30bd\u30c3\u30c9\uff1a
requestinfo.label.pathinfo=\u30d1\u30b9\u60c5\u5831\uff1a
requestinfo.label.protocol=\u30d7\u30ed\u30c8\u30b3\u30eb\uff1a
requestinfo.label.remoteaddr=\u30ea\u30e2\u30fc\u30c8\u30a2\u30c9\u30ec\u30b9\uff1a
requestinfo.label.requesturi=Request URI:
requestinfo.title=\u30ea\u30af\u30a8\u30b9\u30c8\u60c5\u5831\u4f8b
requestparams.firstname=First Name:
requestparams.lastname=Last Name:
requestparams.no-params=\u30d1\u30e9\u30e1\u30fc\u30bf\u304c\u3042\u308a\u307e\u305b\u3093\u3002\u4f55\u304b\u5165\u529b\u3057\u3066\u304f\u3060\u3055\u3044\u3002
requestparams.params-in-req=\u3053\u306e\u30ea\u30af\u30a8\u30b9\u30c8\u306e\u30d1\u30e9\u30e1\u30fc\u30bf\uff1a
requestparams.title=\u30ea\u30af\u30a8\u30b9\u30c8\u30d1\u30e9\u30e1\u30fc\u30bf\u4f8b
sessions.adddata=\u30bb\u30c3\u30b7\u30e7\u30f3\u306b\u30c7\u30fc\u30bf\u3092\u8ffd\u52a0\u3057\u307e\u3059
sessions.created=\u4f5c\u6210\uff1a
sessions.data=\u3042\u306a\u305f\u306e\u30bb\u30c3\u30b7\u30e7\u30f3\u306b\u306f\u6b21\u306e\u30c7\u30fc\u30bf\u304c\u3042\u308a\u307e\u3059\uff1a
sessions.dataname=\u30bb\u30c3\u30b7\u30e7\u30f3\u5c5e\u6027\u540d\uff1a
sessions.datavalue=\u30bb\u30c3\u30b7\u30e7\u30f3\u5c5e\u6027\u306e\u5024\uff1a
sessions.id=\u30bb\u30c3\u30b7\u30e7\u30f3ID
sessions.lastaccessed=\u6700\u7d42\u30a2\u30af\u30bb\u30b9\uff1a
sessions.title=\u30bb\u30c3\u30b7\u30e7\u30f3\u4f8b

View File

@@ -0,0 +1,48 @@
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cookies.cookies=\uadc0\ud558\uc758 \ube0c\ub77c\uc6b0\uc800\uac00 \ub2e4\uc74c \ucfe0\ud0a4\ub4e4\uc744 \ubcf4\ub0c5\ub2c8\ub2e4.
cookies.make-cookie=\uadc0\ud558\uc758 \ube0c\ub77c\uc6b0\uc800\uc5d0 \uc804\uc1a1\ud558\uae30 \uc704\ud55c \ucfe0\ud0a4 \uc0dd\uc131
cookies.name=\uc774\ub984:
cookies.no-cookies=\uadc0\ud558\uc758 \ube0c\ub77c\uc6b0\uc800\ub294 \uc5b4\ub5a4 \ucfe0\ud0a4\ub3c4 \uc804\uc1a1\ud558\uc9c0 \uc54a\uc2b5\ub2c8\ub2e4.
cookies.set=\uadc0\ud558\ub294 \ub2e4\uc74c \ucfe0\ud0a4\ub97c, \uadc0\ud558\uc758 \ube0c\ub77c\uc6b0\uc800\uc5d0 \uc804\uc1a1\ud588\uc2b5\ub2c8\ub2e4.
cookies.title=\ucfe0\ud0a4\ub4e4\uc758 \uc608\uc81c
cookies.value=\uac12:
helloworld.title=\uc548\ub155 \uc138\uacc4\uc5ec!
requestheader.title=\uc694\uccad\uc758 \ud5e4\ub354 \uc608\uc81c
requestinfo.label.method=\uba54\uc18c\ub4dc:
requestinfo.label.pathinfo=\uacbd\ub85c \uc815\ubcf4:
requestinfo.label.protocol=\ud504\ub85c\ud1a0\ucf5c:
requestinfo.label.remoteaddr=\uc6d0\uaca9 \uc8fc\uc18c:
requestinfo.label.requesturi=\uc694\uccad URI:
requestinfo.title=\uc694\uccad \uc815\ubcf4 \uc608\uc81c
requestparams.firstname=\uc774\ub984:
requestparams.lastname=\uc131
requestparams.no-params=\ud30c\ub77c\ubbf8\ud130\ub4e4\uc774 \uc5c6\uc2b5\ub2c8\ub2e4. \ud30c\ub77c\ubbf8\ud130\ub4e4\uc744 \uc785\ub825\ud558\uc2ed\uc2dc\uc624.
requestparams.params-in-req=\uc774 \uc694\uccad\uc758 \ud30c\ub77c\ubbf8\ud130\ub4e4:
requestparams.title=\uc694\uccad \ud30c\ub77c\ubbf8\ud130\ub4e4\uc758 \uc608\uc81c
sessions.adddata=\uadc0\ud558\uc758 \uc138\uc158\uc5d0 \ub370\uc774\ud130\ub97c \ucd94\uac00
sessions.created=\uc0dd\uc131\uc2dc\uac04:
sessions.data=\uadc0\ud558\uc758 \uc138\uc158\uc5d0 \ub2e4\uc74c \ub370\uc774\ud130\uac00 \uc788\uc2b5\ub2c8\ub2e4:
sessions.dataname=\uc138\uc158 \uc18d\uc131 \uc774\ub984:
sessions.datavalue=\uc138\uc158 \uc18d\uc131 \uac12:
sessions.id=\uc138\uc158 ID:
sessions.lastaccessed=\ucd5c\uc885 \uc811\uadfc \uc2dc\uac04:
sessions.title=\uc138\uc158\ub4e4\uc758 \uc608\uc81c

View File

@@ -0,0 +1,48 @@
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cookies.cookies=O se browser esta a enviar os seguintes cookies:
cookies.make-cookie=Crie um cookie para enviar para o seu browser
cookies.name=Nome:
cookies.no-cookies=O seu browser nao esta a enviar nenhuns cookies
cookies.set=Acabou de enviar o seguinte cookie para o seu browser:
cookies.title=CExamplo de Cookies
cookies.value=Valor:
helloworld.title=Ola Mundo!
requestheader.title=Exemplo da Cebeceira do Pedido
requestinfo.label.method=Metodo:
requestinfo.label.pathinfo=Informacao do Caminho:
requestinfo.label.protocol=Protocolo:
requestinfo.label.remoteaddr=Endereco Remoto:
requestinfo.label.requesturi=URI do Pedido:
requestinfo.title=Exemplo da Informacao do Pedido
requestparams.firstname=Primeiro Nome:
requestparams.lastname=Apelido:
requestparams.no-params=Sem Parametros, Por favor entre alguns
requestparams.params-in-req=Parametros neste pedido:
requestparams.title=Examplo de Parametros do Pedido
sessions.adddata=Adicione data a sua sessao
sessions.created=Criada:
sessions.data=Os seguintes dados fazem parte da sua sessao:
sessions.dataname=Nome do atributo da sessao:
sessions.datavalue=Valor do atributo da Sessao:
sessions.id=Identificador da Sessao:
sessions.lastaccessed=Ultima vez acedida:
sessions.title=Examplo de sessoes

View File

@@ -0,0 +1,16 @@
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
requestparams.title=Exemplo de Par\u00e2metros de Requisi\u00e7\u00e3o

View File

@@ -0,0 +1,16 @@
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
requestparams.title=\u041f\u0440\u0438\u043c\u0435\u0440 \u043f\u0430\u0440\u0430\u043c\u0435\u0442\u0440\u043e\u0432 \u0437\u0430\u043f\u0440\u043e\u0441\u0430

View File

@@ -0,0 +1,48 @@
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cookies.cookies=\u4f60\u7684\u6d4f\u89c8\u5668\u6b63\u5728\u53d1\u9001\u4e0b\u9762\u7684cookie\uff1a
cookies.make-cookie=\u521b\u5efa\u4e00\u4e2a\u53d1\u9001\u5230\u4f60\u7684\u6d4f\u89c8\u5668\u7684cookie
cookies.name=\u540d.\u79f0:
cookies.no-cookies=\u4f60\u7684\u6d4f\u89c8\u5668\u672a\u53d1\u9001\u4efb\u4f55cookie
cookies.set=\u4f60\u521a\u521a\u5c06\u4ee5\u4e0bcookie\u53d1\u9001\u5230\u4f60\u7684\u6d4f\u89c8\u5668\uff1a
cookies.title=cookie\u793a\u4f8b
cookies.value=\u503c\uff1a
helloworld.title=\u4f60\u597d\uff0c\u4e16\u754c.
requestheader.title=\u8bf7\u6c42 Header \u793a\u4f8b
requestinfo.label.method=\u65b9\u6cd5\uff1a
requestinfo.label.pathinfo=\u8def\u5f84\u4fe1\u606f\uff1a
requestinfo.label.protocol=\u534f\u8bae\uff1a
requestinfo.label.remoteaddr=\u8fdc\u7a0b\u5730\u5740\uff1a
requestinfo.label.requesturi=\u8bf7\u6c42 URI (:
requestinfo.title=\u8bf7\u6c42\u4fe1\u606f\u8303\u4f8b
requestparams.firstname=\u59d3\uff1a
requestparams.lastname=\u59d3\u6c0f\uff1a
requestparams.no-params=\u6ca1\u6709\u53c2\u6570\uff0c\u8bf7\u8f93\u5165\u4e00\u4e9b
requestparams.params-in-req=\u53c2\u6570\u5728\u8bf7\u6c42\u4e2d.
requestparams.title=\u8bf7\u6c42\u53c2\u6570\u793a\u4f8b
sessions.adddata=\u5c06\u6570\u636e\u6dfb\u52a0\u5230\u4f60\u7684\u4f1a\u8bdd\u4e2d
sessions.created=\u5df2\u521b\u5efa\u7684\uff1a
sessions.data=\u4ee5\u4e0b\u6570\u636e\u5728\u60a8\u7684\u4f1a\u8bdd\u4e2d\uff1a
sessions.dataname=\u4f1a\u8bdd\u5c5e\u6027\u540d\uff1a
sessions.datavalue=\u4f1a\u8bdd\u5c5e\u6027\u503c\uff1a
sessions.id=\u4f1a\u8bddID\uff1a
sessions.lastaccessed=\u6700\u540e\u8bbf\u95ee\uff1a
sessions.title=\u4f1a\u8bdd.\u793a\u4f8b

View File

@@ -0,0 +1,109 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import util.CookieFilter;
import util.HTMLFilter;
/**
* Example servlet showing request headers
*
* @author James Duncan Davidson &lt;duncan@eng.sun.com>
*/
public class RequestHeaderExample extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
ResourceBundle rb = ResourceBundle.getBundle("LocalStrings",request.getLocale());
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html><html>");
out.println("<head>");
out.println("<meta charset=\"UTF-8\" />");
String title = rb.getString("requestheader.title");
out.println("<title>" + title + "</title>");
out.println("</head>");
out.println("<body bgcolor=\"white\">");
// all links relative
// XXX
// making these absolute till we work out the
// addition of a PathInfo issue
out.println("<a href=\"../reqheaders.html\">");
out.println("<img src=\"../images/code.gif\" height=24 " +
"width=24 align=right border=0 alt=\"view code\"></a>");
out.println("<a href=\"../index.html\">");
out.println("<img src=\"../images/return.gif\" height=24 " +
"width=24 align=right border=0 alt=\"return\"></a>");
out.println("<h3>" + title + "</h3>");
out.println("<table border=0>");
Enumeration<String> e = request.getHeaderNames();
while (e.hasMoreElements()) {
String headerName = e.nextElement();
String headerValue = request.getHeader(headerName);
out.println("<tr><td bgcolor=\"#CCCCCC\">");
out.println(HTMLFilter.filter(headerName));
out.println("</td><td>");
if (headerName.toLowerCase(Locale.ENGLISH).contains("cookie")) {
HttpSession session = request.getSession(false);
String sessionId = null;
if (session != null) {
sessionId = session.getId();
}
out.println(HTMLFilter.filter(CookieFilter.filter(headerValue, sessionId)));
} else {
out.println(HTMLFilter.filter(headerValue));
}
out.println("</td></tr>");
}
out.println("</table>");
}
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}

View File

@@ -0,0 +1,118 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ResourceBundle;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import util.HTMLFilter;
/**
* Example servlet showing request information.
*
* @author James Duncan Davidson &lt;duncan@eng.sun.com>
*/
public class RequestInfoExample extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
ResourceBundle rb = ResourceBundle.getBundle("LocalStrings",request.getLocale());
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html><html>");
out.println("<head>");
out.println("<meta charset=\"UTF-8\" />");
String title = rb.getString("requestinfo.title");
out.println("<title>" + title + "</title>");
out.println("</head>");
out.println("<body bgcolor=\"white\">");
// img stuff not req'd for source code HTML showing
// all links relative!
// XXX
// making these absolute till we work out the
// addition of a PathInfo issue
out.println("<a href=\"../reqinfo.html\">");
out.println("<img src=\"../images/code.gif\" height=24 " +
"width=24 align=right border=0 alt=\"view code\"></a>");
out.println("<a href=\"../index.html\">");
out.println("<img src=\"../images/return.gif\" height=24 " +
"width=24 align=right border=0 alt=\"return\"></a>");
out.println("<h3>" + title + "</h3>");
out.println("<table border=0><tr><td>");
out.println(rb.getString("requestinfo.label.method"));
out.println("</td><td>");
out.println(HTMLFilter.filter(request.getMethod()));
out.println("</td></tr><tr><td>");
out.println(rb.getString("requestinfo.label.requesturi"));
out.println("</td><td>");
out.println(HTMLFilter.filter(request.getRequestURI()));
out.println("</td></tr><tr><td>");
out.println(rb.getString("requestinfo.label.protocol"));
out.println("</td><td>");
out.println(HTMLFilter.filter(request.getProtocol()));
out.println("</td></tr><tr><td>");
out.println(rb.getString("requestinfo.label.pathinfo"));
out.println("</td><td>");
out.println(HTMLFilter.filter(request.getPathInfo()));
out.println("</td></tr><tr><td>");
out.println(rb.getString("requestinfo.label.remoteaddr"));
out.println("</td><td>");
out.println(HTMLFilter.filter(request.getRemoteAddr()));
out.println("</td></tr>");
String cipherSuite=
(String)request.getAttribute("javax.servlet.request.cipher_suite");
if(cipherSuite!=null){
out.println("<tr><td>");
out.println("SSLCipherSuite:");
out.println("</td><td>");
out.println(HTMLFilter.filter(cipherSuite));
out.println("</td></tr>");
}
out.println("</table>");
}
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}

View File

@@ -0,0 +1,111 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ResourceBundle;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import util.HTMLFilter;
/**
* Example servlet showing request headers
*
* @author James Duncan Davidson &lt;duncan@eng.sun.com>
*/
public class RequestParamExample extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
ResourceBundle rb = ResourceBundle.getBundle("LocalStrings",request.getLocale());
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html><html>");
out.println("<head>");
out.println("<meta charset=\"UTF-8\" />");
String title = rb.getString("requestparams.title");
out.println("<title>" + title + "</title>");
out.println("</head>");
out.println("<body bgcolor=\"white\">");
// img stuff not req'd for source code HTML showing
// all links relative
// XXX
// making these absolute till we work out the
// addition of a PathInfo issue
out.println("<a href=\"../reqparams.html\">");
out.println("<img src=\"../images/code.gif\" height=24 " +
"width=24 align=right border=0 alt=\"view code\"></a>");
out.println("<a href=\"../index.html\">");
out.println("<img src=\"../images/return.gif\" height=24 " +
"width=24 align=right border=0 alt=\"return\"></a>");
out.println("<h3>" + title + "</h3>");
String firstName = request.getParameter("firstname");
String lastName = request.getParameter("lastname");
out.println(rb.getString("requestparams.params-in-req") + "<br>");
if (firstName != null || lastName != null) {
out.println(rb.getString("requestparams.firstname"));
out.println(" = " + HTMLFilter.filter(firstName) + "<br>");
out.println(rb.getString("requestparams.lastname"));
out.println(" = " + HTMLFilter.filter(lastName));
} else {
out.println(rb.getString("requestparams.no-params"));
}
out.println("<P>");
out.print("<form action=\"");
out.print("RequestParamExample\" ");
out.println("method=POST>");
out.println(rb.getString("requestparams.firstname"));
out.println("<input type=text size=20 name=firstname>");
out.println("<br>");
out.println(rb.getString("requestparams.lastname"));
out.println("<input type=text size=20 name=lastname>");
out.println("<br>");
out.println("<input type=submit>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}

View File

@@ -0,0 +1,39 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletToJsp extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet (HttpServletRequest request,
HttpServletResponse response) {
try {
// Set the attribute and Forward to hello.jsp
request.setAttribute ("servletName", "servletToJsp");
getServletConfig().getServletContext().getRequestDispatcher(
"/jsp/jsptoserv/hello.jsp").forward(request, response);
} catch (Exception ex) {
ex.printStackTrace ();
}
}
}

View File

@@ -0,0 +1,147 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;
import java.util.ResourceBundle;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import util.HTMLFilter;
/**
* Example servlet showing request headers
*
* @author James Duncan Davidson &lt;duncan@eng.sun.com>
*/
public class SessionExample extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
ResourceBundle rb = ResourceBundle.getBundle("LocalStrings",request.getLocale());
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html><html>");
out.println("<head>");
out.println("<meta charset=\"UTF-8\" />");
String title = rb.getString("sessions.title");
out.println("<title>" + title + "</title>");
out.println("</head>");
out.println("<body bgcolor=\"white\">");
// img stuff not req'd for source code HTML showing
// relative links everywhere!
// XXX
// making these absolute till we work out the
// addition of a PathInfo issue
out.println("<a href=\"../sessions.html\">");
out.println("<img src=\"../images/code.gif\" height=24 " +
"width=24 align=right border=0 alt=\"view code\"></a>");
out.println("<a href=\"../index.html\">");
out.println("<img src=\"../images/return.gif\" height=24 " +
"width=24 align=right border=0 alt=\"return\"></a>");
out.println("<h3>" + title + "</h3>");
HttpSession session = request.getSession(true);
out.println(rb.getString("sessions.id") + " " + session.getId());
out.println("<br>");
out.println(rb.getString("sessions.created") + " ");
out.println(new Date(session.getCreationTime()) + "<br>");
out.println(rb.getString("sessions.lastaccessed") + " ");
out.println(new Date(session.getLastAccessedTime()));
String dataName = request.getParameter("dataname");
String dataValue = request.getParameter("datavalue");
if (dataName != null && dataValue != null) {
session.setAttribute(dataName, dataValue);
}
out.println("<P>");
out.println(rb.getString("sessions.data") + "<br>");
Enumeration<String> names = session.getAttributeNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String value = session.getAttribute(name).toString();
out.println(HTMLFilter.filter(name) + " = "
+ HTMLFilter.filter(value) + "<br>");
}
out.println("<P>");
out.print("<form action=\"");
out.print(response.encodeURL("SessionExample"));
out.print("\" ");
out.println("method=POST>");
out.println(rb.getString("sessions.dataname"));
out.println("<input type=text size=20 name=dataname>");
out.println("<br>");
out.println(rb.getString("sessions.datavalue"));
out.println("<input type=text size=20 name=datavalue>");
out.println("<br>");
out.println("<input type=submit>");
out.println("</form>");
out.println("<P>GET based form:<br>");
out.print("<form action=\"");
out.print(response.encodeURL("SessionExample"));
out.print("\" ");
out.println("method=GET>");
out.println(rb.getString("sessions.dataname"));
out.println("<input type=text size=20 name=dataname>");
out.println("<br>");
out.println(rb.getString("sessions.datavalue"));
out.println("<input type=text size=20 name=datavalue>");
out.println("<br>");
out.println("<input type=submit>");
out.println("</form>");
out.print("<p><a href=\"");
out.print(HTMLFilter.filter(response.encodeURL("SessionExample?dataname=foo&datavalue=bar")));
out.println("\" >URL encoded </a>");
out.println("</body>");
out.println("</html>");
}
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
doGet(request, response);
}
}

View File

@@ -0,0 +1,69 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package async;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
public class Async0 extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(Async0.class);
@Override
protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
if (Boolean.TRUE.equals(req.getAttribute("dispatch"))) {
log.info("Received dispatch, completing on the worker thread.");
log.info("After complete called started:"+req.isAsyncStarted());
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
resp.getWriter().write("Async dispatch worked: " + sdf.format(date) + "\n");
} else {
resp.setContentType("text/plain");
final AsyncContext actx = req.startAsync();
actx.setTimeout(Long.MAX_VALUE);
Runnable run = new Runnable() {
@Override
public void run() {
try {
req.setAttribute("dispatch", Boolean.TRUE);
Thread.currentThread().setName("Async0-Thread");
log.info("Putting AsyncThread to sleep");
Thread.sleep(2*1000);
log.info("Dispatching");
actx.dispatch();
}catch (InterruptedException | IllegalStateException x) {
log.error("Async1",x);
}
}
};
Thread t = new Thread(run);
t.start();
}
}
}

View File

@@ -0,0 +1,60 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package async;
import java.io.IOException;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
public class Async1 extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(Async1.class);
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
final AsyncContext actx = req.startAsync();
actx.setTimeout(30*1000);
Runnable run = new Runnable() {
@Override
public void run() {
try {
String path = "/jsp/async/async1.jsp";
Thread.currentThread().setName("Async1-Thread");
log.info("Putting AsyncThread to sleep");
Thread.sleep(2*1000);
log.info("Dispatching to "+path);
actx.dispatch(path);
}catch (InterruptedException | IllegalStateException x) {
log.error("Async1",x);
}
}
};
Thread t = new Thread(run);
t.start();
}
}

View File

@@ -0,0 +1,66 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package async;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
public class Async2 extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(Async2.class);
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
final AsyncContext actx = req.startAsync();
actx.setTimeout(30*1000);
Runnable run = new Runnable() {
@Override
public void run() {
try {
Thread.currentThread().setName("Async2-Thread");
log.info("Putting AsyncThread to sleep");
Thread.sleep(2*1000);
log.info("Writing data.");
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
actx.getResponse().getWriter().write(
"Output from background thread. Time: " + sdf.format(date) + "\n");
actx.complete();
}catch (InterruptedException | IllegalStateException | IOException x) {
log.error("Async2",x);
}
}
};
Thread t = new Thread(run);
t.start();
}
}

View File

@@ -0,0 +1,39 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package async;
import java.io.IOException;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Async3 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
final AsyncContext actx = req.startAsync();
actx.setTimeout(30*1000);
actx.dispatch("/jsp/async/async3.jsp");
}
}

View File

@@ -0,0 +1,44 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package async;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/*
* Ensures the Stockticker is shut down cleanly when the context stops. This
* also covers the case when the server shuts down.
*/
public class AsyncStockContextListener implements ServletContextListener {
public static final String STOCK_TICKER_KEY = "StockTicker";
@Override
public void contextInitialized(ServletContextEvent sce) {
Stockticker stockticker = new Stockticker();
ServletContext sc = sce.getServletContext();
sc.setAttribute(STOCK_TICKER_KEY, stockticker);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
Stockticker stockticker = (Stockticker) sc.getAttribute(STOCK_TICKER_KEY);
stockticker.shutdown();
}
}

View File

@@ -0,0 +1,144 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package async;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import async.Stockticker.Stock;
import async.Stockticker.TickListener;
public class AsyncStockServlet extends HttpServlet implements TickListener, AsyncListener{
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(AsyncStockServlet.class);
private static final ConcurrentLinkedQueue<AsyncContext> clients =
new ConcurrentLinkedQueue<>();
private static final AtomicInteger clientcount = new AtomicInteger(0);
public AsyncStockServlet() {
log.info("AsyncStockServlet created");
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (req.isAsyncStarted()) {
req.getAsyncContext().complete();
} else if (req.isAsyncSupported()) {
AsyncContext actx = req.startAsync();
actx.addListener(this);
resp.setContentType("text/plain");
clients.add(actx);
if (clientcount.incrementAndGet()==1) {
Stockticker ticker = (Stockticker) req.getServletContext().getAttribute(
AsyncStockContextListener.STOCK_TICKER_KEY);
ticker.addTickListener(this);
}
} else {
new Exception("Async Not Supported").printStackTrace();
resp.sendError(400,"Async is not supported.");
}
}
@Override
public void tick(Stock stock) {
for (AsyncContext actx : clients) {
try {
writeStock(actx, stock);
} catch (Exception e) {
// Ignore. The async error handling will deal with this.
}
}
}
public void writeStock(AsyncContext actx, Stock stock) throws IOException {
HttpServletResponse response = (HttpServletResponse)actx.getResponse();
PrintWriter writer = response.getWriter();
writer.write("STOCK#");//make client parsing easier
writer.write(stock.getSymbol());
writer.write("#");
writer.write(stock.getValueAsString());
writer.write("#");
writer.write(stock.getLastChangeAsString());
writer.write("#");
writer.write(String.valueOf(stock.getCnt()));
writer.write("\n");
writer.flush();
response.flushBuffer();
}
@Override
public void shutdown() {
// The web application is shutting down. Complete any AsyncContexts
// associated with an active client.
for (AsyncContext actx : clients) {
try {
actx.complete();
} catch (Exception e) {
// Ignore. The async error handling will deal with this.
}
}
}
@Override
public void onComplete(AsyncEvent event) throws IOException {
if (clients.remove(event.getAsyncContext()) && clientcount.decrementAndGet()==0) {
ServletContext sc = event.getAsyncContext().getRequest().getServletContext();
Stockticker ticker = (Stockticker) sc.getAttribute(
AsyncStockContextListener.STOCK_TICKER_KEY);
ticker.removeTickListener(this);
}
}
@Override
public void onError(AsyncEvent event) throws IOException {
event.getAsyncContext().complete();
}
@Override
public void onTimeout(AsyncEvent event) throws IOException {
event.getAsyncContext().complete();
}
@Override
public void onStartAsync(AsyncEvent event) throws IOException {
// NOOP
}
}

View File

@@ -0,0 +1,212 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package async;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
public class Stockticker implements Runnable {
public volatile boolean run = true;
protected final AtomicInteger counter = new AtomicInteger(0);
final List<TickListener> listeners = new CopyOnWriteArrayList<>();
protected volatile Thread ticker = null;
protected volatile int ticknr = 0;
public synchronized void start() {
run = true;
ticker = new Thread(this);
ticker.setName("Ticker Thread");
ticker.start();
}
public synchronized void stop() {
// On context stop this can be called multiple times.
// NO-OP is the ticker thread is not set
// (i.e. stop() has already completed)
if (ticker == null) {
return;
}
run = false;
try {
ticker.join();
}catch (InterruptedException x) {
Thread.interrupted();
}
ticker = null;
}
public void shutdown() {
// Notify each listener of the shutdown. This enables them to
// trigger any necessary clean-up.
for (TickListener l : listeners) {
l.shutdown();
}
// Wait for the thread to stop. This prevents warnings in the logs
// that the thread is still active when the context stops.
stop();
}
public void addTickListener(TickListener listener) {
if (listeners.add(listener)) {
if (counter.incrementAndGet()==1) {
start();
}
}
}
public void removeTickListener(TickListener listener) {
if (listeners.remove(listener)) {
if (counter.decrementAndGet()==0) {
stop();
}
}
}
@Override
public void run() {
try {
Stock[] stocks = new Stock[] { new Stock("GOOG", 435.43),
new Stock("YHOO", 27.88), new Stock("ASF", 1015.55), };
Random r = new Random(System.currentTimeMillis());
while (run) {
for (int j = 0; j < 1; j++) {
int i = r.nextInt() % 3;
if (i < 0) {
i = i * (-1);
}
Stock stock = stocks[i];
double change = r.nextDouble();
boolean plus = r.nextBoolean();
if (plus) {
stock.setValue(stock.getValue() + change);
} else {
stock.setValue(stock.getValue() - change);
}
stock.setCnt(++ticknr);
for (TickListener l : listeners) {
l.tick(stock);
}
}
Thread.sleep(850);
}
} catch (InterruptedException ix) {
// Ignore
} catch (Exception x) {
x.printStackTrace();
}
}
public interface TickListener {
void tick(Stock stock);
void shutdown();
}
public static final class Stock implements Cloneable {
protected static final DecimalFormat df = new DecimalFormat("0.00");
protected final String symbol;
protected double value = 0.0d;
protected double lastchange = 0.0d;
protected int cnt = 0;
public Stock(String symbol, double initvalue) {
this.symbol = symbol;
this.value = initvalue;
}
public void setCnt(int c) {
this.cnt = c;
}
public int getCnt() {
return cnt;
}
public String getSymbol() {
return symbol;
}
public double getValue() {
return value;
}
public void setValue(double value) {
double old = this.value;
this.value = value;
this.lastchange = value - old;
}
public String getValueAsString() {
return df.format(value);
}
public double getLastChange() {
return this.lastchange;
}
public void setLastChange(double lastchange) {
this.lastchange = lastchange;
}
public String getLastChangeAsString() {
return df.format(lastchange);
}
@Override
public int hashCode() {
return symbol.hashCode();
}
@Override
public boolean equals(Object other) {
if (other instanceof Stock) {
return this.symbol.equals(((Stock) other).symbol);
}
return false;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder("STOCK#");
buf.append(getSymbol());
buf.append('#');
buf.append(getValueAsString());
buf.append('#');
buf.append(getLastChangeAsString());
buf.append('#');
buf.append(String.valueOf(getCnt()));
return buf.toString();
}
@Override
public Object clone() {
Stock s = new Stock(this.getSymbol(), this.getValue());
s.setLastChange(this.getLastChange());
s.setCnt(this.cnt);
return s;
}
}
}

View File

@@ -0,0 +1,63 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
public class Entries {
private final Map<String, Entry> entries;
private static final String[] time = { "8am", "9am", "10am", "11am",
"12pm", "1pm", "2pm", "3pm", "4pm", "5pm", "6pm", "7pm", "8pm" };
public static final int rows = 12;
public Entries() {
entries = new ConcurrentHashMap<>(rows);
for (int i = 0; i < rows; i++) {
entries.put(time[i], new Entry(time[i]));
}
}
public int getRows() {
return rows;
}
public Entry getEntry(int index) {
return this.entries.get(time[index]);
}
public int getIndex(String tm) {
for (int i = 0; i < rows; i++) {
if (tm.equals(time[i])) {
return i;
}
}
return -1;
}
public void processRequest(HttpServletRequest request, String tm) {
int index = getIndex(tm);
if (index >= 0) {
String descr = request.getParameter("description");
entries.get(time[index]).setDescription(descr);
}
}
}

View File

@@ -0,0 +1,52 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cal;
public class Entry {
final String hour;
String description;
public Entry(String hour) {
this.hour = hour;
this.description = "";
}
public String getHour() {
return this.hour;
}
public String getColor() {
if (description.equals("")) {
return "lightblue";
}
return "red";
}
public String getDescription() {
if (description.equals("")) {
return "None";
}
return this.description;
}
public void setDescription(String descr) {
description = descr;
}
}

View File

@@ -0,0 +1,152 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cal;
import java.util.Calendar;
import java.util.Date;
public class JspCalendar {
final Calendar calendar;
public JspCalendar() {
calendar = Calendar.getInstance();
Date trialTime = new Date();
calendar.setTime(trialTime);
}
public int getYear() {
return calendar.get(Calendar.YEAR);
}
public String getMonth() {
int m = getMonthInt();
String[] months = new String [] { "January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December" };
if (m > 12) {
return "Unknown to Man";
}
return months[m - 1];
}
public String getDay() {
int x = getDayOfWeek();
String[] days = new String[] {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
if (x > 7) {
return "Unknown to Man";
}
return days[x - 1];
}
public int getMonthInt() {
return 1 + calendar.get(Calendar.MONTH);
}
public String getDate() {
return getMonthInt() + "/" + getDayOfMonth() + "/" + getYear();
}
public String getCurrentDate() {
Date dt = new Date ();
calendar.setTime (dt);
return getMonthInt() + "/" + getDayOfMonth() + "/" + getYear();
}
public String getNextDate() {
calendar.set (Calendar.DAY_OF_MONTH, getDayOfMonth() + 1);
return getDate ();
}
public String getPrevDate() {
calendar.set (Calendar.DAY_OF_MONTH, getDayOfMonth() - 1);
return getDate ();
}
public String getTime() {
return getHour() + ":" + getMinute() + ":" + getSecond();
}
public int getDayOfMonth() {
return calendar.get(Calendar.DAY_OF_MONTH);
}
public int getDayOfYear() {
return calendar.get(Calendar.DAY_OF_YEAR);
}
public int getWeekOfYear() {
return calendar.get(Calendar.WEEK_OF_YEAR);
}
public int getWeekOfMonth() {
return calendar.get(Calendar.WEEK_OF_MONTH);
}
public int getDayOfWeek() {
return calendar.get(Calendar.DAY_OF_WEEK);
}
public int getHour() {
return calendar.get(Calendar.HOUR_OF_DAY);
}
public int getMinute() {
return calendar.get(Calendar.MINUTE);
}
public int getSecond() {
return calendar.get(Calendar.SECOND);
}
public int getEra() {
return calendar.get(Calendar.ERA);
}
public String getUSTimeZone() {
String[] zones = new String[] {"Hawaii", "Alaskan", "Pacific",
"Mountain", "Central", "Eastern"};
return zones[10 + getZoneOffset()];
}
public int getZoneOffset() {
return calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000);
}
public int getDSTOffset() {
return calendar.get(Calendar.DST_OFFSET)/(60*60*1000);
}
public int getAMPM() {
return calendar.get(Calendar.AM_PM);
}
}

View File

@@ -0,0 +1,106 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
public class TableBean {
private final Map<String, Entries> table;
private final JspCalendar JspCal;
private Entries entries;
private String date;
private String name = null;
private String email = null;
private boolean processError = false;
public TableBean() {
this.table = new ConcurrentHashMap<>(10);
this.JspCal = new JspCalendar();
this.date = JspCal.getCurrentDate();
}
public void setName(String nm) {
this.name = nm;
}
public String getName() {
return this.name;
}
public void setEmail(String mail) {
this.email = mail;
}
public String getEmail() {
return this.email;
}
public String getDate() {
return this.date;
}
public Entries getEntries() {
return this.entries;
}
public void processRequest(HttpServletRequest request) {
// Get the name and e-mail.
this.processError = false;
if (name == null || name.equals("")) {
setName(request.getParameter("name"));
}
if (email == null || email.equals("")) {
setEmail(request.getParameter("email"));
}
if (name == null || email == null || name.equals("")
|| email.equals("")) {
this.processError = true;
return;
}
// Get the date.
String dateR = request.getParameter("date");
if (dateR == null) {
date = JspCal.getCurrentDate();
} else if (dateR.equalsIgnoreCase("next")) {
date = JspCal.getNextDate();
} else if (dateR.equalsIgnoreCase("prev")) {
date = JspCal.getPrevDate();
}
entries = table.get(date);
if (entries == null) {
entries = new Entries();
table.put(date, entries);
}
// If time is provided add the event.
String time = request.getParameter("time");
if (time != null) {
entries.processRequest(request, time);
}
}
public boolean getProcessError() {
return this.processError;
}
}

View File

@@ -0,0 +1,30 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package checkbox;
public class CheckTest {
String b[] = new String[] { "1", "2", "3", "4" };
public String[] getFruit() {
return b;
}
public void setFruit(String [] b) {
this.b = b;
}
}

View File

@@ -0,0 +1,114 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package colors;
public class ColorGameBean {
private String background = "yellow";
private String foreground = "red";
private String color1 = foreground;
private String color2 = background;
private String hint = "no";
private int attempts = 0;
private int intval = 0;
private boolean tookHints = false;
public void processRequest() {
// background = "yellow";
// foreground = "red";
if (! color1.equals(foreground)) {
if (color1.equalsIgnoreCase("black") ||
color1.equalsIgnoreCase("cyan")) {
background = color1;
}
}
if (! color2.equals(background)) {
if (color2.equalsIgnoreCase("black") ||
color2.equalsIgnoreCase("cyan")) {
foreground = color2;
}
}
attempts++;
}
public void setColor2(String x) {
color2 = x;
}
public void setColor1(String x) {
color1 = x;
}
public void setAction(String x) {
if (!tookHints) {
tookHints = x.equalsIgnoreCase("Hint");
}
hint = x;
}
public String getColor2() {
return background;
}
public String getColor1() {
return foreground;
}
public int getAttempts() {
return attempts;
}
public boolean getHint() {
return hint.equalsIgnoreCase("Hint");
}
public boolean getSuccess() {
if (background.equalsIgnoreCase("black") ||
background.equalsIgnoreCase("cyan")) {
if (foreground.equalsIgnoreCase("black") ||
foreground.equalsIgnoreCase("cyan")) {
return true;
}
return false;
}
return false;
}
public boolean getHintTaken() {
return tookHints;
}
public void reset() {
foreground = "red";
background = "yellow";
}
public void setIntval(int value) {
intval = value;
}
public int getIntval() {
return intval;
}
}

View File

@@ -0,0 +1,224 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package compressionFilters;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.StringTokenizer;
import javax.servlet.FilterChain;
import javax.servlet.GenericFilter;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Implementation of <code>javax.servlet.Filter</code> used to compress
* the ServletResponse if it is bigger than a threshold.
*
* @author Amy Roh
* @author Dmitri Valdin
*/
public class CompressionFilter extends GenericFilter {
private static final long serialVersionUID = 1L;
/**
* Minimal reasonable threshold.
*/
private static final int MIN_THRESHOLD = 128;
/**
* Minimal reasonable buffer.
*/
// 8KB is what tomcat would use by default anyway
private static final int MIN_BUFFER = 8192;
/**
* The threshold number to compress.
*/
protected int compressionThreshold = 0;
/**
* The compression buffer size to avoid chunking.
*/
protected int compressionBuffer = 0;
/**
* The mime types to compress.
*/
protected String[] compressionMimeTypes = {"text/html", "text/xml", "text/plain"};
/**
* Debug level for this filter.
*/
private int debug = 0;
@Override
public void init() {
String str = getInitParameter("debug");
if (str != null) {
debug = Integer.parseInt(str);
}
str = getInitParameter("compressionThreshold");
if (str != null) {
compressionThreshold = Integer.parseInt(str);
if (compressionThreshold != 0 && compressionThreshold < MIN_THRESHOLD) {
if (debug > 0) {
System.out.println("compressionThreshold should be either 0 - no compression or >= " + MIN_THRESHOLD);
System.out.println("compressionThreshold set to " + MIN_THRESHOLD);
}
compressionThreshold = MIN_THRESHOLD;
}
}
str = getInitParameter("compressionBuffer");
if (str != null) {
compressionBuffer = Integer.parseInt(str);
if (compressionBuffer < MIN_BUFFER) {
if (debug > 0) {
System.out.println("compressionBuffer should be >= " + MIN_BUFFER);
System.out.println("compressionBuffer set to " + MIN_BUFFER);
}
compressionBuffer = MIN_BUFFER;
}
}
str = getInitParameter("compressionMimeTypes");
if (str != null) {
List<String> values = new ArrayList<>();
StringTokenizer st = new StringTokenizer(str, ",");
while (st.hasMoreTokens()) {
String token = st.nextToken().trim();
if (token.length() > 0) {
values.add(token);
}
}
if (values.size() > 0) {
compressionMimeTypes = values.toArray(new String[0]);
} else {
compressionMimeTypes = null;
}
if (debug > 0) {
System.out.println("compressionMimeTypes set to " +
Arrays.toString(compressionMimeTypes));
}
}
}
/**
* The <code>doFilter</code> method of the Filter is called by the container
* each time a request/response pair is passed through the chain due
* to a client request for a resource at the end of the chain.
* The FilterChain passed into this method allows the Filter to pass on the
* request and response to the next entity in the chain.<p>
* This method first examines the request to check whether the client support
* compression. <br>
* It simply just pass the request and response if there is no support for
* compression.<br>
* If the compression support is available, it creates a
* CompressionServletResponseWrapper object which compresses the content and
* modifies the header if the content length is big enough.
* It then invokes the next entity in the chain using the FilterChain object
* (<code>chain.doFilter()</code>), <br>
**/
@Override
public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain )
throws IOException, ServletException {
if (debug > 0) {
System.out.println("@doFilter");
}
if (compressionThreshold == 0) {
if (debug > 0) {
System.out.println("doFilter got called, but compressionThreshold is set to 0 - no compression");
}
chain.doFilter(request, response);
return;
}
boolean supportCompression = false;
if (request instanceof HttpServletRequest) {
if (debug > 1) {
System.out.println("requestURI = " + ((HttpServletRequest)request).getRequestURI());
}
// Are we allowed to compress ?
String s = ((HttpServletRequest)request).getParameter("gzip");
if ("false".equals(s)) {
if (debug > 0) {
System.out.println("got parameter gzip=false --> don't compress, just chain filter");
}
chain.doFilter(request, response);
return;
}
Enumeration<String> e =
((HttpServletRequest)request).getHeaders("Accept-Encoding");
while (e.hasMoreElements()) {
String name = e.nextElement();
if (name.indexOf("gzip") != -1) {
if (debug > 0) {
System.out.println("supports compression");
}
supportCompression = true;
} else {
if (debug > 0) {
System.out.println("no support for compression");
}
}
}
}
if (supportCompression) {
if (response instanceof HttpServletResponse) {
CompressionServletResponseWrapper wrappedResponse =
new CompressionServletResponseWrapper((HttpServletResponse)response);
wrappedResponse.setDebugLevel(debug);
wrappedResponse.setCompressionThreshold(compressionThreshold);
wrappedResponse.setCompressionBuffer(compressionBuffer);
wrappedResponse.setCompressionMimeTypes(compressionMimeTypes);
if (debug > 0) {
System.out.println("doFilter gets called with compression");
}
try {
chain.doFilter(request, wrappedResponse);
} finally {
wrappedResponse.finishResponse();
}
return;
}
} else {
if (debug > 0) {
System.out.println("doFilter gets called w/o compression");
}
chain.doFilter(request, response);
return;
}
}
}

View File

@@ -0,0 +1,65 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package compressionFilters;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Very Simple test servlet to test compression filter
* @author Amy Roh
*/
public class CompressionFilterTestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletOutputStream out = response.getOutputStream();
response.setContentType("text/plain");
Enumeration<String> e = request.getHeaders("Accept-Encoding");
while (e.hasMoreElements()) {
String name = e.nextElement();
out.println(name);
if (name.indexOf("gzip") != -1) {
out.println("gzip supported -- able to compress");
} else {
out.println("gzip not supported");
}
}
out.println("Compression Filter Test Servlet");
out.println("Minimum content length for compression is 128 bytes");
out.println("********** 32 bytes **********");
out.println("********** 32 bytes **********");
out.println("********** 32 bytes **********");
out.println("********** 32 bytes **********");
out.close();
}
}

View File

@@ -0,0 +1,448 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package compressionFilters;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
/**
* Implementation of <b>ServletOutputStream</b> that works with
* the CompressionServletResponseWrapper implementation.
*
* @author Amy Roh
* @author Dmitri Valdin
*/
public class CompressionResponseStream extends ServletOutputStream {
// ----------------------------------------------------------- Constructors
/**
* Construct a servlet output stream associated with the specified Response.
*
* @param responseWrapper The associated response wrapper
* @param originalOutput the output stream
*/
public CompressionResponseStream(
CompressionServletResponseWrapper responseWrapper,
ServletOutputStream originalOutput) {
super();
closed = false;
this.response = responseWrapper;
this.output = originalOutput;
}
// ----------------------------------------------------- Instance Variables
/**
* The threshold number which decides to compress or not.
* Users can configure in web.xml to set it to fit their needs.
*/
protected int compressionThreshold = 0;
/**
* The compression buffer size to avoid chunking
*/
protected int compressionBuffer = 0;
/**
* The mime types to compress
*/
protected String[] compressionMimeTypes = {"text/html", "text/xml", "text/plain"};
/**
* Debug level
*/
private int debug = 0;
/**
* The buffer through which all of our output bytes are passed.
*/
protected byte[] buffer = null;
/**
* The number of data bytes currently in the buffer.
*/
protected int bufferCount = 0;
/**
* The underlying gzip output stream to which we should write data.
*/
protected OutputStream gzipstream = null;
/**
* Has this stream been closed?
*/
protected boolean closed = false;
/**
* The response with which this servlet output stream is associated.
*/
protected final CompressionServletResponseWrapper response;
/**
* The underlying servlet output stream to which we should write data.
*/
protected final ServletOutputStream output;
// --------------------------------------------------------- Public Methods
/**
* Set debug level.
*
* @param debug The higher the number, the more detail shown. Currently the
* range 0 (none) to 3 (everything) is used.
*/
public void setDebugLevel(int debug) {
this.debug = debug;
}
/**
* Set the compressionThreshold number and create buffer for this size
*
* @param compressionThreshold Responses above this size in bytes will be
* compressed
*/
protected void setCompressionThreshold(int compressionThreshold) {
this.compressionThreshold = compressionThreshold;
buffer = new byte[this.compressionThreshold];
if (debug > 1) {
System.out.println("compressionThreshold is set to "+ this.compressionThreshold);
}
}
/**
* The compression buffer size to avoid chunking
*
* @param compressionBuffer The compression buffer size in bytes
*/
protected void setCompressionBuffer(int compressionBuffer) {
this.compressionBuffer = compressionBuffer;
if (debug > 1) {
System.out.println("compressionBuffer is set to "+ this.compressionBuffer);
}
}
/**
* Set supported mime types.
*
* @param compressionMimeTypes The mimetypes that will be compressed.
*/
public void setCompressionMimeTypes(String[] compressionMimeTypes) {
this.compressionMimeTypes = compressionMimeTypes;
if (debug > 1) {
System.out.println("compressionMimeTypes is set to " +
Arrays.toString(this.compressionMimeTypes));
}
}
/**
* Close this output stream, causing any buffered data to be flushed and
* any further output data to throw an IOException.
*/
@Override
public void close() throws IOException {
if (debug > 1) {
System.out.println("close() @ CompressionResponseStream");
}
if (closed) {
throw new IOException("This output stream has already been closed");
}
if (gzipstream != null) {
flushToGZip();
gzipstream.close();
gzipstream = null;
} else {
if (bufferCount > 0) {
if (debug > 2) {
System.out.print("output.write(");
System.out.write(buffer, 0, bufferCount);
System.out.println(")");
}
output.write(buffer, 0, bufferCount);
bufferCount = 0;
}
}
output.close();
closed = true;
}
/**
* Flush any buffered data for this output stream, which also causes the
* response to be committed.
*/
@Override
public void flush() throws IOException {
if (debug > 1) {
System.out.println("flush() @ CompressionResponseStream");
}
if (closed) {
throw new IOException("Cannot flush a closed output stream");
}
if (gzipstream != null) {
gzipstream.flush();
}
}
public void flushToGZip() throws IOException {
if (debug > 1) {
System.out.println("flushToGZip() @ CompressionResponseStream");
}
if (bufferCount > 0) {
if (debug > 1) {
System.out.println("flushing out to GZipStream, bufferCount = " + bufferCount);
}
writeToGZip(buffer, 0, bufferCount);
bufferCount = 0;
}
}
/**
* Write the specified byte to our output stream.
*
* @param b The byte to be written
*
* @exception IOException if an input/output error occurs
*/
@Override
public void write(int b) throws IOException {
if (debug > 1) {
System.out.println("write "+b+" in CompressionResponseStream ");
}
if (closed) {
throw new IOException("Cannot write to a closed output stream");
}
if (bufferCount >= buffer.length) {
flushToGZip();
}
buffer[bufferCount++] = (byte) b;
}
/**
* Write <code>b.length</code> bytes from the specified byte array
* to our output stream.
*
* @param b The byte array to be written
*
* @exception IOException if an input/output error occurs
*/
@Override
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
/**
* TODO SERVLET 3.1
*/
@Override
public boolean isReady() {
// TODO Auto-generated method stub
return false;
}
/**
* TODO SERVLET 3.1
*/
@Override
public void setWriteListener(WriteListener listener) {
// TODO Auto-generated method stub
}
/**
* Write <code>len</code> bytes from the specified byte array, starting
* at the specified offset, to our output stream.
*
* @param b The byte array containing the bytes to be written
* @param off Zero-relative starting offset of the bytes to be written
* @param len The number of bytes to be written
*
* @exception IOException if an input/output error occurs
*/
@Override
public void write(byte b[], int off, int len) throws IOException {
if (debug > 1) {
System.out.println("write, bufferCount = " + bufferCount + " len = " + len + " off = " + off);
}
if (debug > 2) {
System.out.print("write(");
System.out.write(b, off, len);
System.out.println(")");
}
if (closed) {
throw new IOException("Cannot write to a closed output stream");
}
if (len == 0) {
return;
}
// Can we write into buffer ?
if (len <= (buffer.length - bufferCount)) {
System.arraycopy(b, off, buffer, bufferCount, len);
bufferCount += len;
return;
}
// There is not enough space in buffer. Flush it ...
flushToGZip();
// ... and try again. Note, that bufferCount = 0 here !
if (len <= (buffer.length - bufferCount)) {
System.arraycopy(b, off, buffer, bufferCount, len);
bufferCount += len;
return;
}
// write direct to gzip
writeToGZip(b, off, len);
}
public void writeToGZip(byte b[], int off, int len) throws IOException {
if (debug > 1) {
System.out.println("writeToGZip, len = " + len);
}
if (debug > 2) {
System.out.print("writeToGZip(");
System.out.write(b, off, len);
System.out.println(")");
}
if (gzipstream == null) {
if (debug > 1) {
System.out.println("new GZIPOutputStream");
}
boolean alreadyCompressed = false;
String contentEncoding = response.getHeader("Content-Encoding");
if (contentEncoding != null) {
if (contentEncoding.contains("gzip")) {
alreadyCompressed = true;
if (debug > 0) {
System.out.println("content is already compressed");
}
} else {
if (debug > 0) {
System.out.println("content is not compressed yet");
}
}
}
boolean compressibleMimeType = false;
// Check for compatible MIME-TYPE
if (compressionMimeTypes != null) {
if (startsWithStringArray(compressionMimeTypes, response.getContentType())) {
compressibleMimeType = true;
if (debug > 0) {
System.out.println("mime type " + response.getContentType() + " is compressible");
}
} else {
if (debug > 0) {
System.out.println("mime type " + response.getContentType() + " is not compressible");
}
}
}
if (response.isCommitted()) {
if (debug > 1) {
System.out.print("Response already committed. Using original output stream");
}
gzipstream = output;
} else if (alreadyCompressed) {
if (debug > 1) {
System.out.print("Response already compressed. Using original output stream");
}
gzipstream = output;
} else if (!compressibleMimeType) {
if (debug > 1) {
System.out.print("Response mime type is not compressible. Using original output stream");
}
gzipstream = output;
} else {
response.addHeader("Content-Encoding", "gzip");
response.setContentLength(-1); // don't use any preset content-length as it will be wrong after gzipping
response.setBufferSize(compressionBuffer);
gzipstream = new GZIPOutputStream(output);
}
}
gzipstream.write(b, off, len);
}
// -------------------------------------------------------- Package Methods
/**
* Has this response stream been closed?
*
* @return <code>true</code> if the stream has been closed, otherwise false.
*/
public boolean closed() {
return closed;
}
/**
* Checks if any entry in the string array starts with the specified value
*
* @param sArray the StringArray
* @param value string
*/
private boolean startsWithStringArray(String sArray[], String value) {
if (value == null) {
return false;
}
for (String s : sArray) {
if (value.startsWith(s)) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,295 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package compressionFilters;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
/**
* Implementation of <b>HttpServletResponseWrapper</b> that works with
* the CompressionServletResponseStream implementation..
*
* @author Amy Roh
* @author Dmitri Valdin
*/
public class CompressionServletResponseWrapper
extends HttpServletResponseWrapper {
// ----------------------------------------------------- Constructor
/**
* Calls the parent constructor which creates a ServletResponse adaptor
* wrapping the given response object.
*
* @param response The response object to be wrapped.
*/
public CompressionServletResponseWrapper(HttpServletResponse response) {
super(response);
origResponse = response;
if (debug > 1) {
System.out.println("CompressionServletResponseWrapper constructor gets called");
}
}
// ----------------------------------------------------- Instance Variables
/**
* Original response
*/
protected final HttpServletResponse origResponse;
/**
* The ServletOutputStream that has been returned by
* <code>getOutputStream()</code>, if any.
*/
protected ServletOutputStream stream = null;
/**
* The PrintWriter that has been returned by
* <code>getWriter()</code>, if any.
*/
protected PrintWriter writer = null;
/**
* The threshold number to compress
*/
protected int compressionThreshold = 0;
/**
* The compression buffer size
*/
protected int compressionBuffer = 8192; // 8KB default
/**
* The mime types to compress
*/
protected String[] compressionMimeTypes = {"text/html", "text/xml", "text/plain"};
/**
* Debug level
*/
protected int debug = 0;
/**
* keeps a copy of all headers set
*/
private final Map<String,String> headerCopies = new HashMap<>();
// --------------------------------------------------------- Public Methods
/**
* Set threshold number.
*
* @param threshold The new compression threshold
*/
public void setCompressionThreshold(int threshold) {
if (debug > 1) {
System.out.println("setCompressionThreshold to " + threshold);
}
this.compressionThreshold = threshold;
}
/**
* Set compression buffer.
*
* @param buffer New size of buffer to use for compressed output
*/
public void setCompressionBuffer(int buffer) {
if (debug > 1) {
System.out.println("setCompressionBuffer to " + buffer);
}
this.compressionBuffer = buffer;
}
/**
* Set compressible mime types.
*
* @param mimeTypes The new list of mime types that will be considered for
* compression
*/
public void setCompressionMimeTypes(String[] mimeTypes) {
if (debug > 1) {
System.out.println("setCompressionMimeTypes to " +
Arrays.toString(mimeTypes));
}
this.compressionMimeTypes = mimeTypes;
}
/**
* Set debug level.
*
* @param debug The new debug level
*/
public void setDebugLevel(int debug) {
this.debug = debug;
}
/**
* Create and return a ServletOutputStream to write the content
* associated with this Response.
*
* @exception IOException if an input/output error occurs
*
* @return A new servlet output stream that compressed any data written to
* it
*/
protected ServletOutputStream createOutputStream() throws IOException {
if (debug > 1) {
System.out.println("createOutputStream gets called");
}
CompressionResponseStream stream = new CompressionResponseStream(
this, origResponse.getOutputStream());
stream.setDebugLevel(debug);
stream.setCompressionThreshold(compressionThreshold);
stream.setCompressionBuffer(compressionBuffer);
stream.setCompressionMimeTypes(compressionMimeTypes);
return stream;
}
/**
* Finish a response.
*/
public void finishResponse() {
try {
if (writer != null) {
writer.close();
} else {
if (stream != null) {
stream.close();
}
}
} catch (IOException e) {
// Ignore
}
}
// ------------------------------------------------ ServletResponse Methods
/**
* Flush the buffer and commit this response.
*
* @exception IOException if an input/output error occurs
*/
@Override
public void flushBuffer() throws IOException {
if (debug > 1) {
System.out.println("flush buffer @ GZipServletResponseWrapper");
}
((CompressionResponseStream)stream).flush();
}
/**
* Return the servlet output stream associated with this Response.
*
* @exception IllegalStateException if <code>getWriter</code> has
* already been called for this response
* @exception IOException if an input/output error occurs
*/
@Override
public ServletOutputStream getOutputStream() throws IOException {
if (writer != null) {
throw new IllegalStateException("getWriter() has already been called for this response");
}
if (stream == null) {
stream = createOutputStream();
}
if (debug > 1) {
System.out.println("stream is set to "+stream+" in getOutputStream");
}
return stream;
}
/**
* Return the writer associated with this Response.
*
* @exception IllegalStateException if <code>getOutputStream</code> has
* already been called for this response
* @exception IOException if an input/output error occurs
*/
@Override
public PrintWriter getWriter() throws IOException {
if (writer != null) {
return writer;
}
if (stream != null) {
throw new IllegalStateException("getOutputStream() has already been called for this response");
}
stream = createOutputStream();
if (debug > 1) {
System.out.println("stream is set to "+stream+" in getWriter");
}
String charEnc = origResponse.getCharacterEncoding();
if (debug > 1) {
System.out.println("character encoding is " + charEnc);
}
writer = new PrintWriter(new OutputStreamWriter(stream, charEnc));
return writer;
}
@Override
public String getHeader(String name) {
return headerCopies.get(name);
}
@Override
public void addHeader(String name, String value) {
if (headerCopies.containsKey(name)) {
String existingValue = headerCopies.get(name);
if ((existingValue != null) && (existingValue.length() > 0)) {
headerCopies.put(name, existingValue + "," + value);
} else {
headerCopies.put(name, value);
}
} else {
headerCopies.put(name, value);
}
super.addHeader(name, value);
}
@Override
public void setHeader(String name, String value) {
headerCopies.put(name, value);
super.setHeader(name, value);
}
}

View File

@@ -0,0 +1,155 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dates;
import java.util.Calendar;
import java.util.Date;
public class JspCalendar {
final Calendar calendar;
public JspCalendar() {
calendar = Calendar.getInstance();
Date trialTime = new Date();
calendar.setTime(trialTime);
}
public int getYear() {
return calendar.get(Calendar.YEAR);
}
public String getMonth() {
int m = getMonthInt();
String[] months = new String [] { "January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December" };
if (m > 12) {
return "Unknown to Man";
}
return months[m - 1];
}
public String getDay() {
int x = getDayOfWeek();
String[] days = new String[] {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
if (x > 7) {
return "Unknown to Man";
}
return days[x - 1];
}
public int getMonthInt() {
return 1 + calendar.get(Calendar.MONTH);
}
public String getDate() {
return getMonthInt() + "/" + getDayOfMonth() + "/" + getYear();
}
public String getTime() {
return getHour() + ":" + getMinute() + ":" + getSecond();
}
public int getDayOfMonth() {
return calendar.get(Calendar.DAY_OF_MONTH);
}
public int getDayOfYear() {
return calendar.get(Calendar.DAY_OF_YEAR);
}
public int getWeekOfYear() {
return calendar.get(Calendar.WEEK_OF_YEAR);
}
public int getWeekOfMonth() {
return calendar.get(Calendar.WEEK_OF_MONTH);
}
public int getDayOfWeek() {
return calendar.get(Calendar.DAY_OF_WEEK);
}
public int getHour() {
return calendar.get(Calendar.HOUR_OF_DAY);
}
public int getMinute() {
return calendar.get(Calendar.MINUTE);
}
public int getSecond() {
return calendar.get(Calendar.SECOND);
}
public static void main(String args[]) {
JspCalendar db = new JspCalendar();
p("date: " + db.getDayOfMonth());
p("year: " + db.getYear());
p("month: " + db.getMonth());
p("time: " + db.getTime());
p("date: " + db.getDate());
p("Day: " + db.getDay());
p("DayOfYear: " + db.getDayOfYear());
p("WeekOfYear: " + db.getWeekOfYear());
p("era: " + db.getEra());
p("ampm: " + db.getAMPM());
p("DST: " + db.getDSTOffset());
p("ZONE Offset: " + db.getZoneOffset());
p("TIMEZONE: " + db.getUSTimeZone());
}
private static void p(String x) {
System.out.println(x);
}
public int getEra() {
return calendar.get(Calendar.ERA);
}
public String getUSTimeZone() {
String[] zones = new String[] {"Hawaii", "Alaskan", "Pacific",
"Mountain", "Central", "Eastern"};
return zones[10 + getZoneOffset()];
}
public int getZoneOffset() {
return calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000);
}
public int getDSTOffset() {
return calendar.get(Calendar.DST_OFFSET)/(60*60*1000);
}
public int getAMPM() {
return calendar.get(Calendar.AM_PM);
}
}

View File

@@ -0,0 +1,30 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package error;
public class Smart {
String name = "JSP";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,74 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package examples;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.Tag;
public abstract class ExampleTagBase extends BodyTagSupport {
private static final long serialVersionUID = 1L;
@Override
public void setParent(Tag parent) {
this.parent = parent;
}
@Override
public void setBodyContent(BodyContent bodyOut) {
this.bodyOut = bodyOut;
}
@Override
public Tag getParent() {
return this.parent;
}
@Override
public int doStartTag() throws JspException {
return SKIP_BODY;
}
@Override
public int doEndTag() throws JspException {
return EVAL_PAGE;
}
@Override
public void doInitBody() throws JspException {
// Default implementations for BodyTag methods as well
// just in case a tag decides to implement BodyTag.
}
@Override
public int doAfterBody() throws JspException {
return SKIP_BODY;
}
@Override
public void release() {
bodyOut = null;
pageContext = null;
parent = null;
}
protected BodyContent bodyOut;
protected Tag parent;
}

View File

@@ -0,0 +1,87 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package examples;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
/**
* Example1: the simplest tag
* Collect attributes and call into some actions
*
* <foo att1="..." att2="...." att3="...." />
*/
public class FooTag extends ExampleTagBase {
private static final long serialVersionUID = 1L;
private final String atts[] = new String[3];
int i = 0;
private void setAtt(int index, String value) {
atts[index] = value;
}
public void setAtt1(String value) {
setAtt(0, value);
}
public void setAtt2(String value) {
setAtt(1, value);
}
public void setAtt3(String value) {
setAtt(2, value);
}
/**
* Process start tag
*
* @return EVAL_BODY_INCLUDE
*/
@Override
public int doStartTag() throws JspException {
i = 0;
return EVAL_BODY_BUFFERED;
}
@Override
public void doInitBody() throws JspException {
pageContext.setAttribute("member", atts[i]);
i++;
}
@Override
public int doAfterBody() throws JspException {
try {
if (i == 3) {
bodyOut.writeOut(bodyOut.getEnclosingWriter());
return SKIP_BODY;
}
pageContext.setAttribute("member", atts[i]);
i++;
return EVAL_BODY_BUFFERED;
} catch (IOException ex) {
throw new JspTagException(ex.toString());
}
}
}

View File

@@ -0,0 +1,36 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package examples;
import javax.servlet.jsp.tagext.TagData;
import javax.servlet.jsp.tagext.TagExtraInfo;
import javax.servlet.jsp.tagext.VariableInfo;
public class FooTagExtraInfo extends TagExtraInfo {
@Override
public VariableInfo[] getVariableInfo(TagData data) {
return new VariableInfo[]
{
new VariableInfo("member",
"String",
true,
VariableInfo.NESTED)
};
}
}

View File

@@ -0,0 +1,63 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package examples;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
/**
* Log the contents of the body. Could be used to handle errors etc.
*/
public class LogTag extends ExampleTagBase {
private static final long serialVersionUID = 1L;
boolean toBrowser = false;
public void setToBrowser(String value) {
if (value == null) {
toBrowser = false;
} else if (value.equalsIgnoreCase("true")) {
toBrowser = true;
} else {
toBrowser = false;
}
}
@Override
public int doStartTag() throws JspException {
return EVAL_BODY_BUFFERED;
}
@Override
public int doAfterBody() throws JspException {
try {
String s = bodyOut.getString();
System.err.println(s);
if (toBrowser) {
bodyOut.writeOut(bodyOut.getEnclosingWriter());
}
return SKIP_BODY;
} catch (IOException ex) {
throw new JspTagException(ex.toString());
}
}
}

View File

@@ -0,0 +1,79 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package examples;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
/**
* Accept and display a value.
*/
public class ValuesTag extends TagSupport {
private static final long serialVersionUID = 1L;
// Using "-1" as the default value,
// in the assumption that it won't be used as the value.
// Cannot use null here, because null is an important case
// that should be present in the tests.
private Object objectValue = "-1";
private String stringValue = "-1";
private long longValue = -1;
private double doubleValue = -1;
public void setObject(Object objectValue) {
this.objectValue = objectValue;
}
public void setString(String stringValue) {
this.stringValue = stringValue;
}
public void setLong(long longValue) {
this.longValue = longValue;
}
public void setDouble(double doubleValue) {
this.doubleValue = doubleValue;
}
@Override
public int doEndTag() throws JspException {
JspWriter out = pageContext.getOut();
try {
if (!"-1".equals(objectValue)) {
out.print(objectValue);
} else if (!"-1".equals(stringValue)) {
out.print(stringValue);
} else if (longValue != -1) {
out.print(longValue);
} else if (doubleValue != -1) {
out.print(doubleValue);
} else {
out.print("-1");
}
} catch (IOException ex) {
throw new JspTagException("IOException: " + ex.toString(), ex);
}
return super.doEndTag();
}
}

View File

@@ -0,0 +1,99 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package filters;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.GenericFilter;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* Example filter that can be attached to either an individual servlet
* or to a URL pattern. This filter performs the following functions:
* <ul>
* <li>Attaches itself as a request attribute, under the attribute name
* defined by the value of the <code>attribute</code> initialization
* parameter.</li>
* <li>Calculates the number of milliseconds required to perform the
* servlet processing required by this request, including any
* subsequently defined filters, and logs the result to the servlet
* context log for this application.
* </ul>
*
* @author Craig McClanahan
*/
public final class ExampleFilter extends GenericFilter {
private static final long serialVersionUID = 1L;
/**
* The request attribute name under which we store a reference to ourself.
*/
private String attribute = null;
/**
* Time the processing that is performed by all subsequent filters in the
* current filter stack, including the ultimately invoked servlet.
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param chain The filter chain we are processing
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// Store ourselves as a request attribute (if requested)
if (attribute != null) {
request.setAttribute(attribute, this);
}
// Time and log the subsequent processing
long startTime = System.currentTimeMillis();
chain.doFilter(request, response);
long stopTime = System.currentTimeMillis();
getServletContext().log(this.toString() + ": " + (stopTime - startTime) +
" milliseconds");
}
@Override
public void init() throws ServletException {
this.attribute = getInitParameter("attribute");
}
/**
* Return a String representation of this object.
*/
@Override
public String toString() {
return "ExampleFilter(" + getFilterConfig() + ")";
}
}

View File

@@ -0,0 +1,59 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package http2;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.PushBuilder;
public class SimpleImagePush extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html");
PrintWriter pw = resp.getWriter();
PushBuilder pb = req.newPushBuilder();
if (pb != null) {
pb.path("servlets/images/code.gif");
pb.push();
pw.println("<html>");
pw.println("<body>");
pw.println("<p>The following image was provided via a push request.</p>");
pw.println("<img src=\"" + req.getContextPath() + "/servlets/images/code.gif\"/>");
pw.println("</body>");
pw.println("</html>");
pw.flush();
} else {
pw.println("<html>");
pw.println("<body>");
pw.println("<p>Server push requests are not supported by this protocol.</p>");
pw.println("</body>");
pw.println("</html>");
}
}
}

View File

@@ -0,0 +1,42 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jsp2.examples;
public class BookBean {
private final String title;
private final String author;
private final String isbn;
public BookBean( String title, String author, String isbn ) {
this.title = title;
this.author = author;
this.isbn = isbn;
}
public String getTitle() {
return this.title;
}
public String getAuthor() {
return this.author;
}
public String getIsbn() {
return this.isbn;
}
}

View File

@@ -0,0 +1,34 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jsp2.examples;
public class FooBean {
private String bar;
public FooBean() {
bar = "Initial value";
}
public String getBar() {
return this.bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}

View File

@@ -0,0 +1,50 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jsp2.examples;
/**
* Accept and display a value.
*/
public class ValuesBean {
private String string;
private double doubleValue;
private long longValue;
public String getStringValue() {
return this.string;
}
public void setStringValue(String string) {
this.string = string;
}
public double getDoubleValue() {
return doubleValue;
}
public void setDoubleValue(double doubleValue) {
this.doubleValue = doubleValue;
}
public long getLongValue() {
return longValue;
}
public void setLongValue(long longValue) {
this.longValue = longValue;
}
}

View File

@@ -0,0 +1,45 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jsp2.examples.el;
import java.util.Locale;
/**
* Defines the functions for the jsp2 example tag library.
*
* <p>Each function is defined as a static method.</p>
*/
public class Functions {
public static String reverse( String text ) {
return new StringBuilder( text ).reverse().toString();
}
public static int numVowels( String text ) {
String vowels = "aeiouAEIOU";
int result = 0;
for( int i = 0; i < text.length(); i++ ) {
if( vowels.indexOf( text.charAt( i ) ) != -1 ) {
result++;
}
}
return result;
}
public static String caps( String text ) {
return text.toUpperCase(Locale.ENGLISH);
}
}

View File

@@ -0,0 +1,56 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jsp2.examples.simpletag;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.DynamicAttributes;
import javax.servlet.jsp.tagext.SimpleTagSupport;
/**
* SimpleTag handler that echoes all its attributes
*/
public class EchoAttributesTag
extends SimpleTagSupport
implements DynamicAttributes
{
private final List<String> keys = new ArrayList<>();
private final List<Object> values = new ArrayList<>();
@Override
public void doTag() throws JspException, IOException {
JspWriter out = getJspContext().getOut();
for( int i = 0; i < keys.size(); i++ ) {
String key = keys.get( i );
Object value = values.get( i );
out.println( "<li>" + key + " = " + value + "</li>" );
}
}
@Override
public void setDynamicAttribute( String uri, String localName,
Object value )
throws JspException
{
keys.add( localName );
values.add( value );
}
}

View File

@@ -0,0 +1,44 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jsp2.examples.simpletag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import jsp2.examples.BookBean;
/**
* SimpleTag handler that pretends to search for a book, and stores
* the result in a scoped variable.
*/
public class FindBookSimpleTag extends SimpleTagSupport {
private String var;
private static final String BOOK_TITLE = "The Lord of the Rings";
private static final String BOOK_AUTHOR = "J. R. R. Tolkien";
private static final String BOOK_ISBN = "0618002251";
@Override
public void doTag() throws JspException {
BookBean book = new BookBean( BOOK_TITLE, BOOK_AUTHOR, BOOK_ISBN );
getJspContext().setAttribute( this.var, book );
}
public void setVar( String var ) {
this.var = var;
}
}

View File

@@ -0,0 +1,32 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jsp2.examples.simpletag;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
/**
* SimpleTag handler that prints "Hello, world!"
*/
public class HelloWorldSimpleTag extends SimpleTagSupport {
@Override
public void doTag() throws JspException, IOException {
getJspContext().getOut().write( "Hello, world!" );
}
}

View File

@@ -0,0 +1,42 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jsp2.examples.simpletag;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
/**
* SimpleTag handler that accepts a num attribute and
* invokes its body 'num' times.
*/
public class RepeatSimpleTag extends SimpleTagSupport {
private int num;
@Override
public void doTag() throws JspException, IOException {
for (int i=0; i<num; i++) {
getJspContext().setAttribute("count", String.valueOf( i + 1 ) );
getJspBody().invoke(null);
}
}
public void setNum(int num) {
this.num = num;
}
}

View File

@@ -0,0 +1,85 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jsp2.examples.simpletag;
import java.io.IOException;
import java.util.Random;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
/**
* SimpleTag handler that accepts takes three attributes of type
* JspFragment and invokes then in a random order.
*/
public class ShuffleSimpleTag extends SimpleTagSupport {
// No need for this to use SecureRandom
private static final Random random = new Random();
private JspFragment fragment1;
private JspFragment fragment2;
private JspFragment fragment3;
@Override
public void doTag() throws JspException, IOException {
switch(random.nextInt(6)) {
case 0:
fragment1.invoke( null );
fragment2.invoke( null );
fragment3.invoke( null );
break;
case 1:
fragment1.invoke( null );
fragment3.invoke( null );
fragment2.invoke( null );
break;
case 2:
fragment2.invoke( null );
fragment1.invoke( null );
fragment3.invoke( null );
break;
case 3:
fragment2.invoke( null );
fragment3.invoke( null );
fragment1.invoke( null );
break;
case 4:
fragment3.invoke( null );
fragment1.invoke( null );
fragment2.invoke( null );
break;
case 5:
fragment3.invoke( null );
fragment2.invoke( null );
fragment1.invoke( null );
break;
}
}
public void setFragment1( JspFragment fragment1 ) {
this.fragment1 = fragment1;
}
public void setFragment2( JspFragment fragment2 ) {
this.fragment2 = fragment2;
}
public void setFragment3( JspFragment fragment3 ) {
this.fragment3 = fragment3;
}
}

Some files were not shown because too many files have changed in this diff Show More