We consider a random walk in confined geometry, starting from a site and eventually reaching a target site. We calculate analytically the distribution of the occupation time on a third site, before reaching the target site. The obtained distribution is exact and completely explicit in the case or parallelepipedic confining domains. We discuss implications of these results in two different fields: The mean first passage time for the random trap model is computed in dimensions greater than 1 and is shown to display a nontrivial dependence with the source and target positions. The probability of reaction with a given imperfect center before being trapped by another one is also explicitly calculated, revealing a complex dependence both in geometrical and chemical parameters.