The connection is quite straightforward (but note that your two examples have different boundary conditions and are thus not equivalent). Assume that you know (e.g., from physical considerations) that your unknown function minimizes the functional
$$J(u) = \int_\Omega |\nabla u|^2 - 2fu\,dx$$
over all functions in a certain function space (here, $u\in H^1_0(\Omega)$, the space of all weakly differentiable functions which vanish at the boundary).
Just as in standard calculus, a necessary condition for $u$ to be a minimizer is that the derivative vanishes at $u$; specifically, that the
directional derivative satisfies
$$J(u;v) := \lim_{t\to 0} \frac{J(u+tv)-J(u)}{t} = 0 \qquad\text{for all }v\in H^1_0(\Omega)$$
(intuitively, $J$ does not further decrease by going a small step in any direction $v$ from $u$). Now, inserting the definition, canceling what you can, and taking the limit yields
$$0=J(u;v) = 2\int_\Omega \nabla u\cdot \nabla v\,dx - 2\int_\Omega f v\,dx \qquad \text{for all } v\in H^1_0(\Omega),$$
which is precisely the weak formulation.
If you now replace $H^1_0(\Omega)$ by a finite-dimensional subspace $V_h$ of (say) piecewise linear polynomials defined on a triangulation, you arrive (after rearranging and dividing by $2$) at the finite element formulation
$$\int_\Omega \nabla u_h\cdot \nabla v_h\,dx = \int_\Omega f v_h\,dx \qquad \text{for all } v_h\in V_h.$$
For Neumann boundary conditions, you proceed similarly, but the functional now involves a boundary integral similar to the volume integral for the right-hand side. For nonhomogeneous Dirichlet conditions, you'd write $u=u_g + u_0$, where $u_g$ is a suitable function with $u=g$ on the boundary and $u_0$ satisfies $u=0$ on the boundary and is similarly characterized as a minimizer (or solution of a weak form).
EDIT: In principle, you could also first replace $u\in H^1_0(\Omega)$ by $V_h$ in $J$, i.e., minimize $J(u_h)$ over all $u_h\in V_h$ and then compute the derivative, and end up at the same equation.
You could also discretize the functional and then apply a minimization algorithm to $J(u_h)$, e.g., steepest descent or Newton's method. (Or vice versa, formulate the minimization algorithm in function space and discretize each iteration.) For a linear equation, though, this would be equivalent to applying Richardson iteration to the weak formulation or just solving it, respectively, so there's no real gain. But for a nonlinear problem (where the weak formulation would be a nonlinear PDE), this so-called direct method can make sense and is actually used in practice.