JSP using a bean to do output?

One thing I haven't seen much mention of is the possibility of using a Java Bean to
do some output for a JSP. I'm porting a page I wrote a while back that uses a
JHTML page to call a servlet which is just a thin wrapper around a bean which
actually writes the HTML output (the bean is actually a network client to a server
that generates the HTML page). The natural line of attack seems to be to have a
JSP call the bean which will write the output, but I haven't seen mention of that
technique anywhere and wonder why I'm so strange in thinking of this. The bean
method to do the output currently takes a PrintWriter as a parameter to output to,
but that can be changed to something similar if desired.
Can anyone give me a snippet of code that would best implement taking the output
stream for a JSP page and passing it to a bean for output?
Thanks
Steve

eh? It sounds like your bean is doing all the output? If that's the case, then why do you want to use a JSP? - use a servlet as you already are.
If you have a bean declared in the page and you just want to pass it the page's output stream to output part of the pages content, then use this:
<jsp:useBean id='myBean' class='com.mycompany.MyBeanClass'/>
<%
  PrintWriter beanOut = new PrintWriter(out);
  myBean.writeContent(beanOut);
  beanOut.close()
%>
  ...where writeContent is your method that takes a PriontWriter. out is a JspWriter, which extends Writer, so you need to create a PrintWriter from it. You may or may not need to close/flush the PrintWriter deppending upon your bean implementation.

Similar Messages

  • Why can't my jsp use this bean??

    hi,
    i'm stuck with this problem since yesterday. hope anyone can help me sort this out. i'll try to state my problem here as clear as possible...
    i have a jsp page named call.jsp which i put in the folder
    C:\Tomcat 5.5\webapps\ROOT\mypage\
    here's the content (partially) of the call.jsp
    <%@ page import = "login.*" %>
    <jsp:useBean id="mybean" class="login.loginDB"/>and here's the content of the bean which this call.jsp is trying to call. name of the bean is loginDB.java. i put the the loginDB.java inside this folder:
    C:\Tomcat 5.5\webapps\ROOT\mypage\WEB-INF\classes\login
    then i compiled the java file using the command prompt
    C:\Tomcat 5.5\webapps\ROOT\mypage\WEB-INF\classes\login\javac loginDB.java
    and so the output is loginDB.class which obviously is placed in the folder C:\Tomcat 5.5\webapps\ROOT\mypage\WEB-INF\classes\login\
    here's the content of loginDB.java:
    package login;
    import java.sql.*;
    import java.util.*;
    public class loginDB implements java.io.Serializable {
         private String dbServer = "localhost";
         private String dbName = "toyo-SMP";
         //getter
         public String getdbServer(){
              return dbServer;
         public String getdbName(){
              return dbName;
    }so the problem is, everytime i call call.jsp, this error will come out:
    org.apache.jasper.JasperException: /SMP-toyo/logoutPekerja.jsp(85,0) The value for the useBean class attribute login.loginDB is invalid.
         org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:512)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:377)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)i don't know what else should i to. thanks a lot for helping.
    btw i'm using tomcat 5.5.20 with jdk 1.5

    I got it why you are getting below above error: You should have a public constructor in your bean class without any arguments. Modify your bean like this:
    package login;
    import java.sql.*;
    import java.util.*;
    public class loginDB implements java.io.Serializable {
         private String dbServer = "localhost";
         private String dbName = "toyo-SMP";
    //Constructor
         public loginDB (){
         //getter
         public String getdbServer(){
              return dbServer;
         public String getdbName(){
              return dbName;
    }

  • Drop-down in JSP using a bean as back-end

    Hi everyone,
    I like to create a dynamic drop-down (reading from a database) using JSP but accessing a bean. My code on the bean is:
    public void DepartmentName() {
    try
    stmt1 = tConnection.createStatement();
    rs1 = stmt1.executeQuery ("select DEPT_NAME from DEPARTMENT");
    while ( rs1.next() )
    String DptName = rs1.getString("DEPT_NAME");
    System.out.println(DptName);
    Can anybody tell me how to call this DepartmentName bean in JSP? So far my JSP looks like this...
    <table width="100%"><tr>
    <form action="next.jsp" method="POST">
    <input type="hidden" name="type" value="listemp">
    <td width="100">
    <b>Department</b></td>
    <td wifth="100">
    <SELECT name=cust multiple size=4>
    <option>??????? HELP ???????????</option>
    </SELECT>
    </td>
    <td><input type="submit" value="Submit" name="dept">
    </td></tr></table>
    Many thanks.

    First you need to modify your bean to return some sort of data structure of String objects. How about a Vector? Then you could call Vector.elements() on the return statement of the DepartmentName() method, like this...
    public Enumeration DepartmentName()
      Vector myVector = new Vector(0);
      while(rs.next())
        myVector.add(rs.getString(1));
      return myVector.elements();
    }Then in your JSP you'll need to use the JSP useBean tag
    <jsp:useBean id="myBean" class="com.myco.myapp.MyBean" scope="page|request|session|application" />And before the option tag call the bean and get the enumeration of String objects, then loop through them like this:
    while(enum.hasMoreElements())
      out.println(((String) enum.nextElement()));
    }

  • Unable to run beans  with jsp using myeclipse

    I have create jsp application with in myeclipse using following process
    From the menu i create a J2EE ->WebProject
    The default folder name is src which is create automatically in editor
    when we create a package it will create under src folder
    as i create dbconnection in src folder
    The index.jsp file is in WebRoot folder .
    I have use the bean dbconnection in index.jsp as described below
              <jsp:useBean id="con" scope="session" class="dbconnection.ConnectionManager"></jsp:useBean>
         <jsp:useBean id="app" scope="sesion" class="dbconnection.JspApp"></jsp:useBean>
         <jsp:setProperty name="con" property="driverClass"
              value="com.mysql.jdbc.Driver" />
         <jsp:setProperty name="con" property="connectionURL"
              value="jdbc:mysql://localhost:3306/guestbook" />
    But it generate error and do not show any output There is no errors or warnings in dbconnection folder but i am unable to use it in my index.jsp page
    Please help me
    Thanks in advance

    use cactus jar files

  • How can i use JAVA BEAN and JSP?

    well, i have developed all my web apps by using pure JSP only, i know this sucks, but i dont know how to start on using beans... what directory should i put them into... etc... what are the good programminmg practices/standards/techniques when incorporating beans in jsp???

    Standards are pretty loose, but generally, Beans hold a lot of the backend logic for your JSP. This can include data validation before entering into the database, database inserts, queries, data manipulation. The JSP should really only contain code that will retrieve the data from the bean and appropriately output it.
    As far as using them, you can use the <jsp:useBean> tag in your JSP. As long as the bean is stored somewhere that your classpath points to, you're all set. From then on, you can use it like any other object in your JSP.

  • How to assign bean value to a local variable in JSP using struts.

    Hi everybody!
    I've a problem that puzzled me on how to assign a bean value to a local variable like String in JSP using struts.
    we can have someting like this to display the value
    <bean:write name="detailService" property="status" />or
    <bean:define id="theStatus" name="detailService" property="status"/>
         This is country: <%=theStatus%>but an error occured when I tried like this:
    String currentStatus = "<bean:define id="theStatus" name="detailService" property="status"/>";
    or
    String currentStatus = "<bean:write name="detailService" property="status" />";Is there a way to do this?.....
    Any help pretty much appreciated

    Java != JSP.
    The <bean:define> and <bean:write> tags are custom tags meant to appear in the HTML section of a JSP file, as opposed to the scriptlet section. They actually get turned into java code as part of the translation process.
    The <bean:write> tag naturally just writes out what you tell it to.
    The <bean:define> tag defines a local variable, and gives it a value.
    this should do it.
    <bean:define id="theStatus" name="detailService" property="status" type="java.lang.String"/>
    <%
      String currentStatus = theStatus;
    %>With the advent of JSTL, you shouldn't really need to use scriptlet code anymore. Personally I am for 0% scriptlet code in any jsp I write.

  • Insert data into table from JSP page using Entity Beans(EJB 3.0)

    I want to insert data into a database table from JSP page using Entity Beans(EJB 3.0).
    1. I have a table 'FRIENDS', (in Oracle 10g database).
    2. It has two columns, 'NAME' and 'CITY'. Both have datatype strings(varchar2).
    3. Now from a JSP page, having two textfields, 'NAME' and 'CITY', I want to insert data into table 'FRIENDS'.
    4. In between JSP and database is a Entity Bean(EJB 3.0) and a stateless session bean.
    5. I am using JDev as editor.
    Please provide me code ASAP or link with similar example.
    Thank you.
    Anurag

    Hi,
    I am also trying that scenario. So u can
    Post the jsp form data to a Servlet which will act as a Controller.
    In the servlet invoke the business method.
    Similar kind of app is in www.roseindia.net
    Hope this would help u.
    Meanwhile if u get any optimal solution, pls post it.
    Thanks,
    Happy Java Coding.

  • Problem using a bean in JSP on Tomcat 5.0.28

    Hi,
    I'm new to JSP, I've installed Tomcat 5.0.28 and I'm able to run JSP but when I try an asp wich uses a bean it gives me this error, the directory structure is
    testingProject with the first.jsp
    testingProject\WEB-INF\classes\myPackage with the test.class
    the first.asp
    <%@ page import="myPackage.Test" %>
    <html><head><title>Test</title></head>
    <body bgcolor=white>
    <jsp:useBean id="list" class="myPackage.Test"> </jsp:useBean>
    <jsp:getProperty name="list" property="value1" />
    <%=list.value1%>
    <p>
    </body></html>
    the Test.java
    package myPackage;
    public class Test{
    String value1="testinggggggggg";
    public void Test(){
    public String getValue1(){ return value1}
    the error
    thanks in advance
    org.apache.jasper.JasperException: Unable to compile class for JSP
    An error occurred at line: 6 in the jsp file: /first.jsp
    Generated servlet error:
    C:\Program Files\Apache Group\Tomcat 5.0\work\Catalina\localhost\testingProject\org\apache\jsp\first_jsp.java:60: cannot resolve symbol
    symbol : variable value1
    location: class myPackage.Test
    out.print(list.value1);
    ^
    1 error
         org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:84)
         org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:332)
         org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:412)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:472)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:451)

    There are two ways of getting info from the bean.
    1) the jsp:getProperty tag, which seems correct in your code
    2) the <%= ... tag. In that case you must write a valid java expression. In your case: list.getValue1()

  • Defining the path for the use of beans in a JSP

              Hello,
              I would like to use a bean in a JSP file, via the <jsp:usebean> directive.
              I didn't find any property (weblogic property) which could define the path
              to the directory of my beans classes.
              So :
              1) i have put the path of this directory in the weblogic classpath in the weblogic
              start script.
              2) i made the same with the java classpath.
              Both solutions don't work at all.
              Any suggestion would be appreciated.
              Thanks in advance.
              

              We use the \weblogic\myserver\serverclasses for beans..
              of course we pack beans into jar files, and these jar files are included into
              the wls classpath..
              "Sylvain R." <[email protected]> wrote:
              >
              >Hello,
              >I would like to use a bean in a JSP file, via the <jsp:usebean> directive.
              >I didn't find any property (weblogic property) which could define the
              >path
              > to the directory of my beans classes.
              >So :
              >1) i have put the path of this directory in the weblogic classpath in
              >the weblogic
              >start script.
              >2) i made the same with the java classpath.
              >
              >Both solutions don't work at all.
              >
              >Any suggestion would be appreciated.
              >Thanks in advance.
              >
              

  • Using java bean with jsp

    hello friends,
    i'm new to jsp. i want to create an html form that accepts username and a value from four radio buttons and display back the entered name and checked radio button's value using java bean.
    i use the <jsp:setProperty id="" property="*"> method. i don't know how to access the radio buttons value from the html.
    also when i use an additional field other than username the jsp page is showing error.
    Please give me the correct method to use java bean with jsp in this circumstance.
    thank you.

    thank you, but i have a problem left. the case is like this.
    i got the jsp and bean worked fine when i have a sinle input text field.
    but when i added a second text field i recieved the following error.
    javax.servlet.ServletException: basket.newbean.getUserPass()Ljava/lang/String;
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:825)
         org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:758)
         org.apache.jsp.newform.process_jsp._jspService(process_jsp.java:69)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    where userPass is the new form element. I have made the subsequent chanes in my bean program and jsp file.
    pls hlp.

  • Using web beans in JSP

    I would like to know how create a tree using Web Beans that Jdeveloper provides. Using the web object editor I could add two Beans which mapped to JSTree and JSTreeData(in oracle.jdeveloper.jsp.wb package), though I don't know the difference between them. I tried to include Both these beans in the JSP(which appear as tags) but I am unable to render the tree. Let's say I have a parent node (text: row1, url: url1, 3 childs) and 3 child nodes (text: row2..row4, url: url2..url4, each with no childs). How do I write it in the JSP to render it properly
    -Rajeev

    I would like to know how create a tree using Web Beans that Jdeveloper provides. Using the web object editor I could add two Beans which mapped to JSTree and JSTreeData(in oracle.jdeveloper.jsp.wb package), though I don't know the difference between them. I tried to include Both these beans in the JSP(which appear as tags) but I am unable to render the tree. Let's say I have a parent node (text: row1, url: url1, 3 childs) and 3 child nodes (text: row2..row4, url: url2..url4, each with no childs). How do I write it in the JSP to render it properly
    -Rajeev

  • Using BI Bean in JSP

    Hi,
    Can anyone please provider some pointers on using BIBeans in a JSP page. There are few options in my knowledge.
    1)Using BI-Beans API for writing our own JSP tags.
    2)In Jdev(10g) there seems to be some support for Graphs through ADF.
    3)JSP and UIX tags provided BI-Graph beans.
    thanks
    Rahul

    U may be used the code similar to following :
    Context context = new InitialContext.();
    Object obj = (Object)context.lookup("Your JNDI name");
    YourHome home = (YourHome)obj.portableRemoteObject.narrow(obj,
    YourHome.class);
    YourRemote remote = home.create();
    System.out.println("your Business methods : "+remote.businessMethod1());
    Put this code or whatever code used in ur console client in JSP and invoke the businessMethods using remote object.
    I worked with BEAWeblogic 5.1, I think similar case may be there with BEA Weblogic7 also.
    First, make a jar file with ome.Remote and Bean by using the deploymenttool, then compile with ejb compiler, the new Jar is the complete deployable file. Take this file and register in weblogic.properties file that is specify the path of the Jar file in the weblogic.properties file. and put the JSP in public-html directory and start the server. if the bean is deployed successfully, open JSP file in a browser then it will work.... if the bean is not deployed you won't get any result.
    I can say, just placing the initialContext part of code on the JSP and running the JSP. I think, this may helps u...
    Ramana

  • What's the difference between using java directly in JSP and java bean

    What is the difference if I use java code directly in JSP or use java bean in JSP?
    Which class to use for receiving the passed parameter from html or java script? Any difference for java code and java bean in the way receiving the passed data?
    How can I pass string from jsp to html or java script?

    1 Cleaner pages
    2 you have to write the class and use set and get methods
    3 What do you mean when saying passing string from jsp to html??, do you mean the value you can use <%=variablename%>

  • Portal Runtime Error when communicating from JSPDynPage to JSP Using Bean

    Hi ...
    I am pursuing this problem for quite sometime now. Even opened a high priority message with SAP. We are using a bean to communicate value between a JSPDynPage and a JSP. When trying to access the bean in the doProcessAfterInput of the JSPDynpage, sometimesi get a nullpointer exception ..as if the bean was released ..
    I have tried ComponentProfile, ComponentSession... but in vain. If i try to use HTTPSession, the initialization of the bean in the JSP fails since its scope is applicationIt also fails if i try and reduce the scope of the bean.
    Pls advice. I can post the code on request.
    Thanks,
    Devina

    I believe application has a larger scope than session ..
    Here's the extract of the code
    public void doInitialization() {
    IPortalComponentRequest request =(IPortalComponentRequest) this.getRequest();
              IPortalComponentResponse response =     (IPortalComponentResponse) this.getResponse();
              IPortalComponentContext compcontext = request.getComponentContext();
    zOrgStructBean.setOrgData(aOrgData);
                                  zOrgStructBean.init(); //initialize bean
                   //compcontext.putValue("OrgSelectionBean", zOrgStructBean);
                   myProfile.putValue("OrgSelectionBean", zOrgStructBean);
    public void doProcessBeforeOutput() throws PageException {
              IPortalComponentRequest request = (IPortalComponentRequest) this.getRequest();
              compcontext = request.getComponentContext();
         this.setJspName("TeamViewer.jsp");
         request = (IPortalComponentRequest) this.getRequest();
              request1 = request.getServletRequest();
              compcontext = request.getComponentContext();
              IPortalComponentProfile myProfile = compcontext.getProfile();
    zOrgStructBean =(OrgSelectionTreeBean) myProfile.getValue("OrgSelectionBean");
    ...// bean is returned as null
    JSP
    <%@ page import="com.hersheys.hr.pcr.exit.HersheyTeamViewerExitBean"%>
    <%@ page import="com.hersheys.hr.pcr.exit.OrgSelectionTreeBean"%>
    <%@ page import="java.util.*"%>
    <%@ page import="com.sapportals.portal.prt.component.*"%>
    <%@ page import="com.sapportals.htmlb.TreeNode"%>
    <%@ taglib uri="tagLib" prefix="hbj" %>
    <jsp:useBean id="OrgSelectionBean" scope="application" class="com.hersheys.hr.pcr.exit.OrgSelectionTreeBean"/>
    <jsp:useBean id="myTableViewBean" scope="application" class="com.hersheys.hr.pcr.exit.HersheyTeamViewerExitBean"/>
    <hbj:content id="myContext" >
    <hbj:page title="AIP TeamViewer" >
            <hbj:form id="myFormId">
                   <%  int j = myTableViewBean.getSelectedRow();
                        pageContext.setAttribute("myRootNode", OrgSelectionBean.getTree());
                    OrgSelectionBean.renderTree(myFormId);
    Bean
    public void init(JCO.Table TableData) {
              Object[] colTitle ={"Name","ID"};
              Object[] colTitleB = {"Forms"};
              data = new Object[TableData.getNumRows()][2];
              bdata = new Object[3][1];
              bdata[0][0]="Termination";
              bdata[1][0]="Retirement";
              bdata[2][0]="Death";
              int j = 0;
                        //int i;
              for (int i = 0; i < TableData.getNumRows(); i++) {
                             //HersheyTeamViewerAIPBean zAIPBean = (HersheyTeamViewerAIPBean)TableData.getRow(i);
                   j = 0;
              //for (JCO.FieldIterator e = TableData.fields(); e.hasMoreElements(); ){
                   JCO.FieldIterator e = TableData.fields();
                   while (e.hasMoreElements()) {
                             JCO.Field field = e.nextField();
                             data<i>[j] = field.getString();
                             j = j + 1;
                        TableData.nextRow();
              this.model = new DefaultTableViewModel(data, colTitle);
              this.setOldTableViewModel(data, colTitle);
              bmodel = new DefaultTableViewModel(bdata, colTitleB);

  • Precompiling a JSP that uses a bean

    Hi,
              I am facing a problem when I startup Weblogic with precompiling ON.
              I have a JSP that uses a bean. When the JSP is being compiled, Weblogic is
              actually trying to instantiate the bean and is executing code in the
              constructor of the bean !
              When I use the weblogic.jspc compiler to compile the JSP, no such thing
              happens.
              So this happens only when I precompile such a JSP when starting up Weblogic
              server.
              - Why does weblogic attempt to instantiat the bean ?
              - Is there any way to tell weblogic "dont instantiate this bean now" ?
              Also, the compiler is unable to find a class that is required by the bean. However, this class is there in the /applications/..../WEB-INF/lib in a JAR file. So why is the class not being found ?
              Thanks,
              Jay
              

    Do a stack trace from the constructor to determine who is calling it, and
              maybe why ...
              Peace,
              Cameron Purdy
              Tangosol Inc.
              << Tangosol Server: How Weblogic applications are customized >>
              << Download now from http://www.tangosol.com/download.jsp >>
              "Jayakumar Nandakumar" <[email protected]> wrote in message
              news:3bb0f6d6$[email protected]..
              > Hi,
              > I am facing a problem when I startup Weblogic with precompiling ON.
              >
              > I have a JSP that uses a bean. When the JSP is being compiled, Weblogic is
              > actually trying to instantiate the bean and is executing code in the
              > constructor of the bean !
              >
              > When I use the weblogic.jspc compiler to compile the JSP, no such thing
              > happens.
              >
              > So this happens only when I precompile such a JSP when starting up
              Weblogic
              > server.
              >
              > - Why does weblogic attempt to instantiat the bean ?
              > - Is there any way to tell weblogic "dont instantiate this bean now" ?
              >
              > Also, the compiler is unable to find a class that is required by the bean.
              However, this class is there in the /applications/..../WEB-INF/lib in a JAR
              file. So why is the class not being found ?
              >
              > Thanks,
              > Jay
              

Maybe you are looking for

  • How can I share a movie with my boyfriend?

    I have bought a movie on iTunes using my Apple ID and have watched it on my iPad.  A couple of questions about sharing... Firstly, can we watch my movie on his Mac? My iPad is assigned to my laptop back home, and he has his own iTunes set up on his M

  • Two hdmi displays to the Mac Pro  cylinder

    How do i hook up two hdmi displays to the Mac Pro  cylinder?

  • External Video Monitoring-In HDV

    How I view my HD fotage in an external monitor for editing? According (Help menu in FCP New features) in FCP "You can now output to external video interfaces whose settings don't match those of your sequence. Here are some examples of some of the pos

  • Data Load from DS-- DSO---- Cube

    Hello Guys, I have an issue with the data load. I use the OFI_GL_14 extractor. When I did he innit with data transfer I have around 450 K records. When I loaded to DSO from DS by DTP  it loaded the same 450 K . When I tried to load the data from DSO

  • How to create new audio tracks as stereo by default?

    Is this possible? For some reason all my audio tracks by default are mono. Would save time if they were stereo.