如何在jsp(Spring框架)中直接显示通过PropertySourcesPlaceholderConfigurer定义的属性值?

时间:2013-07-18 14:07:37

标签: spring jsp spring-mvc properties

我在Spring应用程序上下文中有以下配置。

    <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="props">
            <list>
                <value>file://${user.home}/myConfig.properties</value>
            </list>
        </property>
    </bean>

让我们说我想在myConfig.properties文件中直接在jsp中显示一个定义为属性的值(例如:app.url.secret)。我怎样才能做到这一点?

提前感谢您的帮助

2 个答案:

答案 0 :(得分:0)

你必须以某种方式将它送到你的模型:

一种方法是以这种方式使用PropertyHolder:

@Component
public class PropertyHolder {

  @Value("${myprop}")
  private String myProperty;

  //getters and setters..

}

在您的控制器中:

   @Controller
   public class MyController {
      @Autowired private PropertyHolder propertyHolder;

      @ModelAttribute
      public void setModelAttributes(Model model) {
        model.put("myprops", propertyHolder);
      } 

....rest of your controller..

   }

然后您就可以访问jsp中的myprops - myprops.myProperty

答案 1 :(得分:0)

首先使用控制器上的属性值填充模型,然后返回一个解析为JSP的视图

您可以使用@Value注释将属性注入控制器

@Controller
public class MyController {

  @Value("${app.url.secret}") private String urlSecret;

  @RequestMapping("/hello")
  public String hello(Model model) {
    model.addAttribute("urlSecret", urlSecret);

    // assuming this will resolve to hello.jsp
    return "hello";
  }
}

然后在你的hello.jsp

<%@ page ... %>
<html>
 ...
 The secret url is: ${urlSecret}