Chris,

Please compare the iteration logic in renderHTML vs renderJSON.

Your code misses the changes added by
https://github.com/apache/tomcat/commit/c88e75305e198f500ffd626a5b1275dc3ad46553


пн, 12 февр. 2024 г. в 23:19, <schu...@apache.org>:
>
> This is an automated email from the ASF dual-hosted git repository.
>
> schultz pushed a commit to branch main
> in repository https://gitbox.apache.org/repos/asf/tomcat.git
>
>
> The following commit(s) were added to refs/heads/main by this push:
>      new 861b593d7b Add support for JSON responses to request header example.
> 861b593d7b is described below
>
> commit 861b593d7b2a236fbdf9c8a9fe6ef1c8edc39a38
> 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 1d8f6317a8..e4ddfbd30c 100644
> --- a/webapps/docs/changelog.xml
> +++ b/webapps/docs/changelog.xml
> @@ -206,6 +206,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>
>        <fix>
> diff --git a/webapps/examples/WEB-INF/classes/RequestHeaderExample.java 
> b/webapps/examples/WEB-INF/classes/RequestHeaderExample.java
> index 180525dd14..451a7a1ad1 100644
> --- a/webapps/examples/WEB-INF/classes/RequestHeaderExample.java
> +++ b/webapps/examples/WEB-INF/classes/RequestHeaderExample.java
> @@ -27,6 +27,8 @@ import jakarta.servlet.http.HttpServletRequest;
>  import jakarta.servlet.http.HttpServletResponse;
>  import jakarta.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
>

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

Reply via email to