开发者

populating data onto jsp from java classes

开发者 https://www.devze.com 2023-03-06 18:44 出处:网络
How to populate the da开发者_JAVA百科ta from a java class(not a servlet) onto a jsp page. One way would be jsp<->servlet<->java class....

How to populate the da开发者_JAVA百科ta from a java class(not a servlet) onto a jsp page. One way would be jsp<->servlet<->java class....

Is there a direct way without using servlet..jsp<->java class??


You could import your class into the jsp by dropping the jar into the libs folder for the webapp (if you haven't done so already) then importing in into your jsp:

<%@ page import="com.mypkg.MyClass" %>

Once you've done so you can use your class in the jsp as you normally would:

<select>
<%
    MyClass instance = new MyClass();
    for(int i=0;i<instance.itemCount();i++){
        out.println("<option>"+instance.getItem(i).getName()+"</option>");
    }
%>
</select>

Another way which would be preferable overall is to create a TagLibrary that uses your class. TagLibraries are cleaner and easier to support and understand than using Java code inside your jsp. Sun's guide to using and creating tag libraries is pretty good: http://java.sun.com/products/jsp/tutorial/TagLibraries3.html


It's the servlet container that renders the jsp page. The only way (with one possible exception) to pass data to a jsp is by setting attributes on the HttpServletRequest (request scope), HttpSession (session scope), or the ServletContext itself (application scope). So the short answer to your question is no.

That said, there are a few other possibilities I can think of to have other classes get data to a jsp (or at least get it rendered on the page):

  • You can pass one of the above objects to another class and have that class set the data as an attribute in the proper scope.
  • You can write a custom jsp tag that will use one of your classes to render data in the jsp. See here for how to do this.
  • You could use javascript to make an Ajax call that will return json, xml, html, etc. and then write the data to the page.

Hope this helps. Btw, it would help if you put a little more detailed explanation of what you are trying to accomplish.

0

精彩评论

暂无评论...
验证码 换一张
取 消