我正在开发Spring MVC应用程序。在我的应用程序中,我有两个配置文件:测试和生产。当我在生产环境中部署我的应用程序来测试环境和生产环境时,会启用测试。
我需要获取jsp文件中的最新配置文件。有可能吗?我不想发送额外的变量来获取此信息,因为文件包含在许多其他文件中。谢谢
发布于 2013-01-29 20:26:48
您可以使用类似以下内容:
ServletContext sc = request.getSession().getServletContext();
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(sc);
String[] profiles = applicationContext.getEnvironment().getActiveProfiles();发布于 2013-11-11 23:52:04
由于您使用的是MVC,因此更直接的方法是在控制器中自动生成环境,并在模型中传递配置文件。
@Autowired
private Environment environment;
@RequestMapping("/needsProfile")
public String needsProfile(Model model) {
model.addAttribute("profiles", environment.getActiveProfiles());
return "needsProfile";
}在你的needsProfile.jsp中:
<jsp:useBean id="profiles" type="java.lang.String[]" scope="request"/>
<%-- ... --%>
<div>First Profile: ${profiles[0]}</div>发布于 2016-04-16 20:04:13
要获得更好的效果,可以创建自定义JSP标记。您可以使用以下教程来实现这一点:http://blog.florianlopes.io/access-spring-profiles-with-custom-jsp-tag/
使用此自定义标记,您将能够基于活动的Spring配置文件限制区域。
这个想法是为了扩展Spring RequestContextAwareTag.它将使您的自定义标记能够访问Spring配置文件。扩展这个类,实现很简单:
public class ProfileConditionTag extends RequestContextAwareTag {
private String expectedProfile;
@Override
protected int doStartTagInternal() throws Exception {
final Environment environment = this.getRequestContext().getWebApplicationContext().getEnvironment();
if (environment != null) {
final String[] activeProfiles = environment.getActiveProfiles();
if (ArrayUtils.contains(activeProfiles, this.expectedProfile)) {
return EVAL_BODY_INCLUDE;
}
}
return SKIP_BODY;
}
// Getters, setters
}如果活动配置文件不是预期的配置文件,SKIP_BODY返回值将告诉JSP处理器跳过标记主体。
<%@ taglib prefix="tagprefix“uri="/WEB-INF/taglib/profile.tld”%>
<tagprefix:profile value="dev"> Only displayed if the active Spring profile is "dev". </tagprefix:profile>
https://stackoverflow.com/questions/14582661
复制相似问题