[SalesForce] VF controller redirect to another page

I have a Apex Controller for a VF page. I want to redirect my page to another one, only if I cannot get a specific parameter from the URL.
current page: /apex/demo?param=123 -> stay on this page.
current page: /apex/demo -> redirect to /apex/demo2.

My controller's constructor:

public demoController(){
String p = ApexPages.currentPage().getParameters().get('param');
if(p == null){
// redirect to /apex/demo2
}
}

How can I get it done? Thanks!

Best Answer

I figured out that I can use apex:page action="". VF:

<apex:page controller="demoController" action="{!redirect}"/>

Controller:

public PageReference redirect(){
        if(p == null){
            PageReference pageRef = new PageReference('/apex/demo2');
            return pageRef;
        }
        else{
            return null;
        }
}
Related Topic