Create a unique string as a token, save it in the session and paste it as a hidden input value in the form of a POST JSP, and finally check the servlet if the token is valid.
Basically:
When creating a session (e.g. HttpSessionListener#sessionCreated() ):
Set<String> tokens = new HashSet<String>(); event.getSession().setAttribute("tokens", tokens);
When pre-processing a JSP request (for example, HttpServlet#doGet() ):
String token = UUID.randomUUID().toString(); Set<String> tokens = (Set<String>) request.getSession().getAttribute("tokens"); tokens.add(token); request.setAttribute("token", token);
When processing the JSP itself:
<input type="hidden" name="token" value="${token}" />
When post-processing the submit form (in HttpServlet#doPost() , for example):
String token = request.getParameter("token"); Set<String> tokens = (Set<String>) request.getSession().getAttribute("tokens"); if (!tokens.remove(token)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; }
Of course, I assume that your jQuery.post() functions are written unobtrusively, as in $.post(form.action, form.serialize(), callback) , so that it mimics exactly the usual synchronous request (in other words, your forms work fine with disabled JS).
source share