如何通过 JSP 页面调用 servlet [英] How to call servlet through a JSP page

查看:29
本文介绍了如何通过 JSP 页面调用 servlet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过 JSP 页面调用 Servlet.调用的方法是什么?

I would like to call a Servlet through a JSP page. What is the method to call?

推荐答案

可以使用来解决这个问题.

You could use <jsp:include> for this.

<jsp:include page="/servletURL" />

但通常情况相反.您调用 servlet,后者又转发到 JSP 以显示结果.创建一个 Servlet,它在 doGet() 方法中执行如下操作.

It's however usually the other way round. You call the servlet which in turn forwards to the JSP to display the results. Create a Servlet which does something like following in doGet() method.

request.setAttribute("result", "This is the result of the servlet call");
request.getRequestDispatcher("/WEB-INF/result.jsp").forward(request, response);

/WEB-INF/result.jsp

<p>The result is ${result}</p>

现在通过与 web.xml 中匹配的 URL 调用 Servlet,例如http://example.com/contextname/servletURL.

Now call the Servlet by the URL which matches its <url-pattern> in web.xml, e.g. http://example.com/contextname/servletURL.

请注意,JSP 文件明确放置在/WEB-INF 文件夹中.这将阻止用户单独打开 JSP 文件.用户只能调用servlet来打开JSP文件.

Do note that the JSP file is explicitly placed in /WEB-INF folder. This will prevent the user from opening the JSP file individually. The user can only call the servlet in order to open the JSP file.

如果您实际的问题是如何向 servlet 提交表单?"那么您只需要在 HTML 表单 action 中指定 servlet URL.

If your actual question is "How to submit a form to a servlet?" then you just have to specify the servlet URL in the HTML form action.

<form action="servletURL" method="post">

然后会调用它的 doPost() 方法.

Its doPost() method will then be called.

  • Servlets info page - Contains a hello world
  • How to call servlet class from HTML form
  • How do I pass current item to Java method by clicking a hyperlink or button in JSP page?
  • Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
  • Design Patterns web based applications

这篇关于如何通过 JSP 页面调用 servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆