Let assume someone types a longtail keyword, how do you dynamically
generate a page with those keywords?
You cannot dynamically generate a page to appear in search results after the search has been run (unless you control the search engine) so you appear to be either asking how highlight the terms a user entered as part of his or her search on your site or how to create spam content.
Is there a way to know what keyword was searched and display including
that keyword?
Yes and no - if a user is logged in with his or her Google account (or using SSL at Google) the HTTP referrer field is not populated and you will not be able to infer the user's search from the referrer field.
If the user is not logged in, you can parse the query from the q
GET variable in the referrer URL:
http://www.google.com/url?sa=t&rct=j& [...] q=the%20query [...]