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

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

问题描述

我有以下servlet。我想在 jsp 页面加载时调用servlet。我该怎么做?

I have below servlet. I would like to call the servlet on jsp page load. How can I do that?

servlet: SomeServlet.java

<servlet>
  <servlet-name>Hello</servlet-name>
  <servlet-class>SomeServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>Hello</servlet-name>
 <url-pattern>/HelloWorld</url-pattern>
 </servlet-mapping>

如何在jsp页面加载时编写相应的jsp来调用servlet。另外我需要从servlet获取结果并在同一个jsp中显示。我可以将结果发送回 jsp 吗?

How can I write corresponding jsp to invoke the servlet on jsp page load. Also I need to get the result from servlet and display in the same jsp. Can I send result back to jsp?

谢谢!

推荐答案

你应该反过来这样做。通过URL调用servlet并让它呈现JSP。这也是正常的MVC方法(servlet是控制器,JSP是视图)。

You should do it the other way round. Call the servlet by its URL and let it present the JSP. That's also the normal MVC approach (servlet is the controller and JSP is the view).

首先将JSP文件放在 / WEB-INF 文件夹,以便最终用户永远不会无意中通过直接在浏览器地址栏中输入其URL而不调用servlet来打开它。然后相应地更改servlet的 doGet(),它将请求转发给JSP。

First put the JSP file in /WEB-INF folder so that the enduser can never "accidently" open it by directly entering its URL in browser address bar without invoking the servlet. Then change the servlet's doGet() accordingly that it forwards the request to the JSP.

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // ...

    request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}

打开它

http:// localhost:8080 / contextname / HelloServlet

请注意,您当然可以将servlet映射中的URL模式更改为 / hello 以便您可以使用更具代表性的URL:

Note that you can of course change the URL pattern in servlet mapping to something like /hello so that you can use a more representative URL:


http:// localhost:8080 / contextname / hello



参见:




  • 我们的Servlets代码信息页

  • See also:

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

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