无需 POST 或 GET 即可运行 Servlet
我是 servlet 新手,希望遵循 Model2 范例,将所有“代码”保留在 servlet 中,将 html/bean 保留在 jsp 页面中。但是,当我访问 jsp 页面而不使用表单提交时,有没有办法运行 servlet。例如,我有一个登录页面。如果用户登录然后以某种方式返回登录页面,我想检查其会话是否存在并自动将其移至欢迎页面。这是一个现实世界的示例,但由于多种原因,无需提交表单即可运行代码似乎会派上用场。
I am new to servlets, and would like to follow the Model2 paradigm by keeping all my "code" in servlets, and html/beans in jsp pages. But, is there a way to run a servlet when I access a jsp page without using a form submission. For example, I have a login page. If the user logs in and then somehow goes back to the login page I want to check for the existance of their session and automatically move them on to their welcome page. This is one real world example, but it seems it would come in handy to run code without having to submit a form for a multitude of reasons.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不必提交表单来调用 servlet。您所要做的就是让浏览器点击映射到 servlet 的 URL。当提交表单、单击链接、调用 xhr、从命令行使用 curl 或 wget 等时,可能会发生这种情况。
此外,将所有代码保留在 servlet 中并不是一个好的设计。您的 servlet 应该处理传入的请求,调用在单独的类中实现的业务逻辑(为了良好的模块化和测试目的),并返回适当的响应。
you dont have to submit a form to invoke a servlet. All you have to do is have the browser hit the url that is mapped to the servlet. That could happen when submitting a form, clicking a link, invoking an xhr, using curl or wget from the command line, etc.
Also, keeping all code in servlets is not good design. Your servlets should handle incoming requests, invoke business logic implemented in separate classes (for good modularity and testing purposes), and return the appropriate response.
如果我没记错的话,在 Model2 中,用户永远不会导航到 (JSP) 页面 - 仅导航到控制器(servlet)。尝试直接从视图(页面)访问较低层的代码(Servlet)违反了 MVC/Model2。
If I recall correctly, in Model2, the user never navigates to (JSP) pages - only controllers (servlets). Trying to access a lower layer of code (a servlet) direcltly from a view (the page) is a violation of MVC/Model2.