This paper presents a gait optimization method to generate the locomotion pattern for biped and discuss its stability. The main contribution of this paper is a newly proposed energy-based stability criterion, which permits the dynamic stable walking and could be straight-forwardly generalized to different locomotion scenarios and biped robots. The gait optimization problem is formulated subject to the constraints of the whole-body dynamics and kinematics. The constraints are established based on the modelling of bipedal hybrid dynamical systems. Following the whole-body modelling, the system energy is acquired and then applied to create the stability criterion. The optimization objective is also established on the system energy. The gait optimization is solved by being converted to a large-scale programming problem, where the transcription accuracy is improved via the spectral method. To further reduce the dimensionality of the large-scale problem, the whole-body dynamics is re-constructed. The generalization of the optimized gait is improved by the design of feedback control. The optimization examples demonstrate that the stability criterion naturally leads to a cyclic biped locomotion, though the periodicity was not previously imposed. Two simulation cases, level ground walking and slope walking, verify the generalization of the stability criterion and feedback control. The stability analyses are carried out by investigating the motions of centre of gravity and centre of pressure. It is revealed that if the tracked speed is above 0.3 m/s or the biped accelerates/climbs the slope, the stability criterion accomplishes the dynamic stable walking, where zero moment point criterion is not strictly complied.