2015-01-07 17 views
1

저는 thymeleaf 템플릿 엔진을 사용하여 스프링 메일을 구성하려고하는데, 왜 그런 일이 발생하는지 알 수없는 오류가 있습니다. 나는이 문제에 대해 다양한 주제를 보았지만 문제를 해결하기위한 모든 제안은 내 프로젝트에서 옳은 것처럼 보인다.Thymeleaf Spring 메일 컨텍스트 오류

문제는 ServletContextTemplateResolver로 해결하려는 Context 문제입니다.

내 구성은 다음과 같습니다

@Transactional(readOnly = true) 
public void sendContactEmail (final String recipientName, final String recipientEmail, final String imageResourceName, final byte[] imageBytes, final String imageContentType, final Locale locale) throws MessagingException 
{ 
    // Prepare the evaluation context 
    final Context ctx = new Context(locale); 
    ctx.setVariable("name", recipientName); 
    ctx.setVariable("subscriptionDate", new Date()); 
    ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music")); 
    ctx.setVariable("imageResourceName", imageResourceName); // so that we can reference it from HTML 

    // Prepare message using a Spring helper 
    final MimeMessage mimeMessage = this.mailSender.createMimeMessage(); 
    final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart 
    message.setSubject("Example HTML email with inline image"); 
    message.setFrom("[email protected]"); 
    message.setTo(recipientEmail); 

    // Create the HTML body using Thymeleaf 
    final String htmlContent = this.templateEngine.process("contact.html", ctx); 
    message.setText(htmlContent, true); // true = isHtml 

    // Add the inline image, referenced from the HTML code as "cid:${imageResourceName}" 
    final InputStreamSource imageSource = new ByteArrayResource(imageBytes); 
    message.addInline(imageResourceName, imageSource, imageContentType); 

    // Send mail 
    this.mailSender.send(mimeMessage); 
} 

그리고 마지막으로 오류 :

@Bean 
public TemplateResolver webTemplateResolver() { 
    final TemplateResolver templateResolver = new ServletContextTemplateResolver(); 
    templateResolver.setPrefix("/WEB-INF/views/"); 
    templateResolver.setSuffix(".html"); 
    templateResolver.setTemplateMode("HTML5"); 
    templateResolver.setOrder(2); 
    return templateResolver; 
} 

@Bean 
public TemplateResolver emailTemplateResolver() { 
    TemplateResolver templateResolver = new ClassLoaderTemplateResolver(); 
    templateResolver.setPrefix("mail/"); 
    templateResolver.setSuffix(".html"); 
    templateResolver.setTemplateMode("HTML5"); 
    templateResolver.setOrder(1); 
    return templateResolver; 
} 

@Bean 
public SpringTemplateEngine templateEngine (IMessageResolver messageResolver) { 
    final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); 
    templateEngine.addTemplateResolver(webTemplateResolver()); 
    templateEngine.addTemplateResolver(emailTemplateResolver()); 
    templateEngine.addDialect(new LayoutDialect()); 
    templateEngine.addDialect(new SpringSecurityDialect()); 
    templateEngine.addMessageResolver(messageResolver); 
    return templateEngine; 
} 

코드는

[THYMELEAF][http-bio-8080-exec-8] Exception processing template "contact.html": Resource resolution by ServletContext with org.thymeleaf.resourceresolver.ServletContextResourceResolver can only be performed when context implements org.thymeleaf.context.IWebContext [current context: org.thymeleaf.context.Context] 
Exception handled by GlobalExceptionHandler 
org.thymeleaf.exceptions.TemplateProcessingException: Resource resolution by ServletContext with org.thymeleaf.resourceresolver.ServletContextResourceResolver can only be performed when context implements org.thymeleaf.context.IWebContext [current context: org.thymeleaf.context.Context] 
     at org.thymeleaf.resourceresolver.ServletContextResourceResolver.getResourceAsStream(ServletContextResourceResolver.java:78) 
     at org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:221) 
     at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1104) 
     at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060) 
     at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011) 
     at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:924) 
     at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:898) 
     at com.proeza.core.service.MailService.sendContactEmail(MailService.java:47) 
     at com.proeza.core.service.MailService$$FastClassBySpringCGLIB$$f139c878.invoke(<generated>) 
     at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) 
     at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:711) 
     at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) 
     at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98) 
     at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262) 
     at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95) 
     at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) 
     at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644) 
     at com.proeza.core.service.MailService$$EnhancerBySpringCGLIB$$42cabd9f.sendContactEmail(<generated>) 
     at com.proeza.sgs.web.controller.RegisterController.register(RegisterController.java:69) 
     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 
     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
     at java.lang.reflect.Method.invoke(Method.java:606) 
     at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215) 
     at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) 
     at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) 
     at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749) 
     at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690) 
     at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83) 
     at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945) 
     at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876) 
     at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961) 
     at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863) 
     at javax.servlet.http.HttpServlet.service(HttpServlet.java:647) 
     at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837) 
     at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) 
     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) 
     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) 
     at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) 
     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108) 
     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) 
     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) 
     at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51) 
     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) 
     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) 
     at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) 
     at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118) 
     at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84) 
     at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
     at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113) 
     at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
     at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103) 
     at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
     at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113) 
     at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
     at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154) 
     at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
     at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45) 
     at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
     at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199) 
     at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
     at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110) 
     at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
     at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:105) 
     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108) 
     at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
     at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57) 
     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108) 
     at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
     at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87) 
     at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
     at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50) 
     at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108) 
     at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) 
     at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192) 
     at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160) 
     at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344) 
     at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261) 
     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) 
     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) 
     at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) 
     at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) 
     at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) 
     at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) 
     at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) 
     at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) 
     at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) 
     at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) 
     at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041) 
     at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603) 
     at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) 
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) 
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) 
     at java.lang.Thread.run(Thread.java:744) 

희망 누군가가 도움이 될 수 있습니다. 미리 감사드립니다.

감사합니다.

+0

안녕하세요 @ Emiliano Schiano. 내 질문에 [ThymeLeaf를 사용하여 HTML 메일을 보내는 방법] (http://stackoverflow.com/questions/32127059/how-to-send-html-mail-with-inline-image- using-thymeleaf) 도움을받을 수 있는지 확인하십시오. –

답변

2

좋아, thymeleaf 디버깅 문제를 찾을 수 있습니다. 엔진을 템플릿을 해결하도록 알려주는 방법이 잘못되었습니다. 이 줄 :

// Create the HTML body using Thymeleaf 
final String htmlContent = this.templateEngine.process("contact.html", ctx); 

리졸버로는 키우면 그것이 분명한 이유의 원인이 발견되지 않도록 "contant.html.html"라는 이름의 템플릿을 찾기 위해 노력하고있다

templateResolver.setSuffix(".html"); 

이 방법을 구성 .

처리 드 템플릿이 방법 :

// Create the HTML body using Thymeleaf 
final String htmlContent = this.templateEngine.process("contact", ctx); //Note .html not present 

applicaciont가 완벽하게 작동합니다.

이상한 점은 thymeleaf 워드 프로세서의 예제에는 html suffi가 있지만 시도해 보았지만 정상적으로 작동한다는 것입니다.

thymeleaf 버전이 이러한 차이를 일으킬 수 있습니까? 2.1.4.RELEASE

Reagards 대

2.1.3.RELEASE.

+0

어떤 문서를 언급하고 있습니까? 만약 당신이 (http://www.thymeleaf.org/doc/articles/springmail.html) Spring xml에 정의 된 템플릿 해석자를 본다면, 그들 둘 다 접미사 만 설정되고 접두사는 없다. –

+0

스프링 부트 사용자를위한 메모입니다. [ThymeleafProperties] (https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src)의 기본 속성으로 사용할 수 있습니다. /main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafProperties.java)는 DEFAULT_SUFFIX = ".html"로 설정되어 있습니다. 위에서 언급 한 스프링 메일 문서를 따르는 경우 마찬가지로 전달할 때 접미사를 제거해야합니다. 템플릿 이름에 프로세스 이름 –

+0

안녕하세요 @ 매트 C. 여기 내 질문을 보시겠습니까 [어떻게 ThymeLeaf를 사용하여 인라인 이미지와 HTML 메일을 보내려면] (http://stackoverflow.com/questions/32127059/how- to-send-html-mail-with-inline-image-using-thymeleaf)를 참조하여 도움을받을 수 있는지 확인하십시오. –

관련 문제