【问题标题】:How to access spring session bean scope in thymeleaf如何在 thymeleaf 中访问 Spring session bean 范围
【发布时间】:2017-05-13 19:27:17
【问题描述】:

我已经定义了我的对象

  @Component
  @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) 
  public class MySession {
      private String message;

     // getter setter
  }

当我尝试从 thymeleaf 访问时失败了。

<p th:text="${mySession.message}"></p>

解决方案

通过spring bean访问

http://www.thymeleaf.org/doc/articles/springmvcaccessdata.html

 <p th:text="${@mySession.getMessage()}"></p>

【问题讨论】:

  • 什么失败了?有什么错误吗?
  • 错误消息:在 null 上找不到属性或字段“消息”。但是,我找到了解决方案,通过 spring bean 访问

标签: spring-mvc spring-boot thymeleaf


【解决方案1】:
session.setAttribute("mySessionAttribute", "someValue");

您可以直接访问会话属性。

${#session.getAttribute('mySessionAttribute')}

【讨论】:

    【解决方案2】:

    例如会话 bean

    @Component
    @SessionScope
    public class State implements Serializable {
    
        private String pdfPropertyName;
    
        public String getPdfPropertyName() {
            return pdfPropertyName;
        }
        public void setPdfPropertyName(String pdfPropertyName) {
            this.pdfPropertyName = pdfPropertyName;
        }
    }
    

    在控制器中

    @Controller
    @RequestMapping("uploadPdf")
    public class UploadPdfController {
    
        @Autowired State state;
    
        @ModelAttribute("pdfPropertyName")
        public String getPdfPropertyName() {
            return state.getPdfPropertyName();
        }
    
    }
    

    可以通过

    <span th:text="${pdfPropertyName}"></span>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-09
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-10
      相关资源
      最近更新 更多