This is an automated email from the ASF dual-hosted git repository.

schultz pushed a commit to branch 9.0.x
in repository https://gitbox.apache.org/repos/asf/tomcat.git


The following commit(s) were added to refs/heads/9.0.x by this push:
     new 2b6287521b Add support for JSON responses to request header example.
2b6287521b is described below

commit 2b6287521bac2eab66a0b21bf0250a3d8facb407
Author: Christopher Schultz <ch...@christopherschultz.net>
AuthorDate: Mon Feb 12 15:18:22 2024 -0500

    Add support for JSON responses to request header example.
---
 webapps/docs/changelog.xml                         |  8 +++
 .../WEB-INF/classes/RequestHeaderExample.java      | 77 +++++++++++++++++++++-
 2 files changed, 84 insertions(+), 1 deletion(-)

diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index bd7d48f99a..0aa6868e70 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -197,6 +197,14 @@
       </fix>
     </changelog>
   </subsection>
+  <subsection name="Web applications">
+    <changelog>
+      <add>
+        Add support for responses in JSON format from the examples application
+        RequestHeaderExample. (schultz)
+      </add>
+    </changelog>
+  </subsection>
   <subsection name="Other">
     <changelog>
       <update>
diff --git a/webapps/examples/WEB-INF/classes/RequestHeaderExample.java 
b/webapps/examples/WEB-INF/classes/RequestHeaderExample.java
index a80076c697..0cff06402f 100644
--- a/webapps/examples/WEB-INF/classes/RequestHeaderExample.java
+++ b/webapps/examples/WEB-INF/classes/RequestHeaderExample.java
@@ -27,6 +27,8 @@ import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 
+import org.apache.tomcat.util.json.JSONFilter;
+
 import util.CookieFilter;
 import util.HTMLFilter;
 
@@ -35,7 +37,6 @@ import util.HTMLFilter;
  *
  * @author James Duncan Davidson &lt;dun...@eng.sun.com>
  */
-
 public class RequestHeaderExample extends HttpServlet {
 
     private static final long serialVersionUID = 1L;
@@ -44,6 +45,51 @@ public class RequestHeaderExample extends HttpServlet {
     public void doGet(HttpServletRequest request,
                       HttpServletResponse response)
         throws IOException, ServletException
+    {
+        if (prefersJSON(request.getHeader("Accept"))) {
+            renderJSON(request, response);
+        } else {
+            renderHTML(request, response);
+        }
+    }
+
+    /**
+     * Returns true if the client appears to prefer a JSON response,
+     * false otherwise.
+     *
+     * Note that this method is not very pedantic and uses only a very lazy
+     * algorithm for checking whether JSON is "preferred".
+     *
+     * @param acceptHeader The value of the HTTP "Accept" header from the 
client.
+     *
+     * @return true if the client appears to prefer a JSON response,
+     *              false otherwise.
+     */
+    protected boolean prefersJSON(String acceptHeader) {
+        if (null == acceptHeader) {
+            return false;
+        }
+        // mime/type, mime/type;q=n, ...
+
+        // Don't bother with the q-factor.
+        // This is not expected to be 100% accurate or spec-compliant
+        String[] accepts = acceptHeader.split(",");
+        for (String accept : accepts) {
+            if (accept.contains("application/json")) {
+                return true;
+            }
+
+            // text/html, application/html, etc.
+            if (accept.contains("html")) {
+                return false;
+            }
+        }
+        return false;
+    }
+
+    protected void renderHTML(HttpServletRequest request,
+                              HttpServletResponse response)
+        throws IOException, ServletException
     {
         ResourceBundle rb = 
ResourceBundle.getBundle("LocalStrings",request.getLocale());
 
@@ -97,6 +143,35 @@ public class RequestHeaderExample extends HttpServlet {
         out.println("</table>");
     }
 
+    protected void renderJSON(HttpServletRequest request, HttpServletResponse 
response)
+        throws IOException, ServletException
+    {
+        response.setContentType("application/json");
+        response.setCharacterEncoding("UTF-8");
+
+        PrintWriter out = response.getWriter();
+
+        out.append('[');
+        Enumeration<String> e = request.getHeaderNames();
+        while (e.hasMoreElements()) {
+            String headerName = e.nextElement();
+            String headerValue = request.getHeader(headerName);
+
+            out.append("{\"")
+            .append(JSONFilter.escape(headerName))
+            .append("\":\"")
+            .append(JSONFilter.escape(headerValue))
+            .append("\"}")
+            ;
+
+            if(e.hasMoreElements()) {
+                out.append(',');
+            }
+        }
+
+        out.print("]");
+    }
+
     @Override
     public void doPost(HttpServletRequest request,
                       HttpServletResponse response)


---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org
For additional commands, e-mail: dev-h...@tomcat.apache.org

Reply via email to