Hi, I try to write a methode and call it later in my jsp file. I get always the error message: error occurred between lines: 7 and 11 in the jsp file: /test.jsp Generated servlet error: D:\Programme\Apache Tomcat 4.0\work\Standalone\localhost\_\test$jsp.java:15: Undefined variable or class name: out out.println(i);
The <%! %> syntax represents a declaration at the instance level, whereas content between the <% %> syntax gets inlined into the _jspService() method. If you look at the Java code for a translated JSP, the implicit variables that JSP provides are declared inside the _jspService() method and this is why they are available inside <% %> blocks. With declaration blocks, you are just defining another method on your JSP and therefore the out variable isn't available. There are a couple of ways to solve this. First of all, your method could take an additional parameter corresponding to the out variable, meaning that you would call it using <% test("my string", out); %>. Alternatively, if this piece of functionality is going to be reused within other JSP pages, you might consider using JSP tag extensions (also known as custom tags). This provides a much nicer abstraction while keeping your pages readable and maintainable. Hope that helps Simon
ok, thanks that work, but i don't want to use so much parameters, to have access to the java classes. why it doesnt work like this:
Sorry for the simple questions, but i dont understand why i can't write this simple methods. tomcat comiles the jsp parts into a serlet, so why this methods are not methods of a servlet or other class? Thanks again! regards...
It doesn't work because (essentially) the contents of your JSP page get translated into the contents of a method called _jspService() on the servlet, and writing a method declaration inside another method isn't permitted in the Java language. No problems about the questions, that's what the ranch is for. Cheers Simon
No because they are, at the end of the day, just normal methods on a Servlet class. You can write the methods inside other JavaBeans (Java classes) but you still have to pass objects like "out" as parameters. This is one of the key reasons to use custom tags over JavaBeans - they are much more aligned to and aware of the environment in which they are running. JavaBeans are just reusable components that can be reused no matter what the environment is, whereas custom tags require a JSP container to run in. Declaring methods inside JSP pages is useful on occasion, but should you need to start using them elsewhere, take a look at the custom tag stuff. Simon