In this paper, we introduce the Hamiltonian boundary value method (HBVM) to solve nonlinear Hamiltonian PDEs. We use the idea of Fourier pseudospectral method in spatial direction, which leads to the finite-dimensional Hamiltonian system. The HBVM, which can preserve the Hamiltonian effectively, is applied in time direction. Then the nonlinear Schrödinger (NLS) equation and the Korteweg-de Vries (KdV) equation are taken as examples to show the validity of the proposed method. Numerical results confirm that the proposed method can simulate the propagation and collision of different solitons well. Meanwhile the corresponding errors in Hamiltonian and other intrinsic invariants are presented to show the good preservation property of the proposed method during long-time numerical calculation.