如何从 Servlet Filter 渲染 Thymeleaf 模板?

问题描述 投票:0回答:1

我知道,在 JSP 期间,这只是

request.getRequestDispatcher("path..").forward(request, response);

但是:

  1. 如果我只提供 root / 路径,它会寻址映射到 / 的 servlet。所以,不会发生模板渲染;

  2. 在这种情况下,图像和样式等(静态内容)被破坏..未加载..我相信,这种情况发生了,因为 Thymeleaf 不仅仅是一个页面,而且正在渲染。

如何通过

/resources/templates
或任何其他方式渲染 Thymeleaf 模板(该模板位于 Servlet Filter 中的
request.getRequestDispatcher("template.html").forward(request, response);
中)有任何帮助吗?

java spring servlets filter thymeleaf
1个回答
0
投票

解决方案是获取 Spring MVC ViewResolver 并使用 resolveViewName 方法向其请求视图。一旦视图被解析,就可以在请求上调用 render 方法并使用模型图进行响应。

下面的示例系统地呈现了 accessMeFromFilter 视图。

...
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;    
...
public class MyFilter extends GenericFilterBean {

    /** The view resolver */
    private ViewResolver viewResolver;

    /** @param viewResolver The view resolver */
    @Autowired
    public void setViewResolver(ViewResolver viewResolver) {
        this.viewResolver = viewResolver;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        if (request instanceof HttpServletRequest httpRequest
            && response instanceof HttpServletResponse httpResponse) {

            // Get the Thymeleaf view name
            String viewName = "accessMeFromFilter";

            try {

                // Use the viewResolver to find the view for the default locale
                View resolvedView = viewResolver.resolveViewName(viewName, Locale.getDefault());

                // Instantiate the model map
                Map<String, Object> model = new HashMap<>();

                // Here we can add a value in the model that can be used in the Thymeleaf template
                model.put("value", "1234");

                // Renders the view on the request/responses using the model map.
                resolvedView.render(model, httpRequest, httpResponse);

                // The request has been processed, so return
                return;

            } catch (Exception e) {
                LOG.error("Unable to resolve view " + viewName, e);
                throw new ServletException("Unable to resolve view", e);
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.