servlet过滤器在Java中根本没有应用?

时间:2014-06-17 21:28:41

标签: java jsp servlets web.xml servlet-filters

我是使用Java Servlets的初学者。我的servlet存在一些问题。 我的过滤器未被应用。我在过滤器中有一些打印语句,但我从未在控制台上看到任何打印,表明过滤器未应用。而且,我的过滤器应该将生成的xml转换为Json或HTML。但它只返回xml本身。

这是我的web.xml:

<web-app>
        <display-name>CP130 Assignment 8</display-name>
        <servlet>
            <description>Servlet obtaining stock quote from Yahoo Financial Services</description>
            <display-name>CP130QuoteServlet</display-name>
            <servlet-name>StockQuoteJsp</servlet-name>
            <jsp-file>/Quote.jsp</jsp-file>
        </servlet>
        <servlet-mapping>
            <servlet-name>StockQuoteJsp</servlet-name>
            <servlet-class>edu.uw.rgm.web.YahooStockQuoteServlet</servlet-class>
            <url-pattern>/Quote.jsp</url-pattern>
        </servlet-mapping>
        <filter>
            <description>Filter using XSLT to format servlet response</description>
            <display-name>CP130QuoteTransformFilter</display-name>
            <filter-name>QuoteResponseFormatter</filter-name>
            <filter-class>edu.uw.rgm.web.QuoteTransformFilter</filter-class>
            <init-param>
                <description>HTML transform</description>
                <param-name>html-transform</param-name>
                <param-value>xslt/quote2html.xslt</param-value>
            </init-param>
            <init-param>
                <description>JSON transform</description>
                <param-name>json-transform</param-name>
                <param-value>xslt/quote2json.xslt</param-value>
            </init-param>
            <init-param>
                <description>Plain transform</description>
                <param-name>plain-transform</param-name>
                <param-value>xslt/quote2plain.xslt</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>QuoteResponseFormatter</filter-name>
            <servlet-name>StockQuoteJsp</servlet-name>
        </filter-mapping>
        <filter-mapping>
            <filter-name>QuoteResponseFormatter</filter-name>
            <url-pattern>/Quote.jsp</url-pattern>
        </filter-mapping>
        <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
    </web-app>

我在web.xml中检查了拼写错误 为什么我的过滤器没有应用?我还注意到web.xml中元素的顺序很重要。如果我将地点filters更改为servlet以上,则会收到错误。

修改

过滤器:

public class QuoteTransformFilter implements Filter {
    private FilterConfig cfg;
    private String htmlStylePath;
    private String jsonStylePath;
    private String plainStylePath;

    /**
     * @see Filter#init(FilterConfig)
     */
    @Override
    public void init(final FilterConfig fConfig) throws ServletException {
        cfg = fConfig;
        String styleSheet = cfg.getInitParameter("html-transform");
        htmlStylePath = cfg.getServletContext().getRealPath(styleSheet);
        styleSheet = cfg.getInitParameter("json-transform");
        jsonStylePath = cfg.getServletContext().getRealPath(styleSheet);
        styleSheet = cfg.getInitParameter("plain-transform");
        plainStylePath = cfg.getServletContext().getRealPath(styleSheet);

        cfg.getServletContext().log(htmlStylePath);
        cfg.getServletContext().log(jsonStylePath);
        cfg.getServletContext().log(plainStylePath);
    }

    /**
     * @see Filter#destroy()
     */
    @Override
    public void destroy() {
        // no-op
    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
        ServletRequest requestWrapper = request;
        // Illustrate the use of a request wrapper, and the use of a request document
        if ("application/json".equals(request.getContentType()) && request instanceof HttpServletRequest) {
            final ObjectMapper mapper = new ObjectMapper();
            Properties props = mapper.readValue(request.getReader(), Properties.class);
            requestWrapper = new PropertyRequestWrapper((HttpServletRequest)request, props);
        }

        final CharResponseWrapper responseWrapper = new CharResponseWrapper((HttpServletResponse)response);

        String rsType = requestWrapper.getParameter("rstype");
        if (rsType == null) {
            rsType = "html";
        }

        cfg.getServletContext().log("rsType = '" + rsType +"'");

        // pass the request along the filter chain
        chain.doFilter(requestWrapper, responseWrapper);
        final String xml = responseWrapper.toString();
        System.out.println("printing rstype = "+rsType);

        Source styleSource = null;
        String responseStr = xml;
        if (!rsType.equals("xml")) {
            // Select the appropriate sytle sheet
            if (rsType.equals("plain")) {
                System.out.println("plain");
                response.setContentType("text/plain");
                styleSource = new StreamSource(plainStylePath);
            } else if (rsType.equals("json")) {
                response.setContentType("application/json");
                styleSource = new StreamSource(jsonStylePath);
            } else {
                response.setContentType("text/html");
                styleSource = new StreamSource(htmlStylePath);
            }

            // Process the XML document using the stylesheet
            final StringReader sr = new StringReader(xml);
            final Source xmlSource = new StreamSource(sr);

            try {
                final TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer;
                transformer = transformerFactory.newTransformer(styleSource);
                final CharArrayWriter caw = new CharArrayWriter();
                final StreamResult result  = new StreamResult(caw);
                cfg.getServletContext().log("Transforming...");
                transformer.transform(xmlSource, result);
                responseStr = caw.toString();

            } catch(final TransformerConfigurationException ex) {
                cfg.getServletContext().log("Config error", ex);
                return;
            } catch (final TransformerException e) {
                cfg.getServletContext().log("Transform error", e);
                return;
            }
        }
        System.out.println(responseStr);
        response.setContentLength(responseStr.length());
        final PrintWriter out = response.getWriter();
        out.write(responseStr);
        out.close();

    }

}

我为GET请求尝试的网址是:

http://localhost:8080/StockQuote/Quote.jsp?symbol=GOOG&rstype=plain

1 个答案:

答案 0 :(得分:0)

我在你的web.xml中发现了很多错误。我不知道为什么它没有抛出一个解析异常。可能是它,你没有看到它。

  1. servlet-class中的servlet-mapping元素必须位于servlet内。
  2. 您可以jsp-fileservlet-class而不是两者。
  3. 应在Servlets
  4. 之前定义过滤器
  5. 最好在**结束时使用url-pattern与查询字符串关联

    <web-app>
        <display-name>CP130 Assignment 8</display-name>
        <filter>
            <description>Filter using XSLT to format servlet response</description>
            <display-name>CP130QuoteTransformFilter</display-name>
            <filter-name>QuoteResponseFormatter</filter-name>
            <filter-class>edu.uw.rgm.web.QuoteTransformFilter</filter-class>
            <init-param>
                <description>HTML transform</description>
                <param-name>html-transform</param-name>
                <param-value>xslt/quote2html.xslt</param-value>
            </init-param>
            <init-param>
                <description>JSON transform</description>
                <param-name>json-transform</param-name>
                <param-value>xslt/quote2json.xslt</param-value>
            </init-param>
            <init-param>
                <description>Plain transform</description>
                <param-name>plain-transform</param-name>
                <param-value>xslt/quote2plain.xslt</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>QuoteResponseFormatter</filter-name>
            <servlet-name>StockQuoteJsp</servlet-name>
        </filter-mapping>
        <filter-mapping>
            <filter-name>QuoteResponseFormatter</filter-name>
            <url-pattern>/Quote.jsp**</url-pattern>
        </filter-mapping>
        <servlet>
            <description>Servlet obtaining stock quote from Yahoo Financial Services</description>
            <display-name>CP130QuoteServlet</display-name>
            <servlet-name>StockQuoteJsp</servlet-name>
            <servlet-class>edu.uw.rgm.web.YahooStockQuoteServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>StockQuoteJsp</servlet-name>            
            <url-pattern>/Quote.jsp**</url-pattern>
        </servlet-mapping>
        <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
    </web-app>