Pass Parameters from a Command Link to Controller

Sometimes we need to pass parameters to the controller, on click of a Command Link. Here is a simple example how to pass parameters from a Command Link click to controller.

Visualforce Page:

<apex:page standardController="Contact" extensions="SampleControllerExtn">  
    <apex:form>
        <apex:commandLink value="Click Command Link" action="{!processCommandLink}">
            <apex:param name="firstName" value="{!Contact.FirstName}" assignTo="{!firstName}"/>
            <apex:param name="lastName" value="{!Contact.LastName}" assignTo="{!lastName}"/>
        </apex:commandLink>
    </apex:form>
</apex:page>  

Apex Class:

public class SampleControllerExtn {
    
    //Variables being set from the commandlink
    public String firstName {get; set;}
    public String lastName {get; set;}
    
    //Initialize the controller
    public SampleControllerExtn(ApexPages.StandardController stdCtrl) {
        
    }
    
    //Handle the action of the commandLink
    public PageReference processCommandLink() {
        System.debug('Contact Name - ' + firstName + ' ' + lastName);
        //Process the variable with your logic
        return null;
    }
}