0

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/profile?uname='test;, if i get the null value from the url then it's redirect to /apex/home page.below is my code.

public class HomePageController {

public HomePageController()
{
  String unameParam = ApexPages.currentPage().getParameters().get('uname');
  if(unameparam == null)
  {
    // calling logout method to redirect to home page.      
    Logout();
  }
}

public PageReference Logout() {
         System.debug('RCHOME ###');
         PageReference mainHome= Page.rc_home; 
         mainHome.setRedirect(true);
         return mainHome;
}

if i get the null value from url it's executing Logout() method successfully but it's not redirecting to home page.

Could you please help on this.

1 Answer 1

1

You can not redirect user from controller> Call this method from Page's Action attribute and check value of URL and if it is null then redirect it to home page. It will work for you. Code sample

public HomePageController()
{
  String unameParam = ApexPages.currentPage().getParameters().get('uname');
  if(unameparam == null)
  {
    // calling logout method to redirect to home page.      
    Logout();
  }
}

public PageReference Logout() {
     String unameParam = ApexPages.currentPage().getParameters().get('uname');
  if(unameparam == null)
  {
         System.debug('RCHOME ###');
         PageReference mainHome= Page.rc_home; 
         mainHome.setRedirect(true);
         return mainHome;
}
}
6
  • Hi Sharma, thanks for your help, it's working but it's always redirecting to page2 even uname not null or not empty. Please let me know your thoughts on this.
    – ncmouli
    Oct 7, 2015 at 10:18
  • you don't put any condition . First check if your parameter is null same as you are checking the constructor. Oct 7, 2015 at 10:19
  • sorry, it's not working please see my code below. Page: <apex:page controller="redirectcontroller" action="{!HomePage}"> </apex:page> URL: TEST.visual.force.com/apex/page1?uname='test' it's redirecting to page2. Please see the controller below.
    – ncmouli
    Oct 7, 2015 at 10:21
  • public without sharing class redirectcontroller { public redirectcontroller() { String uparam = ApexPages.currentPage().getParameters().get('uname'); System.debug('UPARAM ###:'+uparam); if(uparam == null) { HomePage(); } } public Pagereference HomePage() { System.debug('RCHOME ###'); PageReference mainHome= Page.Page2; mainHome.setRedirect(true); return mainHome; } }
    – ncmouli
    Oct 7, 2015 at 10:25
  • I have update my comment with code sample you can take help from that. I am sure it will work for you. Oct 7, 2015 at 10:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .