java h:commandbutton,如何重定向到外部站点?(JSF 2)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7159358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
h:commandbutton, how to redirect to external site?(JSF 2)
提问by sfrj
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=truein the action attribute and i will get redirected.
当我使用命令按钮重定向到页面时,在我的项目中,您只需要提供没有扩展名的页面名称,然后在 action 属性中添加?faces-redirect=true,我将被重定向。
But what if i want to get redirected to an external page(example:www.google.com)?
但是如果我想被重定向到外部页面(例如:www.google.com)怎么办?
I tried in many ways:
我尝试了很多方法:
www.google.com, google.com, http://google.com
www.google.com、google.com、http://google.com
but i failed.
但我失败了。
This is what i did:
这就是我所做的:
<h:form>
<h:commandButton
action="#{mainPageBB.goToLink}" value="#{msgs.clickhere}"/>
</h:form>
and then the backing bean:
然后是支持 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;
}
Note: the value returned by retrieveLink();is always www.google.com(100% sure)
注意:retrieveLink()返回的值;始终是 www.google.com(100% 确定)
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.
我在控制台中完全没有错误,页面只是刷新。此外,我确信第一个 if 子句验证为真,所以我认为没有理由让它跳转返回 null。
Update
更新
I tried with external context, but i get a 404 because it appends the current url to the link string:
我尝试使用外部上下文,但我得到 404,因为它将当前 url 附加到链接字符串:
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;
}
回答by Jigar Joshi
Use ExternalContext.redirect()
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>
<a href="#{someBean.someLink}">#{msg.someMessage}</a>
回答by MMelo
You can do this creating an input with type="button" between a link tag "a". Something like this:
您可以这样做,在链接标签“a”之间创建一个 type="button" 的输入。像这样的东西:
<a href="http://www.google.com">
<input type="button" value="Button text" />
</a>