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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3590961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 02:17:28  来源:igfitidea点击:

Calling a servlet from JSP file on page load

javajspservletsonload

提问by palAlaa

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 表中显示数据库中的结果。

采纳答案by BalusC

You can use the doGet()method of the servlet to preprocessa request and forward the request to the JSP. Then just point the servlet URL instead of JSP URL in links and browser address bar.

您可以使用doGet()servlet的方法对请求进行预处理并将请求转发到 JSP。然后只需在链接和浏览器地址栏中指向 servlet URL 而不是 JSP URL。

E.g.

例如

@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-INFfolder to prevent users from accessing it directly without calling the servlet.

请注意,JSP 文件放置在/WEB-INF文件夹中,以防止用户在不调用 servlet 的情况下直接访问它。

Also note that @WebServletis only available since Servlet 3.0 (Tomcat 7, etc), see also @WebServlet annotation with Tomcat 7. If you can't upgrade, or when you for some reason need to use a web.xmlwhich is not compatible with Servlet 3.0, then you'd need to manually register the servlet the old fashioned way in web.xmlas below instead of using the annotation:

另请注意,@WebServlet仅自 Servlet 3.0(Tomcat 7 等)起可用,另请参阅@WebServlet 注释与 Tomcat 7。如果您无法升级,或者由于某种原因需要使用web.xml与 Servlet 3.0 不兼容的 servlet,那么您需要以如下方式手动注册 servlet,web.xml而不是使用注释:

<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/productswhere /contextis the webapp's deployed context path and /productsis the servlet's URL pattern. 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. Continue the below links for more concrete examples on that.

一旦通过注释或 XML 正确注册了 servlet,现在您可以通过http://localhost:8080/context/products打开它,其中/context是 webapp 的部署上下文路径,/products是 servlet 的 URL 模式。如果您碰巧在其中包含任何 HTML <form>,那么只需让它像这样 POST 到当前 URL <form method="post">,并将 a 添加doPost()到相同的 servlet 以执行后处理作业。继续下面的链接以获得更具体的例子。

See also

也可以看看

回答by YoK

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. 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. If the file is dynamic, it acts on a request and sends back a result that is included in the JSP page. When the include action is finished, the JSP container continues processing the remainder of the JSP file.

该元素允许您在 JSP 文件中包含静态或动态文件。包括静态和动态文件的结果是完全不同的。如果文件是静态的,则其内容包含在调用 JSP 文件中。如果文件是动态的,它会根据请求执行操作并发回包含在 JSP 页面中的结果。当包含操作完成时,JSP 容器会继续处理 JSP 文件的其余部分。

e.g.

例如

<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. 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. The lines in the source JSP file after the element are not processed.

该元素将包含客户端请求信息的请求对象从一个 JSP 文件转发到另一个文件。目标文件可以是 HTML 文件、另一个 JSP 文件或 servlet,只要它与转发 JSP 文件在同一应用程序上下文中即可。不处理源 JSP 文件中元素之后的行。

e.g.

例如

<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

回答by Truong Ha

Sure you can, simply include it in your actionin the form. But you have to write the correct doPostor doGetto handle the request!

当然可以,只需将其包含actionform. 但是你要写正确的doPost还是doGet要处理请求的!

回答by Rachel

If you want to call a particular servlet method than you also use Expression Language. For example, you can do something like:

如果你想调用一个特定的 servlet 方法,你也可以使用表达式语言。例如,您可以执行以下操作:

Servlet

小服务程序

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

JSP

JSP

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