0

I have the following method in my 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

<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

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

user2473430
  • 43
  • 1
  • 2
  • 8
  • 1
    Almost everything, really. Expose variables to the view through request attributes. If you believe you can't, then the code doesn't belong in the servlet at all. The "source" attribute of a script tag should be a URL that returns JavaScript in this case--but unless you're dynamically creating the entirety of your JavaScript, also-ew. – Dave Newton Jul 16 '13 at 19:57
  • What exactly is the error you're getting ? Or you're just trying to validate the design for a working solution ? – Costi Ciudatu Jul 16 '13 at 20:04
  • Yes, I am trying to validate my design.I need to get the google maps api url from the database and add it as as the src tag in the JSP FIle. – user2473430 Jul 16 '13 at 20:16
  • I agree with @DaveNewton *Can anyone please tell me what I m doing wrong?* Almost everything. – Luiggi Mendoza Jul 16 '13 at 21:08

3 Answers3

1

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.

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

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

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.

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:

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

Costi Ciudatu
  • 37,042
  • 7
  • 56
  • 92
0

You dont need that, you should access to data so :

Save data from Servlet -> request.setAttribute("MyObject", data);

After in JSP you load data that need -> request.getAttribute("MyObject");

Sorry my english, good luck.

-1

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.
  2. Then write the following scriptlet: <%= 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.

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.

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

  2. Invoking a Servlet method from JSP is bad design. Servlet methods are designed to handle HTTP methods. 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. That information should be pre-processed.

Community
  • 1
  • 1
Rubens Mariuzzo
  • 28,358
  • 27
  • 121
  • 148
  • When I code as in the question control is going to the process method.But I need the src tag to have the return value of the process method.Is there any way to do this? – user2473430 Jul 16 '13 at 20:10
  • @user2473430, I just fixed the answer. Try adding the `=` sign in the opening tag like: `<%= %>`. – Rubens Mariuzzo Jul 16 '13 at 20:12
  • -1: This is invalid code. What's worse is that `process` method is `private` and can't be directly accessed not even if creating a new instance of `MyServletName` class. Also, `src` will execute a `GET` request on the name of the resource you put there. Looks like OP wants to recover a whole JavaScript file from the `MyServlet#doGet` handling. – Luiggi Mendoza Jul 16 '13 at 21:00
  • @LuiggiMendoza, I said to the OP that he needs to 'ensure that its servlet method is publicly accessible'. Also, he said that he want to 'add the string returned from the process method'. As far as I understand... he just want the string returned. I'm thinking that the string could be a path such as `/path/to/script.js`. I don't know the situation of the OP, I'm just being specific about what he want. – Rubens Mariuzzo Jul 16 '13 at 21:07
  • Even if the `process` method wrongly returns `/path/to/script.js`, you **must not** use scriptlet to do this, and what's worse, creating an instance of a Servlet class manually! This answer is as wrong as OP's current design. The only solution I can come up to solve this is accessing the Servlet and save the `/path/to/script.js` in a request attribute and forward to this JSP, then consume this request attribute in the JSP in form of ``. – Luiggi Mendoza Jul 16 '13 at 21:09
  • @LuiggiMendoza, I know that. Thanks for writing this to let the OP know that. I'm just limiting myself to answer his question instead of criticizing he's bad design/implementation. I could wrote a whole article about best practice but I didn't, because the OP is not asking that. Of course I could encourage the OP to do something else like not using scriplet, but you and I don't know what is his situations. – Rubens Mariuzzo Jul 16 '13 at 21:15
  • 2
    @RubensMariuzzo We know he's doing it wrong; IMO we should encourage the OP to do it *right* when it's *this* wrong. – Dave Newton Jul 16 '13 at 21:18
  • Anyway, if OP wants to keep using this approach, the `process` method should do something like `response.setContentType("text/javascript");` and start writing the JavaScript contents in the response (that's not handled in your answer as well). FYI there's an *article* about the bests practices: [How to avoid Java Code in JSP-Files?](http://stackoverflow.com/q/3177733/1065197) no need to reinvent this wheel :). – Luiggi Mendoza Jul 16 '13 at 21:18
  • Thanks @DaveNewton, you are right, I added a note above my answer. If you suggest me to remove my answer, I will do so, in favor of the OP and others. – Rubens Mariuzzo Jul 16 '13 at 21:20
  • @LuiggiMendoza, my natural languages are French and Spanish, but as far as I understood from the question is that the OP want the *result* of the Java method (again, the OP textually said: 'I want to add the string returned from the process method'), *not the method itself*. Also, since the OP wants to write to the `src` tag, logically he want a path, not a JavaScript function. – Rubens Mariuzzo Jul 16 '13 at 21:24
  • My natural language is Spanish and I understood that OP still hasn't grasp all the concepts. It's our labor to explain them what's wrong with the current approach and the causes. For me, it looks like OP wanted that the Servlet GET method retrieves the content of the JavaScript file (not a simple JavaScript function) in the response. Anyway, I would recommend you posting a new answer with a right answer and deleting this one. – Luiggi Mendoza Jul 16 '13 at 21:27
  • @RubensMariuzzo I'm in favor of answering the OP's question, but explaining that what the OP is trying to do is horrible, and providing an answer to the question they *should* have asked ;) – Dave Newton Jul 16 '13 at 21:29
  • Thanks @LuiggiMendoza for your suggestions. I will not delete this answer because I still believe it somewhat *wrongly* answer the OP question. Since the OP 'still hasnt grasp all the concept' and didn't provided more information. I think you could answer the question or maybe DaveNewton. In this way, the OP and newbie can start rethinking :) – Rubens Mariuzzo Jul 16 '13 at 21:31