freemarkerservlet.java

来自「freemaker安装软件」· Java 代码 · 共 770 行 · 第 1/3 页

JAVA
770
字号
                }
            }

            // Process all other init-params:
            Enumeration initpnames = getServletConfig().getInitParameterNames();
            while (initpnames.hasMoreElements()) {
                String name = (String) initpnames.nextElement();
                String value = getInitParameter(name);
                
                if (name == null) {
                    throw new ServletException(
                            "init-param without param-name. "
                            + "Maybe the web.xml is not well-formed?");
                }
                if (value == null) {
                    throw new ServletException(
                            "init-param without param-value. "
                            + "Maybe the web.xml is not well-formed?");
                }
                
                if (name.equals(DEPR_INITPARAM_OBJECT_WRAPPER)
                        || name.equals(Configurable.OBJECT_WRAPPER_KEY)
                        || name.equals(INITPARAM_TEMPLATE_PATH)) {
                    // ignore: we have already processed these
                } else if (name.equals(DEPR_INITPARAM_ENCODING)) { // BC
                    if (getInitParameter(Configuration.DEFAULT_ENCODING_KEY) != null) {
                        throw new ServletException(
                                "Conflicting init-params: "
                                + Configuration.DEFAULT_ENCODING_KEY + " and "
                                + DEPR_INITPARAM_ENCODING);
                    }
                    config.setDefaultEncoding(value);
                } else if (name.equals(DEPR_INITPARAM_TEMPLATE_DELAY)) { // BC
                    if (getInitParameter(Configuration.TEMPLATE_UPDATE_DELAY_KEY) != null) {
                        throw new ServletException(
                                "Conflicting init-params: "
                                + Configuration.TEMPLATE_UPDATE_DELAY_KEY + " and "
                                + DEPR_INITPARAM_TEMPLATE_DELAY);
                    }
                    try {
                        config.setTemplateUpdateDelay(Integer.parseInt(value));
                    } catch (NumberFormatException e) {
                        // Intentionally ignored
                    }
                } else if (name.equals(DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER)) { // BC
                    if (getInitParameter(Configurable.TEMPLATE_EXCEPTION_HANDLER_KEY) != null) {
                        throw new ServletException(
                                "Conflicting init-params: "
                                + Configurable.TEMPLATE_EXCEPTION_HANDLER_KEY + " and "
                                + DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER);
                    }

                    if (DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER_RETHROW.equals(value)) {
                        config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
                    } else if (DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER_DEBUG.equals(value)) {
                        config.setTemplateExceptionHandler(TemplateExceptionHandler.DEBUG_HANDLER);
                    } else if  (DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER_HTML_DEBUG.equals(value)) {
                        config.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
                    } else if  (DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER_IGNORE.equals(value)) {
                        config.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
                    } else {
                        throw new ServletException(
                                "Invalid value for servlet init-param "
                                + DEPR_INITPARAM_TEMPLATE_EXCEPTION_HANDLER + ": " + value);
                    }
                } else if (name.equals(INITPARAM_NOCACHE)) {
                    nocache = StringUtil.getYesNo(value);
                } else if (name.equals(DEPR_INITPARAM_DEBUG)) { // BC
                    if (getInitParameter(INITPARAM_DEBUG) != null) {
                        throw new ServletException(
                                "Conflicting init-params: "
                                + INITPARAM_DEBUG + " and "
                                + DEPR_INITPARAM_DEBUG);
                    }
                    debug = StringUtil.getYesNo(value);
                } else if (name.equals(INITPARAM_DEBUG)) {
                    debug = StringUtil.getYesNo(value);
                } else if (name.equals(INITPARAM_CONTENT_TYPE)) {
                    contentType = value;
                } else {
                    config.setSetting(name, value);
                }
            } // while initpnames
            
            noCharsetInContentType = true;
            int i = contentType.toLowerCase().indexOf("charset=");
            if (i != -1) {
                char c = ' ';
                i--;
                while (i >= 0) {
                    c = contentType.charAt(i);
                    if (!Character.isWhitespace(c)) break;
                    i--;
                }
                if (i == -1 || c == ';') {
                    noCharsetInContentType = false;
                }
            }
        } catch (ServletException e) {
            throw e;
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        process(request, response);
    }

    public void doPost(
        HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException
    {
        process(request, response);
    }

    private void process(
        HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException
    {
        // Give chance to subclasses to perform preprocessing
        if (preprocessRequest(request, response)) {
            return;
        }

        String path = requestUrlToTemplatePath(request);

        if (debug) {
            log("Requested template: " + path);
        }

        Template template = null;
        try {
            template = config.getTemplate(
                    path,
                    deduceLocale(path, request, response));
        } catch (FileNotFoundException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        
        Object attrContentType = template.getCustomAttribute("content_type");
        if(attrContentType != null) {
            response.setContentType(attrContentType.toString());
        }
        else {
            if (noCharsetInContentType) {
                response.setContentType(
                        contentType + "; charset=" + template.getEncoding());
            } else {
                response.setContentType(contentType);
            }
        }

        // Set cache policy
        setBrowserCachingPolicy(response);

        ServletContext servletContext = getServletContext();
        try {
            TemplateModel model = createModel(wrapper, servletContext, request, response);

            // Give subclasses a chance to hook into preprocessing
            if (preTemplateProcess(request, response, template, model)) {
                try {
                    // Process the template
                    template.process(model, response.getWriter());
                } finally {
                    // Give subclasses a chance to hook into postprocessing
                    postTemplateProcess(request, response, template, model);
                }
            }
        } catch (TemplateException te) {
            if (config.getTemplateExceptionHandler()
                        .getClass().getName().indexOf("Debug") != -1) {
                this.log("Error executing FreeMarker template", te);
            } else {
                ServletException e = new ServletException(
                        "Error executing FreeMarker template", te);
                // Attempt to set init cause, but don't freak out if the method
                // is not available (i.e. pre-1.4 JRE). This is required as the
                // constructor-passed throwable won't show up automatically in
                // stack traces.
                try {
                    e.getClass().getMethod("initCause",
                            new Class[] { Throwable.class }).invoke(e,
                            new Object[] { te });
                } catch (Exception ex) {
                    // Can't set init cause, we're probably running on a pre-1.4
                    // JDK, oh well...
                }
                throw e;
            }
        }
    }
    
    /**
     * Returns the locale used for the 
     * {@link Configuration#getTemplate(String, Locale)} call.
     * The base implementation simply returns the locale setting of the
     * configuration. Override this method to provide different behaviour, i.e.
     * to use the locale indicated in the request.
     */
    protected Locale deduceLocale(
            String templatePath, HttpServletRequest request, HttpServletResponse response) {
        return config.getLocale();
    }

    protected TemplateModel createModel(ObjectWrapper wrapper,
                                        ServletContext servletContext,
                                        HttpServletRequest request,
                                        HttpServletResponse response) throws TemplateModelException {
        try {
            AllHttpScopesHashModel params = new AllHttpScopesHashModel(wrapper, servletContext, request);
    
            // Create hash model wrapper for servlet context (the application)
            ServletContextHashModel servletContextModel =
                (ServletContextHashModel) servletContext.getAttribute(
                    ATTR_APPLICATION_MODEL);
            if (servletContextModel == null)
            {
                servletContextModel = new ServletContextHashModel(this, wrapper);
                servletContext.setAttribute(
                    ATTR_APPLICATION_MODEL,
                    servletContextModel);
                TaglibFactory taglibs = new TaglibFactory(servletContext);
                servletContext.setAttribute(
                    ATTR_JSP_TAGLIBS_MODEL,
                    taglibs);
                initializeServletContext(request, response);
            }
            params.putUnlistedModel(KEY_APPLICATION, servletContextModel);
            params.putUnlistedModel(KEY_APPLICATION_PRIVATE, servletContextModel);
            params.putUnlistedModel(KEY_JSP_TAGLIBS, (TemplateModel)servletContext.getAttribute(ATTR_JSP_TAGLIBS_MODEL));
            // Create hash model wrapper for session
            HttpSessionHashModel sessionModel;
            HttpSession session = request.getSession(false);
            if(session != null) {
                sessionModel = (HttpSessionHashModel) session.getAttribute(ATTR_SESSION_MODEL);
                if (sessionModel == null || sessionModel.isZombie()) {
                    sessionModel = new HttpSessionHashModel(session, wrapper);
                    session.setAttribute(ATTR_SESSION_MODEL, sessionModel);
                    if(!sessionModel.isZombie()) {
                        initializeSession(request, response);
                    }
                }
            }
            else {
                sessionModel = new HttpSessionHashModel(this, request, response, wrapper);
            }
            params.putUnlistedModel(KEY_SESSION, sessionModel);
    
            // Create hash model wrapper for request
            HttpRequestHashModel requestModel =

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?