By running the program from a windowed environment, like GNOME, KDE, Enlightenment, etc. Judging from that exception, you are running the program on a command line without any windowing system running, probably a server. So where are you going to display the JOptionPane?
If you get a HeadlessException you can sometimes prevent it by using the -Djava.awt.headless=true JVM property (which comes before the class name), but only if you don't really need the windowed environment. Which you do in this case.
A web application does not work in exactly the same way as a desktop application, where you can display a message box at any time. You have to be aware of the HTTP request-response cycle, and what code runs where (server or client) and when.