简体   繁体   English

如何从JSP调用servlet方法?

[英]How to call a servlet method from a JSP?

I have the following method in my Servlet. 我的Servlet中有以下方法。

private String process(HttpServletRequest arg0, HttpServletResponse arg1) {
    return ("a key");
} 

protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
    process(arg0, arg1);
}

In web.xml the following code is added 在web.xml中,添加了以下代码

<servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>iusa.ubicacel.actions.map.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/MyServlet</url-pattern>
</servlet-mapping>

In inicio.jsp the following is added 在inicio.jsp中添加了以下内容

<script type="text/javascript" src="<%=request.getContextPath()%>/MyServlet"></script>

In the src tag above I want to add google map api url(which I will retrieve from the database in the servlet) from the process method in the MyServlet.I understand from the comments that my approach is wrong.Can anyone please tell me how to do it correctly with only this jsp and servlet. 在上面的src标记中,我想从MyServlet的处理方法中添加google map api url(我将从servlet中的数据库中检索)。我从评论中了解到我的方法是错误的。有人可以告诉我如何仅使用此jsp和servlet即可正确执行此操作。

A best practice for writing servlets with JSP is to follow the MVC pattern: your servlet will be the controller, the JSP is the view, while the model will consist of your domain objects which are passed from the servlet to the JSP page via request attributes. 使用JSP编写servlet的最佳实践是遵循MVC模式:您的servlet将是控制器,JSP是视图,而模型将由您的域对象组成,这些域对象通过请求属性从servlet传递到JSP页面。

I don't think that what you have right now is entirely wrong. 我不认为您现在拥有的完全是错误的。 But it's only suited for a special scenario where you will need to generate all your javascript code from a servlet (and this is hardly ever a true requirement). 但这仅适用于需要从servlet生成所有javascript代码的特殊情况(这几乎不是真正的要求)。 Assuming though that this is a true requirement in your case (perhaps you read the whole javascript content from a database), it's OK to define a servlet that renders the JS content (and perhaps map it as /main.js or something, to make the dynamic generation transparent for the JSP page). 假设这是您的真实要求(也许您从数据库中读取了整个javascript内容),则可以定义一个呈现JS内容的servlet(也可以将其映射为/main.js或其他内容)对JSP页面透明的动态生成)。

Most likely, you need only a bunch of small items to be dynamically generated at runtime (like your google maps url, API key or whatever you store in your database). 最有可能的是,您只需要一堆小项目即可在运行时动态生成(例如Google Maps网址,API密钥或您存储在数据库中的任何内容)。 If this is the case, then your JavaScript code can be statically defined in a .js file and allow initialization with some constructor arguments (or whatever). 如果是这种情况,则可以在.js文件中静态定义您的JavaScript代码,并允许使用某些构造函数参数(或其他参数)进行初始化。

In this setup, your servlet will read the url from the database, will pass it to the view by calling request.setAttribute("googleMapsUrl", url) and then call requestDispatcher.forward(...) to pass control to the JSP. 在此设置中,您的servlet将读取数据库中的request.setAttribute("googleMapsUrl", url) ,然后通过调用request.setAttribute("googleMapsUrl", url)将其传递给视图,然后调用requestDispatcher.forward(...)将控制权传递给JSP。

In the JSP, you'll now need to include your static script with src and then you can have another script tag to initialize your code based on dynamic values bound to your request: 在JSP中,您现在需要在src中包含静态脚本,然后可以使用另一个script标签根据绑定到请求的动态值来初始化代码:

<c:url value="/static.js" var="scriptUrl"/>
<script type="text/javascript" src="${scriptUrl}"></script>
<script type="text/javascript">
    // let's assume your static script defines an object called `MyGoogleMapsDriver`...
    var googleMapsDriver = new MyGoogleMapsDriver('${googleMapsUrl}');
</script>

I hope this helps. 我希望这有帮助。

You dont need that, you should access to data so : 您不需要它,应该访问数据,以便:

Save data from Servlet -> request.setAttribute( "MyObject", data); Servlet保存数据-> request.setAttribute( “ MyObject”,data);

After in JSP you load data that need -> request.getAttribute( "MyObject" ) ; JSP中之后,加载需要-> request.getAttribute( “ MyObject” )的数据

Sorry my english, good luck. 对不起,我的英语,祝你好运。

Note : I don't recommend to do this, but this is the direct answer to the question. 注意 :我不建议您这样做,但这是问题的直接答案。 For more information, take a look at the comments. 有关更多信息,请查看注释。


If you just ' want to add the string returned from the process method ' you need to do the following: 如果您只是想添加处理方法返回的字符串,则需要执行以下操作:

  1. Make your method public and static . 使您的方法publicstatic
  2. Then write the following scriptlet: <%= MyServletName.process(request, response); %> 然后编写以下脚本: <%= MyServletName.process(request, response); %> <%= MyServletName.process(request, response); %> . <%= MyServletName.process(request, response); %> This will output the result of the process method. 这将输出处理方法的结果。

At the end you will have the following: 最后,您将获得以下内容:

<script src="<%= MyServletName.process(request, response); %>"></script>

The variables request and response are available in this scope. requestresponse变量在此范围内可用。

Important : The thing you are trying to achieve this way looks like a bad design . 重要提示 :您试图通过这种方式实现的目标看起来像是一个糟糕的设计 For various reason commented in this answer. 由于各种原因,在此答案中进行了评论。 Check the comments made by @LuiggiMendoza and @DaveNewton. 检查@LuiggiMendoza和@DaveNewton的评论。

Here are some points to take in account: 以下是需要考虑的一些要点:

  1. Writing scriplet is easy but is not recommended by any mean. 编写片段很容易,但绝不建议这样做。 See: How to avoid Java code in JSP files? 请参阅: 如何避免JSP文件中的Java代码? .

  2. Invoking a Servlet method from JSP is bad design . 从JSP调用Servlet方法是错误的设计 Servlet methods are designed to handle HTTP methods. Servlet方法旨在处理HTTP方法。 They were not designed to handle specific situation. 它们并非旨在处理特定情况。

  3. The thing you are trying to do is an anti-pattern , you are not separating concerns. 您尝试做的事情是反模式 ,您没有分离问题。 A JSP page should be a view that structure and render information. JSP页面应该是结构和呈现信息的视图。 That information should be pre-processed. 该信息应进行预处理。

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

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