h:commandbutton,如何重定向到外部站点?(JSF 2) [英] h:commandbutton, how to redirect to external site?(JSF 2)
问题描述
当我使用命令按钮重定向到页面时,在我的项目中,你只需要提供没有扩展名的页面名称,然后在action属性中输入?faces-redirect = true 我会被重定向。
When i use command button to redirect to pages, inside my project, u just need to give the name of the page with no extention, followed by ?faces-redirect=true in the action attribute and i will get redirected.
但如果我想重定向到外部网页(例如:www.google.com)怎么办?
But what if i want to get redirected to an external page(example:www.google.com)?
我尝试过多种方式:
www.google.com,google.com, http://google.com
但是我失败了。
这就是我所做的:
<h:form>
<h:commandButton
action="#{mainPageBB.goToLink}" value="#{msgs.clickhere}"/>
</h:form>
然后支持bean:
@Named("mainPageBB")
@RequestScoped
public class MainPageBB {
@EJB
private ILinkManagerEJB linkManagerEJB;
public String goToLink() {
String link = linkManagerEJB.retrieveLink();
if(link != null) {
System.out.println(link);
return link.trim() + "?faces-redirect=true";
}
return null;
}
注意: retrieveLink(); 总是www.google.com(100%肯定)
Note: the value returned by retrieveLink(); is always www.google.com(100% sure)
我在控制台中完全没有错误,页面只是刷新。此外,我确信第一个if子句验证为true,所以我认为没有理由跳转到返回null。
I get no errors at all in the console, the page just refreshes. Also i am sure the first if clause validates to true, so i see no reason for it to jump to return null.
更新
我尝试了外部上下文,但我得到了404,因为它将当前url附加到链接字符串:
I tried with external context, but i get a 404 because it appends the current url to the link string:
public String goToRandomLink() {
String link = linkManagerEJB.retrieveRandomLink();
if(link != null) {
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
try {
externalContext.redirect(link.trim());
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
推荐答案
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
externalContext.redirect(link.trim());
如果您知道该链接已经使用
and if you know the link already just use
< a href =#{someBean.someLink}>#{msg.someMessage}< / a>
这篇关于h:commandbutton,如何重定向到外部站点?(JSF 2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!