Servlet Forward on Post Validation Failure and Post-Redirect-Get

♀尐吖头ヾ 提交于 2019-12-31 04:11:17

问题


One strategy for handling validation of a form that is posted to a Java Servlet is to forward back to the original JSP view on validation failure. This allows the user to see that there was a validation failure in the context of the form they just submitted (perhaps they didn't provide a value for a required field), and then they can retry. However, since this strategy doesn't follow the well known Post-Redirect-Get pattern (http://en.wikipedia.org/wiki/Post/Redirect/Get) it suffers in that the browser history now includes a non-bookmarkable page. If the user later tries to access this page via the history/back button they'll get a document expired exception (in Firefox 19 at least). How should this be handled? Is there a better way?

Note: the strategy I'm describing is actually recommended in the Servlet info page: (https://stackoverflow.com/tags/servlets/info). There is no mention of browser history issues though.

Note: this question is similar: (JSF PRG with validation error). It suggests using AJAX for posts. If this is the recommended strategy maybe we need to update the Servlet wiki? Not exactly sure how this would translate from JSF to servlets anyways.


回答1:


As far as I can tell the forward on validation failure approach is flawed and shouldn't be used. Instead use one of these:

  1. Store validation error messages in session and do a redirect.

  2. Use AJAX to submit forms

  3. Catch all validation errors on the client with JavaScript and treat validation failures that reach the server as application errors and assume someone is posting to the server directly without using the application form or the application form has a bug. If you forward to an error page you'll have the same problem, but attackers deserve a jacked-up browser history. If the session is available you could stuff the error message in the session and do a redirect. Either way it removes validation from the server in "normal" operation and sidesteps the issue somewhat.



来源:https://stackoverflow.com/questions/15250588/servlet-forward-on-post-validation-failure-and-post-redirect-get

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!