如何在jsp页面加载时调用servlet [英] How to call servlet on jsp page load

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

问题描述

我想在加载 index.jsp 页面时调用servlet latest_products 。这个servlet在List中有记录。我想将此列表< products> 传递给 index.jsp 。但我不想在url中显示servlet的名称。有什么方法可以做到这一点。

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.

推荐答案

解决方案1 ​​



要遵循的步骤:

Solution 1

Steps to follow:


  • 使用 jsp:include 来调用Servlet来自JSP的JSP将在运行时包含Servlet在JSP中的响应

  • 在Servlet中设置请求中的属性,然后在JSP中读取它

  • 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:

<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


但我不想在url中显示servlet的名称。

but i don't want to display the name of servlet in url.

只需定义一个不同的和对于 web.xml 中的Servlet,有意义的 url-pattern ,如下所示,看起来像JSP页面但是在内部,它是一个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.

web.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>



解决方案2



要遵循的步骤:

Solution 2

Steps to follow:


  • 首次致电Servlet

  • 处理最新产品

  • 在请求属性中设置列表

  • 将请求转发到JSP,使用JSTL可以在JSP中轻松访问它

  • 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:

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:

index.jsp:

<body>      
    <c:out value="${message }"></c:out>
</body>

点击URL: scheme:// domain:port / latest_products.jsp 将调用Servlet的 doGet()方法。

hit the URL: scheme://domain:port/latest_products.jsp that will call the Servlet's doGet() method.

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

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