简体   繁体   English

在页面加载时从 JSP 文件调用 servlet

[英]Calling a servlet from JSP file on page load

Can I call a servlet from JSP file without using a HTML form?我可以在不使用 HTML 表单的情况下从 JSP 文件调用 servlet 吗?

For example, to show results from database in a HTML table during page load.例如,在页面加载期间在 HTML 表中显示来自数据库的结果。

You can use the doGet() method of the servlet to preprocess a request and forward the request to the JSP.您可以使用 servlet 的doGet()方法来预处理请求并将请求转发给 JSP。 Then just point the servlet URL instead of JSP URL in links and browser address bar.然后只需在链接和浏览器地址栏中指向 servlet URL 而不是 JSP URL。

Eg例如

@WebServlet("/products")
public class ProductsServlet extends HttpServlet {

    @EJB
    private ProductService productService;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Product> products = productService.list();
        request.setAttribute("products", products);
        request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);
    }

}
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
    <c:forEach items="${products}" var="product">
        <tr>
            <td>${product.name}</td>
            <td>${product.description}</td>
            <td>${product.price}</td>
        </tr>
    </c:forEach>
</table>

Note that the JSP file is placed inside /WEB-INF folder to prevent users from accessing it directly without calling the servlet.请注意,JSP 文件放在/WEB-INF文件夹中,以防止用户在不调用 servlet 的情况下直接访问它。

Also note that @WebServlet is only available since Servlet 3.0 (Tomcat 7, etc), see also @WebServlet annotation with Tomcat 7 .另请注意, @WebServlet仅在 Servlet 3.0(Tomcat 7 等)之后才可用,另请参见@WebServlet annotation with Tomcat 7 If you can't upgrade, or when you for some reason need to use a web.xml which is not compatible with Servlet 3.0, then you'd need to manually register the servlet the old fashioned way in web.xml as below instead of using the annotation:如果您无法升级,或者由于某种原因需要使用与 Servlet 3.0 不兼容的web.xml ,那么您需要在web.xml中手动注册 servlet,如下所示,而不是使用注释:

<servlet>
    <servlet-name>productsServlet</servlet-name>
    <servlet-class>com.example.ProductsServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>productsServlet</servlet-name>
    <url-pattern>/products</url-pattern>
</servlet-mapping>

Once having properly registered the servlet by annotation or XML, now you can open it by http://localhost:8080/context/products where /context is the webapp's deployed context path and /products is the servlet's URL pattern.一旦通过注释或 XML 正确注册了 servlet,现在您可以通过 http://localhost:8080/context/products 打开它,其中/context是 webapp 部署的上下文路径, /products是 servlet 的 URL 模式。 If you happen to have any HTML <form> inside it, then just let it POST to the current URL like so <form method="post"> and add a doPost() to the very same servlet to perform the postprocessing job.如果您碰巧在其中有任何 HTML <form> ,那么只需让它像<form method="post">那样 POST 到当前 URL,并将doPost()添加到同一个 servlet 以执行后处理工作。 Continue the below links for more concrete examples on that.继续下面的链接以获取更多具体示例。

See also也可以看看

You will need to use RequestDispatcher's Methods forward/include depending on your requirement to achieve same.您将需要根据您的要求使用 RequestDispatcher 的方法转发/包含来实现相同的目标。

In JSP you need to use following tags:在 JSP 中,您需要使用以下标签:

jsp:include : jsp:包括

The element allows you to include either a static or dynamic file in a JSP file.该元素允许您在 JSP 文件中包含静态或动态文件。 The results of including static and dynamic files are quite different.包含静态文件和动态文件的结果是完全不同的。 If the file is static, its content is included in the calling JSP file.如果文件是静态的,则其内容包含在调用 JSP 文件中。 If the file is dynamic, it acts on a request and sends back a result that is included in the JSP page.如果文件是动态的,它会根据请求执行操作并返回包含在 JSP 页面中的结果。 When the include action is finished, the JSP container continues processing the remainder of the JSP file.当包含动作完成时,JSP 容器继续处理 JSP 文件的剩余部分。

eg例如

<jsp:include page="/HandlerServlet" flush="true">  

jsp:forward : jsp:转发

The element forwards the request object containing the client request information from one JSP file to another file.该元素将包含客户端请求信息的请求对象从一个 JSP 文件转发到另一个文件。 The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file.目标文件可以是 HTML 文件、另一个 JSP 文件或 servlet,只要它与转发 JSP 文件位于相同的应用程序上下文中即可。 The lines in the source JSP file after the element are not processed.不处理源 JSP 文件中元素之后的行。

eg例如

<jsp:forward page="/servlet/ServletCallingJsp" />

Check Advanced JSP Sample : JSP-Servlet Communication:检查高级 JSP 示例:JSP-Servlet 通信:

http://www.oracle.com/technology/sample_code/tech/java/jsps/ojsp/jspservlet.html http://www.oracle.com/technology/sample_code/tech/java/jsps/ojsp/jspservlet.html

Sure you can, simply include it in your action in the form .当然可以,只需将其包含在form中的action中。 But you have to write the correct doPost or doGet to handle the request!但是您必须编写正确的doPostdoGet来处理请求!

If you want to call a particular servlet method than you also use Expression Language.如果你想调用一个特定的 servlet 方法,那么你也可以使用表达式语言。 For example, you can do something like:例如,您可以执行以下操作:

Servlet小服务程序

ForexTest forexObject = new ForexTest();
request.setAttribute("forex", forexObject);

JSP JSP

<body bgcolor="#D2E9FF">
Current date : ${forex.rate}
</body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM