A light ray is refracted when it obliquely passes from one medium to another. Because different wavelengths (colours) of light travel through a medium at different speeds, the amount of bending is different for different wavelengths. Violet is bent the most and red the least. Because white light is made up of all visible wavelengths, its colours can be separated (dispersed) by this difference in behavior.
When light passes through glass, it encounters two interfaces: one while entering and the other while leaving. It slows down at the first interface and speeds back up at the second. If the two interface surfaces are parallel to each other, as in a glass slab, all of the bending (and dispersion) that takes place at the first interfaces is exactly reversed at the second; and the colurs recombine to give back white light.
If the second interface is not parallel to the first, as in a prism, the effects of the first interface are not reversed and the colors separated at that interface continue along different paths upon leaving the glass, hence forming a spectrum.