Java 如何在jsp页面加载时调用servlet
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24066367/
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
How to call servlet on jsp page load
提问by user3660263
I want to call a servlet latest_products
on load of index.jsp
page.This servlet has records in List. I want to pass this List<products>
to index.jsp
. But I don't want to display the name of servlet in url. Is there any way by which I can do this.
我想latest_products
在加载index.jsp
页面时调用一个 servlet 。这个 servlet 在列表中有记录。我想把这个List<products>
传给index.jsp
. 但我不想在 url 中显示 servlet 的名称。有什么办法可以做到这一点。
采纳答案by Braj
Solution 1
解决方案1
Steps to follow:
要遵循的步骤:
- use
jsp:include
to call the Servlet from the JSP that will include the response of the Servlet in the JSP at runtime - set the attribute in the request in Servlet and then simply read it in JSP
- 用于
jsp:include
从 JSP 调用 Servlet,该 Servlet 将在运行时包含 JSP 中 Servlet 的响应 - 在 Servlet 中设置请求中的属性,然后在 JSP 中简单地读取它
Sample code:
示例代码:
JSP:
JSP:
<body>
<jsp:include page="/latest_products.jsp" />
<c:out value="${message }"></c:out>
</body>
Servlet:
小服务程序:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("message", "hello");
}
EDIT
编辑
but i don't want to display the name of servlet in url.
但我不想在 url 中显示 servlet 的名称。
Simply define a different and meaningful url-pattern
for the Servlet in the web.xml
such as as shown below that look like a JSP page but internally it's a Servlet.
简单地定义一个不同的和有意义url-pattern
的 Servletweb.xml
如下图所示,它看起来像一个 JSP 页面,但在内部它是一个 Servlet。
web.xml:
网页.xml:
<servlet>
<servlet-name>LatestProductsServlet</servlet-name>
<servlet-class>com.x.y.LatestProductsServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LatestProductsServlet</servlet-name>
<url-pattern>/latest_products.jsp</url-pattern>
</servlet-mapping>
Solution 2
解决方案2
Steps to follow:
要遵循的步骤:
- first call to the the Servlet
- process the latest products
- set the list in the request attribute
- forward the request to the JSP where it can be accessed easily in JSP using JSTL
- 第一次调用 Servlet
- 加工最新产品
- 在请求属性中设置列表
- 将请求转发到 JSP,在那里它可以使用 JSTL 在 JSP 中轻松访问
Sample code:
示例代码:
Servlet:
小服务程序:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("message", "hello");
RequestDispatcher view=request.getRequestDispatcher("index.jsp");
view.forward(request,response);
}
index.jsp:
索引.jsp:
<body>
<c:out value="${message }"></c:out>
</body>
hit the URL: scheme://domain:port/latest_products.jsp
that will call the Servlet's doGet()
method.
点击 URL:scheme://domain:port/latest_products.jsp
这将调用 Servlet 的doGet()
方法。
回答by Erran Morad
Thanks to +Braj, I am able to make an answer using Expression Language. Apparently, this is supposed to be better than jsp scripting/tags.
感谢+Braj,我能够使用表达式语言做出答案。显然,这应该比 jsp 脚本/标签更好。
Servlet -
小服务程序 -
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ProductList extends HttpServlet {
private static final long serialVersionUID = 1L;
public ProductList() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<String> products = new ArrayList<String>();
products.add("Car");
products.add("Gun");
products.add("Shades");
request.setAttribute("productsList", products);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
JSP -
JSP -
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<c:import url="/ProductList" />
<c:set var="myProducts" value="${requestScope.productsList}" />
<h1>List of products from servlet</h1>
<c:forEach var="product" items= "${myProducts}" varStatus="i">
${product}<br>
</c:forEach>
</body>
</html>
回答by Luiggi Mendoza
(...) but I don't want to display the name of servlet in url.
(...) 但我不想在 url 中显示 servlet 的名称。
You don't need to use the Servlet name at all when accessing to a Servlet. In fact, you can create your servlet to point to the desired URL by defining the right URL pattern:
访问 Servlet 时根本不需要使用 Servlet 名称。事实上,您可以通过定义正确的 URL 模式来创建您的 servlet 以指向所需的 URL :
@WebServlet("/index.jsp")
public class LatestProductServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
List<Product> productList = ...
//all the necessary code to obtain the list of products
//store it as request attribute
request.setAttribute("productList", productLlist);
//forward to the desired view
//this is the real JSP that has the content to display to user
request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
}
}
Then, you will have a folder structure like this
然后,您将拥有这样的文件夹结构
- <root folder>
- WEB-INF
+ index.jsp
+ web.xml
And in WEB-INF/index.jsp:
在 WEB-INF/index.jsp 中:
<!DOCTYPE html>
<html lang="es">
<body>
<!--
Display the data accordingly.
Basic quick start example
-->
<c:forEach items="${productList}" var="product">
${product.name} <br />
</c:forEach>
</body>
</html>
Note that your clients will access to http://<yourWebServer>:<port>/<yourApplication>/index.jsp
and will get the desired content. And you don't need to fire two GET requests to retrieve the content for your specific page.
请注意,您的客户将访问http://<yourWebServer>:<port>/<yourApplication>/index.jsp
并获得所需的内容。而且您不需要触发两个 GET 请求来检索特定页面的内容。
Note that you can go further with this approach: Since the pattern is now defined in servlet, you may choose to not use index.jsp for your clients, but index.html to access to your page. Just change the URL pattern in the Servlet:
请注意,您可以使用这种方法更进一步:由于模式现在是在 servlet 中定义的,您可以选择不为您的客户端使用 index.jsp,而是使用 index.html 来访问您的页面。只需更改 Servlet 中的 URL 模式:
@WebServlet("/index.html")
public class LatestProductServlet extends HttpServlet {
//implementation...
}
And the clients will access to http://<yourWebServer>:<port>/<yourApplication>/index.html
, which will show the results in WEB-INF/index.jsp. Now both your clients and you will be happy: clients will get their data and you won't show that ugly servlet name in your URL.
并且客户端将访问http://<yourWebServer>:<port>/<yourApplication>/index.html
,这将在 WEB-INF/index.jsp 中显示结果。现在你和你的客户都会很高兴:客户会得到他们的数据,你不会在你的 URL 中显示那个丑陋的 servlet 名称。
Additional
额外的
If you have index.jsp as your welcome page in web.xml, this approach won't work because application servlet expects that a real file index.jsp exists. To solve this issue, just create an empty file named index.jsp:
如果您将 index.jsp 作为 web.xml 中的欢迎页面,则此方法将不起作用,因为应用程序 servlet 期望存在真实的文件 index.jsp。要解决这个问题,只需创建一个名为 index.jsp 的空文件:
- <root folder>
- index.jsp <-- fake empty file to trick the application server
- WEB-INF
+ index.jsp
+ web.xml
And when accessing to http://<yourWebServer>:<port>/<yourApplication>/
, will work as shown above.
当访问 时http://<yourWebServer>:<port>/<yourApplication>/
,将如上所示工作。