Singleton in jsp

Hi folks
In a jsp based webapplication is it better to create SingleTon class for making connection?

No. Because of two reasons:
1) you shouldn't be doing database stuff in a JSP
2) you shouldn't even have Java code in a JSP
Lets talk about doing these things from a servlet, where it really belongs. You could create a singleton, but a simple util class with a static method that obtains a datasource from JNDI and creates a Connection using it can be enough.
It all depends on how you are going to structure your code, how you are going to separate tasks and logic, etc. There is no one design that is the best for all applications.

Similar Messages

  • Can not access the Instance Data of a Singleton class from MBean

    I am working against the deadline and i am sweating now. From past few days i have been working on a problem and now its the time to shout out.
    I have an application (let's call it "APP") and i have a "PerformanceStatistics" MBean written for APP. I also have a Singleton Data class (let's call it "SDATA") which provides some data for the MBean to access and calculate some application runtime stuff. Thus during the application startup and then in the application lifecysle, i will be adding data to the SDATA instance.So, this SDATA instance always has the data.
    Now, the problem is that i am not able to access any of the data or data structures from the PerformanceStatistics MBean. if i check the data structures when i am adding the data, all the structures contains data. But when i call this singleton instance from the MBean, am kind of having the empty data.
    Can anyone explain or have hints on what's happening ? Any help will be appreciated.
    I tried all sorts of DATA class being final and all methods being synchronized, static, ect.,, just to make sure. But no luck till now.
    Another unfortunate thing is that, i some times get different "ServicePerformanceData " instances (i.e. when i print the ServicePerformanceData.getInstance() they are different at different times). Not sure whats happening. I am running this application in WebLogic server and using the JConsole.
    Please see the detailed problem at @ http://stackoverflow.com/questions/1151117/can-not-access-the-instance-data-of-a-singleton-class-from-mbean
    I see related problems but no real solutions. Appreciate if anyone can throw in ideas.
    http://www.velocityreviews.com/forums/t135852-rmi-singletons-and-multiple-classloaders-in-weblogic.html
    http://www.theserverside.com/discussions/thread.tss?thread_id=12194
    http://www.jguru.com/faq/view.jsp?EID=1051835
    Thanks,
    Krishna

    I am working against the deadline and i am sweating now. From past few days i have been working on a problem and now its the time to shout out.
    I have an application (let's call it "APP") and i have a "PerformanceStatistics" MBean written for APP. I also have a Singleton Data class (let's call it "SDATA") which provides some data for the MBean to access and calculate some application runtime stuff. Thus during the application startup and then in the application lifecysle, i will be adding data to the SDATA instance.So, this SDATA instance always has the data.
    Now, the problem is that i am not able to access any of the data or data structures from the PerformanceStatistics MBean. if i check the data structures when i am adding the data, all the structures contains data. But when i call this singleton instance from the MBean, am kind of having the empty data.
    Can anyone explain or have hints on what's happening ? Any help will be appreciated.
    I tried all sorts of DATA class being final and all methods being synchronized, static, ect.,, just to make sure. But no luck till now.
    Another unfortunate thing is that, i some times get different "ServicePerformanceData " instances (i.e. when i print the ServicePerformanceData.getInstance() they are different at different times). Not sure whats happening. I am running this application in WebLogic server and using the JConsole.
    Please see the detailed problem at @ http://stackoverflow.com/questions/1151117/can-not-access-the-instance-data-of-a-singleton-class-from-mbean
    I see related problems but no real solutions. Appreciate if anyone can throw in ideas.
    http://www.velocityreviews.com/forums/t135852-rmi-singletons-and-multiple-classloaders-in-weblogic.html
    http://www.theserverside.com/discussions/thread.tss?thread_id=12194
    http://www.jguru.com/faq/view.jsp?EID=1051835
    Thanks,
    Krishna

  • Problem with Configuring Tomcat for running jsp web applications..Plz HELP

    I am using Tomcat 5.5 and Jdk 1.5.0_12 and Oracle 10g. I am using jdbc-odbc bridge connection
    to connect to the database. I have placed my project folder called
    tdm under the webapps folder in Tomcat. This 'tdm' folder consists of
    a collection of html pages,jsp pages and images of my project. Also I created a
    WEB-INF folderand in that I have lib folder which contains catalina-root.jar
    , classes12.jar and nls_charset.jar files. And also in the WEB-INF folder I have the web.xml
    file which looks like this
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <!--
    Copyright 2004 The Apache Software Foundation
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
    -->
    <web-app>
    <resource-ref>
    <description>Oracle Datasource example</description>
    <res-ref-name>jdbc/gdn</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    </resource-ref>
    </web-app>
    My Server.xml file in Tomcat\conf folder is as follows
    <!-- Example Server Configuration File -->
    <!-- Note that component elements are nested corresponding to their
    parent-child relationships with each other -->
    <!-- A "Server" is a singleton element that represents the entire JVM,
    which may contain one or more "Service" instances. The Server
    listens for a shutdown command on the indicated port.
    Note: A "Server" is not itself a "Container", so you may not
    define subcomponents such as "Valves" or "Loggers" at this level.
    -->
    <Server port="8005" shutdown="SHUTDOWN">
    <!-- Comment these entries out to disable JMX MBeans support used for the
    administration web application -->
    <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
    <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
    <!-- Global JNDI resources -->
    <GlobalNamingResources>
    <!-- Test entry for demonstration purposes -->
    <Environment name="simpleValue" type="java.lang.Integer" value="30"/>
    <!-- Editable user database that can also be used by
    UserDatabaseRealm to authenticate users -->
    <Resource name="UserDatabase" auth="Container"
    type="org.apache.catalina.UserDatabase"
    description="User database that can be updated and saved"
    factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
    pathname="conf/tomcat-users.xml" />
    <Resource name="jdbc/gdn" auth="Container"
    type="javax.sql.DataSource" driverClassName="sun.jdbc.odbc.JdbcOdbcDriver"
    url="jdbc:odbc:gdn"
    username="system" password="tiger" maxActive="20" maxIdle="10"
    maxWait="-1"/>
    </GlobalNamingResources>
    <!-- A "Service" is a collection of one or more "Connectors" that share
    a single "Container" (and therefore the web applications visible
    within that Container). Normally, that Container is an "Engine",
    but this is not required.
    Note: A "Service" is not itself a "Container", so you may not
    define subcomponents such as "Valves" or "Loggers" at this level.
    -->
    <!-- Define the Tomcat Stand-Alone Service -->
    <Service name="Catalina">
    <!-- A "Connector" represents an endpoint by which requests are received
    and responses are returned. Each Connector passes requests on to the
    associated "Container" (normally an Engine) for processing.
    By default, a non-SSL HTTP/1.1 Connector is established on port 8080.
    You can also enable an SSL HTTP/1.1 Connector on port 8443 by
    following the instructions below and uncommenting the second Connector
    entry. SSL support requires the following steps (see the SSL Config
    HOWTO in the Tomcat 5 documentation bundle for more detailed
    instructions):
    * If your JDK version 1.3 or prior, download and install JSSE 1.0.2 or
    later, and put the JAR files into "$JAVA_HOME/jre/lib/ext".
    * Execute:
    %JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA (Windows)
    $JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA (Unix)
    with a password value of "changeit" for both the certificate and
    the keystore itself.
    By default, DNS lookups are enabled when a web application calls
    request.getRemoteHost(). This can have an adverse impact on
    performance, so you can disable it by setting the
    "enableLookups" attribute to "false". When DNS lookups are disabled,
    request.getRemoteHost() will return the String version of the
    IP address of the remote client.
    -->
    <!-- Define a non-SSL HTTP/1.1 Connector on port 8080 -->
    <Connector
    port="5050" maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
    enableLookups="false" redirectPort="8443" acceptCount="100"
    connectionTimeout="20000" disableUploadTimeout="true" />
    <!-- Note : To disable connection timeouts, set connectionTimeout value
    to 0 -->
         <!-- Note : To use gzip compression you could set the following properties :
                   compression="on"
                   compressionMinSize="2048"
                   noCompressionUserAgents="gozilla, traviata"
                   compressableMimeType="text/html,text/xml"
         -->
    <!-- Define a SSL HTTP/1.1 Connector on port 8443 -->
    <!--
    <Connector port="8443"
    maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
    enableLookups="false" disableUploadTimeout="true"
    acceptCount="100" scheme="https" secure="true"
    clientAuth="false" sslProtocol="TLS" />
    -->
    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8009"
    enableLookups="false" redirectPort="8443" protocol="AJP/1.3" />
    <!-- Define a Proxied HTTP/1.1 Connector on port 8082 -->
    <!-- See proxy documentation for more information about using this. -->
    <!--
    <Connector port="8082"
    maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
    enableLookups="false" acceptCount="100" connectionTimeout="20000"
    proxyPort="80" disableUploadTimeout="true" />
    -->
    <!-- An Engine represents the entry point (within Catalina) that processes
    every request. The Engine implementation for Tomcat stand alone
    analyzes the HTTP headers included with the request, and passes them
    on to the appropriate Host (virtual host). -->
    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Standalone" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <!-- Define the top level container in our container hierarchy -->
    <Engine name="Catalina" defaultHost="localhost">
    <!-- The request dumper valve dumps useful debugging information about
    the request headers and cookies that were received, and the response
    headers and cookies that were sent, for all requests received by
    this instance of Tomcat. If you care only about requests to a
    particular virtual host, or a particular application, nest this
    element inside the corresponding <Host> or <Context> entry instead.
    For a similar mechanism that is portable to all Servlet 2.4
    containers, check out the "RequestDumperFilter" Filter in the
    example application (the source for this filter may be found in
    "$CATALINA_HOME/webapps/examples/WEB-INF/classes/filters").
    Request dumping is disabled by default. Uncomment the following
    element to enable it. -->
    <!--
    <Valve className="org.apache.catalina.valves.RequestDumperValve"/>
    -->
    <!-- Because this Realm is here, an instance will be shared globally -->
    <!-- This Realm uses the UserDatabase configured in the global JNDI
    resources under the key "UserDatabase". Any edits
    that are performed against this UserDatabase are immediately
    available for use by the Realm. -->
    <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
    resourceName="UserDatabase"/>
    <!-- Comment out the old realm but leave here for now in case we
    need to go back quickly -->
    <!--
    <Realm className="org.apache.catalina.realm.MemoryRealm" />
    -->
    <!-- Replace the above Realm with one of the following to get a Realm
    stored in a database and accessed via JDBC -->
    <!--
    <Realm className="org.apache.catalina.realm.JDBCRealm"
    driverName="org.gjt.mm.mysql.Driver"
    connectionURL="jdbc:mysql://localhost/authority"
    connectionName="test" connectionPassword="test"
    userTable="users" userNameCol="user_name" userCredCol="user_pass"
    userRoleTable="user_roles" roleNameCol="role_name" />
    -->
    <!--
    <Realm className="org.apache.catalina.realm.JDBCRealm"
    driverName="oracle.jdbc.driver.OracleDriver"
    connectionURL="jdbc:oracle:thin:@ntserver:1521:ORCL"
    connectionName="scott" connectionPassword="tiger"
    userTable="users" userNameCol="user_name" userCredCol="user_pass"
    userRoleTable="user_roles" roleNameCol="role_name" />
    -->
    <!--
    <Realm className="org.apache.catalina.realm.JDBCRealm"
    driverName="sun.jdbc.odbc.JdbcOdbcDriver"
    connectionURL="jdbc:odbc:CATALINA"
    userTable="users" userNameCol="user_name" userCredCol="user_pass"
    userRoleTable="user_roles" roleNameCol="role_name" />
    -->
    <!-- Define the default virtual host
    Note: XML Schema validation will not work with Xerces 2.2.
    -->
    <Host name="localhost" appBase="webapps"
    unpackWARs="true" autoDeploy="true"
    xmlValidation="false" xmlNamespaceAware="false">
    <!-- Defines a cluster for this node,
    By defining this element, means that every manager will be changed.
    So when running a cluster, only make sure that you have webapps in there
    that need to be clustered and remove the other ones.
    A cluster has the following parameters:
    className = the fully qualified name of the cluster class
    name = a descriptive name for your cluster, can be anything
    mcastAddr = the multicast address, has to be the same for all the nodes
    mcastPort = the multicast port, has to be the same for all the nodes
    mcastBindAddr = bind the multicast socket to a specific address
    mcastTTL = the multicast TTL if you want to limit your broadcast
    mcastSoTimeout = the multicast readtimeout
    mcastFrequency = the number of milliseconds in between sending a "I'm alive" heartbeat
    mcastDropTime = the number a milliseconds before a node is considered "dead" if no heartbeat is received
    tcpThreadCount = the number of threads to handle incoming replication requests, optimal would be the same amount of threads as nodes
    tcpListenAddress = the listen address (bind address) for TCP cluster request on this host,
    in case of multiple ethernet cards.
    auto means that address becomes
    InetAddress.getLocalHost().getHostAddress()
    tcpListenPort = the tcp listen port
    tcpSelectorTimeout = the timeout (ms) for the Selector.select() method in case the OS
    has a wakup bug in java.nio. Set to 0 for no timeout
    printToScreen = true means that managers will also print to std.out
    expireSessionsOnShutdown = true means that
    useDirtyFlag = true means that we only replicate a session after setAttribute,removeAttribute has been called.
    false means to replicate the session after each request.
    false means that replication would work for the following piece of code: (only for SimpleTcpReplicationManager)
    <%
    HashMap map = (HashMap)session.getAttribute("map");
    map.put("key","value");
    %>
    replicationMode = can be either 'pooled', 'synchronous' or 'asynchronous'.
    * Pooled means that the replication happens using several sockets in a synchronous way. Ie, the data gets replicated, then the request return. This is the same as the 'synchronous' setting except it uses a pool of sockets, hence it is multithreaded. This is the fastest and safest configuration. To use this, also increase the nr of tcp threads that you have dealing with replication.
    * Synchronous means that the thread that executes the request, is also the
    thread the replicates the data to the other nodes, and will not return until all
    nodes have received the information.
    * Asynchronous means that there is a specific 'sender' thread for each cluster node,
    so the request thread will queue the replication request into a "smart" queue,
    and then return to the client.
    The "smart" queue is a queue where when a session is added to the queue, and the same session
    already exists in the queue from a previous request, that session will be replaced
    in the queue instead of replicating two requests. This almost never happens, unless there is a
    large network delay.
    -->
    <!--
    When configuring for clustering, you also add in a valve to catch all the requests
    coming in, at the end of the request, the session may or may not be replicated.
    A session is replicated if and only if all the conditions are met:
    1. useDirtyFlag is true or setAttribute or removeAttribute has been called AND
    2. a session exists (has been created)
    3. the request is not trapped by the "filter" attribute
    The filter attribute is to filter out requests that could not modify the session,
    hence we don't replicate the session after the end of this request.
    The filter is negative, ie, anything you put in the filter, you mean to filter out,
    ie, no replication will be done on requests that match one of the filters.
    The filter attribute is delimited by ;, so you can't escape out ; even if you wanted to.
    filter=".*\.gif;.*\.js;" means that we will not replicate the session after requests with the URI
    ending with .gif and .js are intercepted.
    The deployer element can be used to deploy apps cluster wide.
    Currently the deployment only deploys/undeploys to working members in the cluster
    so no WARs are copied upons startup of a broken node.
    The deployer watches a directory (watchDir) for WAR files when watchEnabled="true"
    When a new war file is added the war gets deployed to the local instance,
    and then deployed to the other instances in the cluster.
    When a war file is deleted from the watchDir the war is undeployed locally
    and cluster wide
    -->
    <!--
    <Cluster className="org.apache.catalina.cluster.tcp.SimpleTcpCluster"
    managerClassName="org.apache.catalina.cluster.session.DeltaManager"
    expireSessionsOnShutdown="false"
    useDirtyFlag="true"
    notifyListenersOnReplication="true">
    <Membership
    className="org.apache.catalina.cluster.mcast.McastService"
    mcastAddr="228.0.0.4"
    mcastPort="45564"
    mcastFrequency="500"
    mcastDropTime="3000"/>
    <Receiver
    className="org.apache.catalina.cluster.tcp.ReplicationListener"
    tcpListenAddress="auto"
    tcpListenPort="4001"
    tcpSelectorTimeout="100"
    tcpThreadCount="6"/>
    <Sender
    className="org.apache.catalina.cluster.tcp.ReplicationTransmitter"
    replicationMode="pooled"
    ackTimeout="15000"/>
    <Valve className="org.apache.catalina.cluster.tcp.ReplicationValve"
    filter=".*\.gif;.*\.js;.*\.jpg;.*\.htm;.*\.html;.*\.txt;"/>
    <Deployer className="org.apache.catalina.cluster.deploy.FarmWarDeployer"
    tempDir="/tmp/war-temp/"
    deployDir="/tmp/war-deploy/"
    watchDir="/tmp/war-listen/"
    watchEnabled="false"/>
    </Cluster>
    -->
    <!-- Normally, users must authenticate themselves to each web app
    individually. Uncomment the following entry if you would like
    a user to be authenticated the first time they encounter a
    resource protected by a security constraint, and then have that
    user identity maintained across all web applications contained
    in this virtual host. -->
    <!--
    <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
    -->
    <!-- Access log processes all requests for this virtual host. By
    default, log files are created in the "logs" directory relative to
    $CATALINA_HOME. If you wish, you can specify a different
    directory with the "directory" attribute. Specify either a relative
    (to $CATALINA_HOME) or absolute path to the desired directory.
    -->
    <!--
    <Valve className="org.apache.catalina.valves.AccessLogValve"
    directory="logs" prefix="localhost_access_log." suffix=".txt"
    pattern="common" resolveHosts="false"/>
    -->
    <!-- Access log processes all requests for this virtual host. By
    default, log files are created in the "logs" directory relative to
    $CATALINA_HOME. If you wish, you can specify a different
    directory with the "directory" attribute. Specify either a relative
    (to $CATALINA_HOME) or absolute path to the desired directory.
    This access log implementation is optimized for maximum performance,
    but is hardcoded to support only the "common" and "combined" patterns.
    -->
    <!--
    <Valve className="org.apache.catalina.valves.FastCommonAccessLogValve"
    directory="logs" prefix="localhost_access_log." suffix=".txt"
    pattern="common" resolveHosts="false"/>
    -->
    <Context path="/tdm" docBase="tdm" debug="0" reloadable="true" />
    </Host>
    </Engine>
    </Service>
    </Server>
    I have set the context path to /tdm in the server.xml file. Should this be placed in context.xml?
    My first page in the project is called Homepage.html. To start my project I give http://localhost:5050/tdm/homepage.html
    in a browser. Here I accept a username and password from the user and then do the validation in
    a valid.jsp file, where I connect to the database and check and use jsp:forward to go to next pages
    accordingly. However when I enter the username and password and click Go in the homepage, nothing is
    displayed on the next page. The URL in the browser says valid.jsp but a blank screen appears.
    WHY DOES IT HAPPEN SO? DOES IT MEAN THAT TOMCAT IS NOT RECOGNIZING JAVA IN MY SYSTEM OR IS IT A PROBLEM
    WITH THE DATABASE CONNECTION OR SOMETHING ELSE? I FEEL THAT TOMCAT IS NOT EXECUTING JSP COMMANDS?
    IS IT POSSIBLE?WHY WILL THIS HAPPEN?
    I set the JAVA_HOME and CATALINA_HOME environment to the jdk and tomcat folders resp.
    Is there any other thing that I need to set in classpath? Should I have my project as a
    WAR file in the webapps of TOMCAT or just a folder i.e. directory structure will fine?

    I am using Tomcat 5.5 and Jdk 1.5.0_12 and Oracle 10g. I am using jdbc-odbc bridge connection
    to connect to the database. I have placed my project folder called
    tdm under the webapps folder in Tomcat. This 'tdm' folder consists of
    a collection of html pages,jsp pages and images of my project. Also I created a
    WEB-INF folderand in that I have lib folder which contains catalina-root.jar
    , classes12.jar and nls_charset.jar files. And also in the WEB-INF folder I have the web.xml
    file which looks like this
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <!--
    Copyright 2004 The Apache Software Foundation
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
    -->
    <web-app>
    <resource-ref>
    <description>Oracle Datasource example</description>
    <res-ref-name>jdbc/gdn</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    </resource-ref>
    </web-app>
    My Server.xml file in Tomcat\conf folder is as follows
    <!-- Example Server Configuration File -->
    <!-- Note that component elements are nested corresponding to their
    parent-child relationships with each other -->
    <!-- A "Server" is a singleton element that represents the entire JVM,
    which may contain one or more "Service" instances. The Server
    listens for a shutdown command on the indicated port.
    Note: A "Server" is not itself a "Container", so you may not
    define subcomponents such as "Valves" or "Loggers" at this level.
    -->
    <Server port="8005" shutdown="SHUTDOWN">
    <!-- Comment these entries out to disable JMX MBeans support used for the
    administration web application -->
    <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
    <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
    <!-- Global JNDI resources -->
    <GlobalNamingResources>
    <!-- Test entry for demonstration purposes -->
    <Environment name="simpleValue" type="java.lang.Integer" value="30"/>
    <!-- Editable user database that can also be used by
    UserDatabaseRealm to authenticate users -->
    <Resource name="UserDatabase" auth="Container"
    type="org.apache.catalina.UserDatabase"
    description="User database that can be updated and saved"
    factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
    pathname="conf/tomcat-users.xml" />
    <Resource name="jdbc/gdn" auth="Container"
    type="javax.sql.DataSource" driverClassName="sun.jdbc.odbc.JdbcOdbcDriver"
    url="jdbc:odbc:gdn"
    username="system" password="tiger" maxActive="20" maxIdle="10"
    maxWait="-1"/>
    </GlobalNamingResources>
    <!-- A "Service" is a collection of one or more "Connectors" that share
    a single "Container" (and therefore the web applications visible
    within that Container). Normally, that Container is an "Engine",
    but this is not required.
    Note: A "Service" is not itself a "Container", so you may not
    define subcomponents such as "Valves" or "Loggers" at this level.
    -->
    <!-- Define the Tomcat Stand-Alone Service -->
    <Service name="Catalina">
    <!-- A "Connector" represents an endpoint by which requests are received
    and responses are returned. Each Connector passes requests on to the
    associated "Container" (normally an Engine) for processing.
    By default, a non-SSL HTTP/1.1 Connector is established on port 8080.
    You can also enable an SSL HTTP/1.1 Connector on port 8443 by
    following the instructions below and uncommenting the second Connector
    entry. SSL support requires the following steps (see the SSL Config
    HOWTO in the Tomcat 5 documentation bundle for more detailed
    instructions):
    * If your JDK version 1.3 or prior, download and install JSSE 1.0.2 or
    later, and put the JAR files into "$JAVA_HOME/jre/lib/ext".
    * Execute:
    %JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA (Windows)
    $JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA (Unix)
    with a password value of "changeit" for both the certificate and
    the keystore itself.
    By default, DNS lookups are enabled when a web application calls
    request.getRemoteHost(). This can have an adverse impact on
    performance, so you can disable it by setting the
    "enableLookups" attribute to "false". When DNS lookups are disabled,
    request.getRemoteHost() will return the String version of the
    IP address of the remote client.
    -->
    <!-- Define a non-SSL HTTP/1.1 Connector on port 8080 -->
    <Connector
    port="5050" maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
    enableLookups="false" redirectPort="8443" acceptCount="100"
    connectionTimeout="20000" disableUploadTimeout="true" />
    <!-- Note : To disable connection timeouts, set connectionTimeout value
    to 0 -->
         <!-- Note : To use gzip compression you could set the following properties :
                   compression="on"
                   compressionMinSize="2048"
                   noCompressionUserAgents="gozilla, traviata"
                   compressableMimeType="text/html,text/xml"
         -->
    <!-- Define a SSL HTTP/1.1 Connector on port 8443 -->
    <!--
    <Connector port="8443"
    maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
    enableLookups="false" disableUploadTimeout="true"
    acceptCount="100" scheme="https" secure="true"
    clientAuth="false" sslProtocol="TLS" />
    -->
    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8009"
    enableLookups="false" redirectPort="8443" protocol="AJP/1.3" />
    <!-- Define a Proxied HTTP/1.1 Connector on port 8082 -->
    <!-- See proxy documentation for more information about using this. -->
    <!--
    <Connector port="8082"
    maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
    enableLookups="false" acceptCount="100" connectionTimeout="20000"
    proxyPort="80" disableUploadTimeout="true" />
    -->
    <!-- An Engine represents the entry point (within Catalina) that processes
    every request. The Engine implementation for Tomcat stand alone
    analyzes the HTTP headers included with the request, and passes them
    on to the appropriate Host (virtual host). -->
    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Standalone" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <!-- Define the top level container in our container hierarchy -->
    <Engine name="Catalina" defaultHost="localhost">
    <!-- The request dumper valve dumps useful debugging information about
    the request headers and cookies that were received, and the response
    headers and cookies that were sent, for all requests received by
    this instance of Tomcat. If you care only about requests to a
    particular virtual host, or a particular application, nest this
    element inside the corresponding <Host> or <Context> entry instead.
    For a similar mechanism that is portable to all Servlet 2.4
    containers, check out the "RequestDumperFilter" Filter in the
    example application (the source for this filter may be found in
    "$CATALINA_HOME/webapps/examples/WEB-INF/classes/filters").
    Request dumping is disabled by default. Uncomment the following
    element to enable it. -->
    <!--
    <Valve className="org.apache.catalina.valves.RequestDumperValve"/>
    -->
    <!-- Because this Realm is here, an instance will be shared globally -->
    <!-- This Realm uses the UserDatabase configured in the global JNDI
    resources under the key "UserDatabase". Any edits
    that are performed against this UserDatabase are immediately
    available for use by the Realm. -->
    <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
    resourceName="UserDatabase"/>
    <!-- Comment out the old realm but leave here for now in case we
    need to go back quickly -->
    <!--
    <Realm className="org.apache.catalina.realm.MemoryRealm" />
    -->
    <!-- Replace the above Realm with one of the following to get a Realm
    stored in a database and accessed via JDBC -->
    <!--
    <Realm className="org.apache.catalina.realm.JDBCRealm"
    driverName="org.gjt.mm.mysql.Driver"
    connectionURL="jdbc:mysql://localhost/authority"
    connectionName="test" connectionPassword="test"
    userTable="users" userNameCol="user_name" userCredCol="user_pass"
    userRoleTable="user_roles" roleNameCol="role_name" />
    -->
    <!--
    <Realm className="org.apache.catalina.realm.JDBCRealm"
    driverName="oracle.jdbc.driver.OracleDriver"
    connectionURL="jdbc:oracle:thin:@ntserver:1521:ORCL"
    connectionName="scott" connectionPassword="tiger"
    userTable="users" userNameCol="user_name" userCredCol="user_pass"
    userRoleTable="user_roles" roleNameCol="role_name" />
    -->
    <!--
    <Realm className="org.apache.catalina.realm.JDBCRealm"
    driverName="sun.jdbc.odbc.JdbcOdbcDriver"
    connectionURL="jdbc:odbc:CATALINA"
    userTable="users" userNameCol="user_name" userCredCol="user_pass"
    userRoleTable="user_roles" roleNameCol="role_name" />
    -->
    <!-- Define the default virtual host
    Note: XML Schema validation will not work with Xerces 2.2.
    -->
    <Host name="localhost" appBase="webapps"
    unpackWARs="true" autoDeploy="true"
    xmlValidation="false" xmlNamespaceAware="false">
    <!-- Defines a cluster for this node,
    By defining this element, means that every manager will be changed.
    So when running a cluster, only make sure that you have webapps in there
    that need to be clustered and remove the other ones.
    A cluster has the following parameters:
    className = the fully qualified name of the cluster class
    name = a descriptive name for your cluster, can be anything
    mcastAddr = the multicast address, has to be the same for all the nodes
    mcastPort = the multicast port, has to be the same for all the nodes
    mcastBindAddr = bind the multicast socket to a specific address
    mcastTTL = the multicast TTL if you want to limit your broadcast
    mcastSoTimeout = the multicast readtimeout
    mcastFrequency = the number of milliseconds in between sending a "I'm alive" heartbeat
    mcastDropTime = the number a milliseconds before a node is considered "dead" if no heartbeat is received
    tcpThreadCount = the number of threads to handle incoming replication requests, optimal would be the same amount of threads as nodes
    tcpListenAddress = the listen address (bind address) for TCP cluster request on this host,
    in case of multiple ethernet cards.
    auto means that address becomes
    InetAddress.getLocalHost().getHostAddress()
    tcpListenPort = the tcp listen port
    tcpSelectorTimeout = the timeout (ms) for the Selector.select() method in case the OS
    has a wakup bug in java.nio. Set to 0 for no timeout
    printToScreen = true means that managers will also print to std.out
    expireSessionsOnShutdown = true means that
    useDirtyFlag = true means that we only replicate a session after setAttribute,removeAttribute has been called.
    false means to replicate the session after each request.
    false means that replication would work for the following piece of code: (only for SimpleTcpReplicationManager)
    <%
    HashMap map = (HashMap)session.getAttribute("map");
    map.put("key","value");
    %>
    replicationMode = can be either 'pooled', 'synchronous' or 'asynchronous'.
    * Pooled means that the replication happens using several sockets in a synchronous way. Ie, the data gets replicated, then the request return. This is the same as the 'synchronous' setting except it uses a pool of sockets, hence it is multithreaded. This is the fastest and safest configuration. To use this, also increase the nr of tcp threads that you have dealing with replication.
    * Synchronous means that the thread that executes the request, is also the
    thread the replicates the data to the other nodes, and will not return until all
    nodes have received the information.
    * Asynchronous means that there is a specific 'sender' thread for each cluster node,
    so the request thread will queue the replication request into a "smart" queue,
    and then return to the client.
    The "smart" queue is a queue where when a session is added to the queue, and the same session
    already exists in the queue from a previous request, that session will be replaced
    in the queue instead of replicating two requests. This almost never happens, unless there is a
    large network delay.
    -->
    <!--
    When configuring for clustering, you also add in a valve to catch all the requests
    coming in, at the end of the request, the session may or may not be replicated.
    A session is replicated if and only if all the conditions are met:
    1. useDirtyFlag is true or setAttribute or removeAttribute has been called AND
    2. a session exists (has been created)
    3. the request is not trapped by the "filter" attribute
    The filter attribute is to filter out requests that could not modify the session,
    hence we don't replicate the session after the end of this request.
    The filter is negative, ie, anything you put in the filter, you mean to filter out,
    ie, no replication will be done on requests that match one of the filters.
    The filter attribute is delimited by ;, so you can't escape out ; even if you wanted to.
    filter=".*\.gif;.*\.js;" means that we will not replicate the session after requests with the URI
    ending with .gif and .js are intercepted.
    The deployer element can be used to deploy apps cluster wide.
    Currently the deployment only deploys/undeploys to working members in the cluster
    so no WARs are copied upons startup of a broken node.
    The deployer watches a directory (watchDir) for WAR files when watchEnabled="true"
    When a new war file is added the war gets deployed to the local instance,
    and then deployed to the other instances in the cluster.
    When a war file is deleted from the watchDir the war is undeployed locally
    and cluster wide
    -->
    <!--
    <Cluster className="org.apache.catalina.cluster.tcp.SimpleTcpCluster"
    managerClassName="org.apache.catalina.cluster.session.DeltaManager"
    expireSessionsOnShutdown="false"
    useDirtyFlag="true"
    notifyListenersOnReplication="true">
    <Membership
    className="org.apache.catalina.cluster.mcast.McastService"
    mcastAddr="228.0.0.4"
    mcastPort="45564"
    mcastFrequency="500"
    mcastDropTime="3000"/>
    <Receiver
    className="org.apache.catalina.cluster.tcp.ReplicationListener"
    tcpListenAddress="auto"
    tcpListenPort="4001"
    tcpSelectorTimeout="100"
    tcpThreadCount="6"/>
    <Sender
    className="org.apache.catalina.cluster.tcp.ReplicationTransmitter"
    replicationMode="pooled"
    ackTimeout="15000"/>
    <Valve className="org.apache.catalina.cluster.tcp.ReplicationValve"
    filter=".*\.gif;.*\.js;.*\.jpg;.*\.htm;.*\.html;.*\.txt;"/>
    <Deployer className="org.apache.catalina.cluster.deploy.FarmWarDeployer"
    tempDir="/tmp/war-temp/"
    deployDir="/tmp/war-deploy/"
    watchDir="/tmp/war-listen/"
    watchEnabled="false"/>
    </Cluster>
    -->
    <!-- Normally, users must authenticate themselves to each web app
    individually. Uncomment the following entry if you would like
    a user to be authenticated the first time they encounter a
    resource protected by a security constraint, and then have that
    user identity maintained across all web applications contained
    in this virtual host. -->
    <!--
    <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
    -->
    <!-- Access log processes all requests for this virtual host. By
    default, log files are created in the "logs" directory relative to
    $CATALINA_HOME. If you wish, you can specify a different
    directory with the "directory" attribute. Specify either a relative
    (to $CATALINA_HOME) or absolute path to the desired directory.
    -->
    <!--
    <Valve className="org.apache.catalina.valves.AccessLogValve"
    directory="logs" prefix="localhost_access_log." suffix=".txt"
    pattern="common" resolveHosts="false"/>
    -->
    <!-- Access log processes all requests for this virtual host. By
    default, log files are created in the "logs" directory relative to
    $CATALINA_HOME. If you wish, you can specify a different
    directory with the "directory" attribute. Specify either a relative
    (to $CATALINA_HOME) or absolute path to the desired directory.
    This access log implementation is optimized for maximum performance,
    but is hardcoded to support only the "common" and "combined" patterns.
    -->
    <!--
    <Valve className="org.apache.catalina.valves.FastCommonAccessLogValve"
    directory="logs" prefix="localhost_access_log." suffix=".txt"
    pattern="common" resolveHosts="false"/>
    -->
    <Context path="/tdm" docBase="tdm" debug="0" reloadable="true" />
    </Host>
    </Engine>
    </Service>
    </Server>
    I have set the context path to /tdm in the server.xml file. Should this be placed in context.xml?
    My first page in the project is called Homepage.html. To start my project I give http://localhost:5050/tdm/homepage.html
    in a browser. Here I accept a username and password from the user and then do the validation in
    a valid.jsp file, where I connect to the database and check and use jsp:forward to go to next pages
    accordingly. However when I enter the username and password and click Go in the homepage, nothing is
    displayed on the next page. The URL in the browser says valid.jsp but a blank screen appears.
    WHY DOES IT HAPPEN SO? DOES IT MEAN THAT TOMCAT IS NOT RECOGNIZING JAVA IN MY SYSTEM OR IS IT A PROBLEM
    WITH THE DATABASE CONNECTION OR SOMETHING ELSE? I FEEL THAT TOMCAT IS NOT EXECUTING JSP COMMANDS?
    IS IT POSSIBLE?WHY WILL THIS HAPPEN?
    I set the JAVA_HOME and CATALINA_HOME environment to the jdk and tomcat folders resp.
    Is there any other thing that I need to set in classpath? Should I have my project as a
    WAR file in the webapps of TOMCAT or just a folder i.e. directory structure will fine?

  • Shared Connection Pool via Singleton

    I have just started to learn Java (more jsp & servlets) and have been going through "Core Servlets and Java Server Pages" and in there is stuff on connection pooling. The author provides a good a connection pool servlet that can be shared, but as I'm new and don't fully understand how everything works (got a basic idea).
    How do i go about making the following code accessiable via a singleton class?
    ConnectionPool Class
    package sco;
    import java.sql.*;
    import java.util.*;
    /** A class for preallocating, recycling, and managing
    *  JDBC connections.
    *  <P>
    *  Taken from Core Servlets and JavaServer Pages
    *  from Prentice Hall and Sun Microsystems Press,
    *  http://www.coreservlets.com/.
    *  &copy; 2000 Marty Hall; may be freely used or adapted.
    public class ConnectionPool implements Runnable {
      private String driver, url, username, password;
      private int maxConnections;
      private boolean waitIfBusy;
      private Vector availableConnections, busyConnections;
      private boolean connectionPending = false;
      public ConnectionPool(String driver, String url,
                            String username, String password,
                            int initialConnections,
                            int maxConnections,
                            boolean waitIfBusy)
          throws SQLException {
        this.driver = driver;
        this.url = url;
        this.username = username;
        this.password = password;
        this.maxConnections = maxConnections;
        this.waitIfBusy = waitIfBusy;
        if (initialConnections > maxConnections) {
          initialConnections = maxConnections;
        availableConnections = new Vector(initialConnections);
        busyConnections = new Vector();
        for(int i=0; i<initialConnections; i++) {
          availableConnections.addElement(makeNewConnection());
      public synchronized Connection getConnection()
          throws SQLException {
        if (!availableConnections.isEmpty()) {
          Connection existingConnection =
            (Connection)availableConnections.lastElement();
          int lastIndex = availableConnections.size() - 1;
          availableConnections.removeElementAt(lastIndex);
          // If connection on available list is closed (e.g.,
          // it timed out), then remove it from available list
          // and repeat the process of obtaining a connection.
          // Also wake up threads that were waiting for a
          // connection because maxConnection limit was reached.
          if (existingConnection.isClosed()) {
            notifyAll(); // Freed up a spot for anybody waiting
            return(getConnection());
          } else {
            busyConnections.addElement(existingConnection);
            return(existingConnection);
        } else {
          // Three possible cases:
          // 1) You haven't reached maxConnections limit. So
          //    establish one in the background if there isn't
          //    already one pending, then wait for
          //    the next available connection (whether or not
          //    it was the newly established one).
          // 2) You reached maxConnections limit and waitIfBusy
          //    flag is false. Throw SQLException in such a case.
          // 3) You reached maxConnections limit and waitIfBusy
          //    flag is true. Then do the same thing as in second
          //    part of step 1: wait for next available connection.
          if ((totalConnections() < maxConnections) &&
              !connectionPending) {
            makeBackgroundConnection();
          } else if (!waitIfBusy) {
            throw new SQLException("Connection limit reached");
          // Wait for either a new connection to be established
          // (if you called makeBackgroundConnection) or for
          // an existing connection to be freed up.
          try {
            wait();
          } catch(InterruptedException ie) {}
          // Someone freed up a connection, so try again.
          return(getConnection());
      // You can't just make a new connection in the foreground
      // when none are available, since this can take several
      // seconds with a slow network connection. Instead,
      // start a thread that establishes a new connection,
      // then wait. You get woken up either when the new connection
      // is established or if someone finishes with an existing
      // connection.
      private void makeBackgroundConnection() {
        connectionPending = true;
        try {
          Thread connectThread = new Thread(this);
          connectThread.start();
        } catch(OutOfMemoryError oome) {
          // Give up on new connection
      public void run() {
        try {
          Connection connection = makeNewConnection();
          synchronized(this) {
            availableConnections.addElement(connection);
            connectionPending = false;
            notifyAll();
        } catch(Exception e) { // SQLException or OutOfMemory
          // Give up on new connection and wait for existing one
          // to free up.
      // This explicitly makes a new connection. Called in
      // the foreground when initializing the ConnectionPool,
      // and called in the background when running.
      private Connection makeNewConnection()
          throws SQLException {
        try {
          // Load database driver if not already loaded
          Class.forName(driver);
          // Establish network connection to database
          Connection connection =
            DriverManager.getConnection(url, username, password);
          return(connection);
        } catch(ClassNotFoundException cnfe) {
          // Simplify try/catch blocks of people using this by
          // throwing only one exception type.
          throw new SQLException("Can't find class for driver: " +
                                 driver);
      public synchronized void free(Connection connection) {
        busyConnections.removeElement(connection);
        availableConnections.addElement(connection);
        // Wake up threads that are waiting for a connection
        notifyAll();
      public synchronized int totalConnections() {
        return(availableConnections.size() +
               busyConnections.size());
      /** Close all the connections. Use with caution:
       *  be sure no connections are in use before
       *  calling. Note that you are not <I>required</I> to
       *  call this when done with a ConnectionPool, since
       *  connections are guaranteed to be closed when
       *  garbage collected. But this method gives more control
       *  regarding when the connections are closed.
      public synchronized void closeAllConnections() {
        closeConnections(availableConnections);
        availableConnections = new Vector();
        closeConnections(busyConnections);
        busyConnections = new Vector();
      private void closeConnections(Vector connections) {
        try {
          for(int i=0; i<connections.size(); i++) {
            Connection connection =
              (Connection)connections.elementAt(i);
            if (!connection.isClosed()) {
              connection.close();
        } catch(SQLException sqle) {
          // Ignore errors; garbage collect anyhow
      public synchronized String toString() {
        String info =
          "ConnectionPool(" + url + "," + username + ")\n" +
          ", available=" + availableConnections.size() + "\n" +
          ", busy=" + busyConnections.size() + "\n" +
          ", max=" + maxConnections;
        return(info);
    ScoPool Class (singleton to access the connection pool)
    package sco;
    public class ScoPool extends ConnectionPool {
      private ScoPool pool = null;
      private ScoPool() {
        super(); // Call parent constructor
      public static synchronized ScoPool getInstance() {
        if(pool == null) {
          pool = new ScoPool();
        return(pool);
    }Please help a newbie.

    Figured it out.
    package sco;
    import java.sql.SQLException;
    public class ScoPool extends ConnectionPool {
      private static ScoPool pool;
      private ScoPool(String driver, String url, String username, String password,
                      int initialConnections, int maxConnections, boolean waitIfBusy) throws SQLException {
        super(driver, url, username, password, initialConnections, maxConnections, waitIfBusy); // Call parent constructor
      public static synchronized ScoPool getInstance() {
        if(pool == null) {
          String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
          String url = "jdbc:microsoft:sqlserver://MIM-W0432:1433;DatabaseName=sco";
          String username = "sco_user";
          String password = "123";
          int initCon = 5;
          int maxCon = 10;
          boolean waitIfBusy = true;
          try {
            pool = new ScoPool(driver, url, username, password, initCon, maxCon, waitIfBusy);
          catch(SQLException sqle) {
        return pool;
    }

  • How to populate data before displaying jsp in JSF ?

    I have the following situation :
    In my app, i have a couple of left-navigation menus, when i click on one of them, i need to show some history data. So, i first need to call a managed bean on click of the link, fetch data and forward to history jsp page.
    How do call the managed bean directly (like struts action page) before going to JSP first ? Whenever i give a link to "something.faces", it goes to the jsp directly ?

    There are two solutions on my mind. The first is to use the Shale ViewController where you got prerender() method and in it you could fetch the data. The second solution is to fetch the data in the getter method of your property but remember that the getter method could be invoked more than once per request so putting expencive code in it could be dangerous. Use singleton instance of the fetched property, something like:
    getMyProperty() {
    if (myProperty == null) {
    .... fetch the data
    return myProperty;
    }

  • Hi how to add new folders under root for jsp in tomcat4.1.18

    hi,
    previsously i used tomcat3.3 and tomcat4.1.12 run sucessfully.
    now i downloed jakartha_tomcat4.1.18,
    i am running sample succesfuly direcly under root.
    now i want my some jsp appilcationes to run under xyz,pqr folders
    here my jsp files are abc.jsp,fgh.jsp while running file url like this
    http://localhost:8080/xyz/abc.jsp
    http://localhost:8080/pqr/fgh.jsp
    while running url server not locate the files.
    where i add these xyz and pqr folders in server.xml.
    here my server.xml like this any one can modify this
    <!-- Example Server Configuration File -->
    <!-- Note that component elements are nested corresponding to their
    parent-child relationships with each other -->
    <!-- A "Server" is a singleton element that represents the entire JVM,
    which may contain one or more "Service" instances. The Server
    listens for a shutdown command on the indicated port.
    Note: A "Server" is not itself a "Container", so you may not
    define subcomponents such as "Valves" or "Loggers" at this level.
    -->
    <Server port="8005" shutdown="SHUTDOWN" debug="0">
    <!-- Comment these entries out to disable JMX MBeans support -->
    <!-- You may also configure custom components (e.g. Valves/Realms) by
    including your own mbean-descriptor file(s), and setting the
    "descriptors" attribute to point to a ';' seperated list of paths
    (in the ClassLoader sense) of files to add to the default list.
    e.g. descriptors="/com/myfirm/mypackage/mbean-descriptor.xml"
    -->
    <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener"
    debug="0"/>
    <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"
    debug="0"/>
    <!-- Global JNDI resources -->
    <GlobalNamingResources>
    <!-- Test entry for demonstration purposes -->
    <Environment name="simpleValue" type="java.lang.Integer" value="30"/>
    <!-- Editable user database that can also be used by
    UserDatabaseRealm to authenticate users -->
    <Resource name="UserDatabase" auth="Container"
    type="org.apache.catalina.UserDatabase"
    description="User database that can be updated and saved">
    </Resource>
    <ResourceParams name="UserDatabase">
    <parameter>
    <name>factory</name>
    <value>org.apache.catalina.users.MemoryUserDatabaseFactory</value>
    </parameter>
    <parameter>
    <name>pathname</name>
    <value>conf/tomcat-users.xml</value>
    </parameter>
    </ResourceParams>
    </GlobalNamingResources>
    <!-- A "Service" is a collection of one or more "Connectors" that share
    a single "Container" (and therefore the web applications visible
    within that Container). Normally, that Container is an "Engine",
    but this is not required.
    Note: A "Service" is not itself a "Container", so you may not
    define subcomponents such as "Valves" or "Loggers" at this level.
    -->
    <!-- Define the Tomcat Stand-Alone Service -->
    <Service name="Tomcat-Standalone">
    <!-- A "Connector" represents an endpoint by which requests are received
    and responses are returned. Each Connector passes requests on to the
    associated "Container" (normally an Engine) for processing.
    By default, a non-SSL HTTP/1.1 Connector is established on port 8080.
    You can also enable an SSL HTTP/1.1 Connector on port 8443 by
    following the instructions below and uncommenting the second Connector
    entry. SSL support requires the following steps (see the SSL Config
    HOWTO in the Tomcat 4.0 documentation bundle for more detailed
    instructions):
    * Download and install JSSE 1.0.2 or later, and put the JAR files
    into "$JAVA_HOME/jre/lib/ext".
    * Execute:
    %JAVA_HOME%\bin\keytool -genkey -alias tomcat -keyalg RSA (Windows)
    $JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA (Unix)
    with a password value of "changeit" for both the certificate and
    the keystore itself.
    By default, DNS lookups are enabled when a web application calls
    request.getRemoteHost(). This can have an adverse impact on
    performance, so you can disable it by setting the
    "enableLookups" attribute to "false". When DNS lookups are disabled,
    request.getRemoteHost() will return the String version of the
    IP address of the remote client.
    -->
    <!-- Define a non-SSL Coyote HTTP/1.1 Connector on port 8080 -->
    <Connector className="org.apache.coyote.tomcat4.CoyoteConnector"
    port="8080" minProcessors="5" maxProcessors="75"
    enableLookups="true" redirectPort="8443"
    acceptCount="100" debug="0" connectionTimeout="20000"
    useURIValidationHack="false" disableUploadTimeout="true" />
    <!-- Note : To disable connection timeouts, set connectionTimeout value
    to -1 -->
    <!-- Define a SSL Coyote HTTP/1.1 Connector on port 8443 -->
    <!--
    <Connector className="org.apache.coyote.tomcat4.CoyoteConnector"
    port="8443" minProcessors="5" maxProcessors="75"
    enableLookups="true"
         acceptCount="100" debug="0" scheme="https" secure="true"
    useURIValidationHack="false" disableUploadTimeout="true">
    <Factory className="org.apache.coyote.tomcat4.CoyoteServerSocketFactory"
    clientAuth="false" protocol="TLS" />
    </Connector>
    -->
    <!-- Define a Coyote/JK2 AJP 1.3 Connector on port 8009 -->
    <Connector className="org.apache.coyote.tomcat4.CoyoteConnector"
    port="8009" minProcessors="5" maxProcessors="75"
    enableLookups="true" redirectPort="8443"
    acceptCount="10" debug="0" connectionTimeout="0"
    useURIValidationHack="false"
    protocolHandlerClassName="org.apache.jk.server.JkCoyoteHandler"/>
    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <!--
    <Connector className="org.apache.ajp.tomcat4.Ajp13Connector"
    port="8009" minProcessors="5" maxProcessors="75"
    acceptCount="10" debug="0"/>
    -->
    <!-- Define a Proxied HTTP/1.1 Connector on port 8082 -->
    <!-- See proxy documentation for more information about using this. -->
    <!--
    <Connector className="org.apache.coyote.tomcat4.CoyoteConnector"
    port="8082" minProcessors="5" maxProcessors="75"
    enableLookups="true"
    acceptCount="100" debug="0" connectionTimeout="20000"
    proxyPort="80" useURIValidationHack="false"
    disableUploadTimeout="true" />
    -->
    <!-- Define a non-SSL legacy HTTP/1.1 Test Connector on port 8083 -->
    <!--
    <Connector className="org.apache.catalina.connector.http.HttpConnector"
    port="8083" minProcessors="5" maxProcessors="75"
    enableLookups="true" redirectPort="8443"
    acceptCount="10" debug="0" />
    -->
    <!-- Define a non-SSL HTTP/1.0 Test Connector on port 8084 -->
    <!--
    <Connector className="org.apache.catalina.connector.http10.HttpConnector"
    port="8084" minProcessors="5" maxProcessors="75"
    enableLookups="true" redirectPort="8443"
    acceptCount="10" debug="0" />
    -->
    <!-- An Engine represents the entry point (within Catalina) that processes
    every request. The Engine implementation for Tomcat stand alone
    analyzes the HTTP headers included with the request, and passes them
    on to the appropriate Host (virtual host). -->
    <!-- You should set jvmRoute to support load-balancing via JK/JK2 ie :
    <Engine name="Standalone" defaultHost="localhost" debug="0" jmvRoute="jvm1">
    -->
    <!-- Define the top level container in our container hierarchy -->
    <Engine name="Standalone" defaultHost="localhost" debug="0">
    <!-- The request dumper valve dumps useful debugging information about
    the request headers and cookies that were received, and the response
    headers and cookies that were sent, for all requests received by
    this instance of Tomcat. If you care only about requests to a
    particular virtual host, or a particular application, nest this
    element inside the corresponding <Host> or <Context> entry instead.
    For a similar mechanism that is portable to all Servlet 2.3
    containers, check out the "RequestDumperFilter" Filter in the
    example application (the source for this filter may be found in
    "$CATALINA_HOME/webapps/examples/WEB-INF/classes/filters").
    Request dumping is disabled by default. Uncomment the following
    element to enable it. -->
    <!--
    <Valve className="org.apache.catalina.valves.RequestDumperValve"/>
    -->
    <!-- Global logger unless overridden at lower levels -->
    <Logger className="org.apache.catalina.logger.FileLogger"
    prefix="catalina_log." suffix=".txt"
    timestamp="true"/>
    <!-- Because this Realm is here, an instance will be shared globally -->
    <!-- This Realm uses the UserDatabase configured in the global JNDI
    resources under the key "UserDatabase". Any edits
    that are performed against this UserDatabase are immediately
    available for use by the Realm. -->
    <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
    debug="0" resourceName="UserDatabase"/>
    <!-- Comment out the old realm but leave here for now in case we
    need to go back quickly -->
    <!--
    <Realm className="org.apache.catalina.realm.MemoryRealm" />
    -->
    <!-- Replace the above Realm with one of the following to get a Realm
    stored in a database and accessed via JDBC -->
    <!--
    <Realm className="org.apache.catalina.realm.JDBCRealm" debug="99"
    driverName="org.gjt.mm.mysql.Driver"
    connectionURL="jdbc:mysql://localhost/authority"
    connectionName="test" connectionPassword="test"
    userTable="users" userNameCol="user_name" userCredCol="user_pass"
    userRoleTable="user_roles" roleNameCol="role_name" />
    -->
    <!--
    <Realm className="org.apache.catalina.realm.JDBCRealm" debug="99"
    driverName="oracle.jdbc.driver.OracleDriver"
    connectionURL="jdbc:oracle:thin:@ntserver:1521:ORCL"
    connectionName="scott" connectionPassword="tiger"
    userTable="users" userNameCol="user_name" userCredCol="user_pass"
    userRoleTable="user_roles" roleNameCol="role_name" />
    -->
    <!--
    <Realm className="org.apache.catalina.realm.JDBCRealm" debug="99"
    driverName="sun.jdbc.odbc.JdbcOdbcDriver"
    connectionURL="jdbc:odbc:CATALINA"
    userTable="users" userNameCol="user_name" userCredCol="user_pass"
    userRoleTable="user_roles" roleNameCol="role_name" />
    -->
    <!-- Define the default virtual host -->
    <Host name="localhost" debug="0" appBase="webapps"
    unpackWARs="true" autoDeploy="true">
    <!-- Normally, users must authenticate themselves to each web app
    individually. Uncomment the following entry if you would like
    a user to be authenticated the first time they encounter a
    resource protected by a security constraint, and then have that
    user identity maintained across all web applications contained
    in this virtual host. -->
    <!--
    <Valve className="org.apache.catalina.authenticator.SingleSignOn"
    debug="0"/>
    -->
    <!-- Access log processes all requests for this virtual host. By
    default, log files are created in the "logs" directory relative to
    $CATALINA_HOME. If you wish, you can specify a different
    directory with the "directory" attribute. Specify either a relative
    (to $CATALINA_HOME) or absolute path to the desired directory.
    -->
    <!--
    <Valve className="org.apache.catalina.valves.AccessLogValve"
    directory="logs" prefix="localhost_access_log." suffix=".txt"
    pattern="common" resolveHosts="false"/>
    -->
    <!-- Logger shared by all Contexts related to this virtual host. By
    default (when using FileLogger), log files are created in the "logs"
    directory relative to $CATALINA_HOME. If you wish, you can specify
    a different directory with the "directory" attribute. Specify either a
    relative (to $CATALINA_HOME) or absolute path to the desired
    directory.-->
    <Logger className="org.apache.catalina.logger.FileLogger"
    directory="logs" prefix="localhost_log." suffix=".txt"
         timestamp="true"/>
    <!-- Define properties for each web application. This is only needed
    if you want to set non-default properties, or have web application
    document roots in places other than the virtual host's appBase
    directory. -->
    <!-- Tomcat Root Context -->
    <Context path="" docBase="ROOT" debug="0"/>
    <!-- Tomcat Examples Context -->
    <Context path="/examples" docBase="examples" debug="0"
    reloadable="true" crossContext="true">
    <Logger className="org.apache.catalina.logger.FileLogger"
    prefix="localhost_examples_log." suffix=".txt"
         timestamp="true"/>
    <Ejb name="ejb/EmplRecord" type="Entity"
    home="com.wombat.empl.EmployeeRecordHome"
    remote="com.wombat.empl.EmployeeRecord"/>
    <!-- If you wanted the examples app to be able to edit the
    user database, you would uncomment the following entry.
    Of course, you would want to enable security on the
    application as well, so this is not done by default!
    The database object could be accessed like this:
    Context initCtx = new InitialContext();
    Context envCtx = (Context) initCtx.lookup("java:comp/env");
    UserDatabase database =
    (UserDatabase) envCtx.lookup("userDatabase");
    -->
    <!--
    <ResourceLink name="userDatabase" global="UserDatabase"
    type="org.apache.catalina.UserDatabase"/>
    -->
    <!-- PersistentManager: Uncomment the section below to test Persistent
              Sessions.
    saveOnRestart: If true, all active sessions will be saved
    to the Store when Catalina is shutdown, regardless of
    other settings. All Sessions found in the Store will be
    loaded on startup. Sessions past their expiration are
    ignored in both cases.
    maxActiveSessions: If 0 or greater, having too many active
    sessions will result in some being swapped out. minIdleSwap
    limits this. -1 or 0 means unlimited sessions are allowed.
    If it is not possible to swap sessions new sessions will
    be rejected.
    This avoids thrashing when the site is highly active.
    minIdleSwap: Sessions must be idle for at least this long
    (in seconds) before they will be swapped out due to
    activity.
    0 means sessions will almost always be swapped out after
    use - this will be noticeably slow for your users.
    maxIdleSwap: Sessions will be swapped out if idle for this
    long (in seconds). If minIdleSwap is higher, then it will
    override this. This isn't exact: it is checked periodically.
    -1 means sessions won't be swapped out for this reason,
    although they may be swapped out for maxActiveSessions.
    If set to >= 0, guarantees that all sessions found in the
    Store will be loaded on startup.
    maxIdleBackup: Sessions will be backed up (saved to the Store,
    but left in active memory) if idle for this long (in seconds),
    and all sessions found in the Store will be loaded on startup.
    If set to -1 sessions will not be backed up, 0 means they
    should be backed up shortly after being used.
    To clear sessions from the Store, set maxActiveSessions, maxIdleSwap,
    and minIdleBackup all to -1, saveOnRestart to false, then restart
    Catalina.
    -->
              <!--
    <Manager className="org.apache.catalina.session.PersistentManager"
    debug="0"
    saveOnRestart="true"
    maxActiveSessions="-1"
    minIdleSwap="-1"
    maxIdleSwap="-1"
    maxIdleBackup="-1">
    <Store className="org.apache.catalina.session.FileStore"/>
    </Manager>
              -->
    <Environment name="maxExemptions" type="java.lang.Integer"
    value="15"/>
    <Parameter name="context.param.name" value="context.param.value"
    override="false"/>
    <Resource name="jdbc/EmployeeAppDb" auth="SERVLET"
    type="javax.sql.DataSource"/>
    <ResourceParams name="jdbc/EmployeeAppDb">
    <parameter><name>username</name><value>sa</value></parameter>
    <parameter><name>password</name><value></value></parameter>
    <parameter><name>driverClassName</name>
    <value>org.hsql.jdbcDriver</value></parameter>
    <parameter><name>url</name>
    <value>jdbc:HypersonicSQL:database</value></parameter>
    </ResourceParams>
    <Resource name="mail/Session" auth="Container"
    type="javax.mail.Session"/>
    <ResourceParams name="mail/Session">
    <parameter>
    <name>mail.smtp.host</name>
    <value>localhost</value>
    </parameter>
    </ResourceParams>
    <ResourceLink name="linkToGlobalResource"
    global="simpleValue"
    type="java.lang.Integer"/>
    </Context>
    </Host>
    </Engine>
    </Service>
    <!-- The MOD_WEBAPP connector is used to connect Apache 1.3 with Tomcat 4.0
    as its servlet container. Please read the README.txt file coming with
    the WebApp Module distribution on how to build it.
    (Or check out the "jakarta-tomcat-connectors/webapp" CVS repository)
    To configure the Apache side, you must ensure that you have the
    "ServerName" and "Port" directives defined in "httpd.conf". Then,
    lines like these to the bottom of your "httpd.conf" file:
    LoadModule webapp_module libexec/mod_webapp.so
    WebAppConnection warpConnection warp localhost:8008
    WebAppDeploy examples warpConnection /examples/
    The next time you restart Apache (after restarting Tomcat, if needed)
    the connection will be established, and all applications you make
    visible via "WebAppDeploy" directives can be accessed through Apache.
    -->
    <!-- Define an Apache-Connector Service -->
    <!--
    <Service name="Tomcat-Apache">
    <Connector className="org.apache.catalina.connector.warp.WarpConnector"
    port="8008" minProcessors="5" maxProcessors="75"
    enableLookups="true" appBase="webapps"
    acceptCount="10" debug="0"/>
    <Engine className="org.apache.catalina.connector.warp.WarpEngine"
    name="Apache" debug="0">
    <Logger className="org.apache.catalina.logger.FileLogger"
    prefix="apache_log." suffix=".txt"
    timestamp="true"/>
    <Realm className="org.apache.catalina.realm.MemoryRealm" />
    </Engine>
    </Service>
    -->
    </Server>
    ==========
    any one may modify above one
    thanks
    pullareddyj

    As the server.xml is big enough, I took the minimum portion of it. Hope u can proceed with it.
    <!-- Tomcat Root Context -->
    <Context path="" docBase="ROOT" debug="0"/>
    <!-- New contexts -->
    <Context path="/xyz" docBase="pathTo_xyz" debug="0" crossContext="true"/>
    <Context path="/pqr" docBase="pathTo_pqr" debug="0" crossContext="true"/>
    <!-- Tomcat Examples Context -->
    <Context path="/examples" docBase="examples" debug="0"
    reloadable="true" crossContext="true">
    You should also provide a WEB-INF folder under pqr or xyz folder.
    You should also provide a web.xml file under each WEB-INF folder.
    The minimal web.xml is
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/j2ee/dtd/web-app_2_3.dtd">
    <web-app>
    </web-app>
    That's it. Try it out. Hope it is OK.
    Hafizur Rahman
    SCJP

  • Singleton

    I have written a classic Singleton which appears to work fine. One issue bothers me. I wish to collect error messages and return them to the caller rather than throw the error(s). I am concerned that given the single instance of this class, there could be -conflict- in generation of these error messages ....in other words, could caller1 get /see error messages from caller2 ....this code is running in a JAVA class as part of a JSP / Struts environment ....
    Rod .
    public class SingleClass {
    // Sample usage:
    // SingleClass.getInstance().setExceptionList();
    // X509Certificate cert = SingleClass.getInstance().getCACert ("xxx");
    // SingleClass.getInstance().getExceptionList();
    private SingleClass() {
    // Define our security provider
    Security.addProvider(new BouncyCastleProvider());
    * A handle to the unique instance.
    private static SingleClass _instance = null;
    // Errors Collection
    private ArrayList EXCEPTIONLIST;
    // Our cache of CA Certs
    private static HashMap cachedCerts = null;
    // How long are cache entries valid - 5 days default
    private static long cacheLife = 5 * 24 * 60 * 60 * 1000;
    public static void clearCache() {
    cachedCerts = null;
    public static SingleClass getInstance() {
    if ( _instance == null ) {
    _instance = new  SingleClass();
    return _instance;
    public ArrayList getExceptionList() {
    return EXCEPTIONLIST;
    public void setExceptionList() {
    EXCEPTIONLIST = new ArrayList();
    public X509Certificate getCACert(String caCertDN) {
    X509Certificate cert = null;
    if ( somecondition ) {
    // generate an error message
    EXCEPTIONLIST.add(msgParams);
    return cert;
    etc.

    could caller1 get /see error messages from caller2 Well yes. Thats the point of a singleton isn't it? There is only one instance, shared by all the callers. If you want each caller to store their own error messages, a singleton is not the way to do it.
    If you are using Struts, why are you not using the Messages/Errors functionality provided there?

  • JSP tags for managing MBeans??

    Hi,
    I'm trying to build a GUI for managing a custom MBean. The MBean implementation is a wrapper for a singleton class (specifically, a Configuration class for a web app). I've tried using WebJMX, but the problem there is that it relies heavily on MX4J, and has not kept up with JMX advances in the last two years (MX4J is a bit ahead of weblogic 8.1).
    Just as there is a set of console extension jsp tags, I suspect that a set of JSP tags exists for the developers of the Weblogic console to write their JSP pages to manage the weblogic MBeans. I coud just try to figure out the pattern of the INPUT and FORM tags in the html, but that leaves me with a possibly-inaccurate, version-dependent, non-dynamically-generated page to manage one MBean.
    Does such a set exist? Could someone point me to any information about how to use such a set of tags?
    I would like to be able to have the JSP I use for my console extension display an interface for modifying MBean configurable fields and executing MBean operations. What would the best way be to do this? I do not want to embed the Sun JMX RI in my web-app and launch a separate HtmlAdaptor listening on a different port. I would like the admin to the MBean be accessible through (and only through) the weblogic console.
    Thanks in advance for the help,
    Matt Geis

    Hi,
    I'm trying to build a GUI for managing a custom MBean. The MBean implementation is a wrapper for a singleton class (specifically, a Configuration class for a web app). I've tried using WebJMX, but the problem there is that it relies heavily on MX4J, and has not kept up with JMX advances in the last two years (MX4J is a bit ahead of weblogic 8.1).
    Just as there is a set of console extension jsp tags, I suspect that a set of JSP tags exists for the developers of the Weblogic console to write their JSP pages to manage the weblogic MBeans. I coud just try to figure out the pattern of the INPUT and FORM tags in the html, but that leaves me with a possibly-inaccurate, version-dependent, non-dynamically-generated page to manage one MBean.
    Does such a set exist? Could someone point me to any information about how to use such a set of tags?
    I would like to be able to have the JSP I use for my console extension display an interface for modifying MBean configurable fields and executing MBean operations. What would the best way be to do this? I do not want to embed the Sun JMX RI in my web-app and launch a separate HtmlAdaptor listening on a different port. I would like the admin to the MBean be accessible through (and only through) the weblogic console.
    Thanks in advance for the help,
    Matt Geis

  • Object living with servlet/jsp container

    How do I make an Object live until the servlet container lives? I mean I want an Object to be instantiated once in the lifetime of the webserver session and its has to be singleton and should live alive until the webserver dies? How can I make this possible? I should be able to keep that object alive even if any no references are made to the object. Moreover I should be able to access that object from any java class on that webserver?

    You can't do this in memory. The easiest thing to do would be to read/write the persistant data you need from disk.
    Anything your JSP or servlet creates in memory will be cleared when it is done serving the request.

  • Anybody using Hypersonic SQL in JSP?

    Hello,
    Does anybody use Hypersonic SQL?
    I implement a guestbook system with JSP that
    saves data in Hypersonic SQL. This system
    runs on www.mycgiserver.com. My JSP program
    has thread safe option set to false to make
    sure one thread is reading and writing the database
    at a time. However, every once in a while, the
    database will be wiped out mysteriously.
    So I am just wondering that this happens to
    anyone else? Is this a Hypersonic SQL's bug
    or it's the server that goofs up or I did something
    wrong with the JSP setting? Any ideas or
    comments please? Thanks !!!

    Hi there!
    I use Hypersonic locally and on mycgiserver.com. Luckilly, I haven't encountered your problems so far. I use a similar approach, I have a bean that handles a singleton-connection to the DB, and that will queue up all requests. But so far , I haven't had that much load on the app, so maybe I'll get back in this matter, with the same problem... Anyone att mycgiserver that had an id�a?
    regards
    Markus

  • How to automate task in jsp?

    I want to create an sms messaging website using jsp. The sms i believe would be ez, i would just have to use sockets in a bean. However there is a specific functionality i want to implement where my website would send a dummy sms message every 5 minutes to the sms server just to test what speed that server is accepting messages at. This way i can display the server speed to users when the come to my site. My problem is i am not sure how to implement this functionality in jsp. It is a process that needs to happen like a new thread. It should happen whether or not people are visiting the website and it needs to happed every 5 minutes. I am wondering if this functionality could only be setup by my webserver or is there some way in jsp i could use a bean to do this.
    Any assistance would be greatly appreciated

    could the same thing be done with a jsp page instead of a servlet?The load on startup part, I'm not sure about. If you only wanted to wait til the first person hits a page, or just have a page that must be hit first on startup of the server to get the thread going, you could do that. But that requires direct user interaction to start things off....
    As for examples....
    In web.xml, you define a servlet and servlet mapping.
    <servlet>
         <servlet-name>smsinit</servlet-name>
         <servlet-class>com.pckg.SMSInitServlet</servlet-class>
         <init-param>
              <param-name>config</param-name>
              <param-value>/WEB-INF/sms-config.xml</param-value>
         </init-param>
         <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
         <servlet-name>smsinit</servlet-name>
         <url-pattern>sms.init</url-pattern>
    </servlet-mapping>So that means that if the URL contains "sms.init", the smsinit servlet will be invoked. You probably don't need worry about that, if all you want is something that will load when the server starts. For that, that's what "load-on-startup" is for. The number value has to do with defining load order for multiple servlets. If left out, the servlet isn't initialized til the first time it's called via a URL. Otherwise, any number will do (for all practical purposes). The init-param config is useful if you need to define a file or some parameter that you can use on init to get some other information.
    As for the servlet itself
    package com.pckg;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class SMSInitServlet extends HttpServlet {
         private ServletContext application = null;
         public void init(ServletConfig config) throws ServletException {
              super.init(config);
              application = config.getServletContext();
              String config = application.getInitParameter("config");
              File configFile = new File(application.getRealPath(config));
              // read the file or whatever....
              // start your thread class running and maybe put it in application
              // or pass the thread the application object which it could store
              // information in, or just have the thread use static methods/fields
              // or a singleton instance or something like that. 
              // the advantage to using the application scope is it limits it to being
              // accessed to JSP pages or other servlets within the web application only
         public void doGet(HttpServletRequest request, HttpServletResponse response)
                       throws ServletException, IOException {
              doPost(request, response);
         public void doPost(HttpServletRequest request, HttpServletResponse response)
                       throws ServletException, IOException {
              // do something here...  or nothing, if you want.
    }

  • Declaring public class in JSP environment.

    Can anybody please tell me, what technical implication can occur, if we declare a public java class inside JSP.
    The scenario is -
    I have a JSP file used to display the results in table format.
    Before displaying the table, a public class is defined in the same JSP.
    Inside the scriptlet, the object is instantiated (using 'new' keyword).
    That object is used to populate the table.
    I know that according to the MVC architecture, the presentation logic should not be intermingled with the business logic. But I wanted to know whether any 'technical' problems we can face because of this.
    For e.g. Synchronization problem or singleton object creation problem etc.

    Yes its like a inner class, and will be available only to the current JSP.
    The code structure is somewhat like this -
    <%!
    public class SearchCN{
         String strUserName;
         String strPassword;
         Context context = null;
    %>
    <%
    SearchCN searchObject = new SearchCN();
    obj.connect();
    %>
    Now in such a scenario, I can think of some causes like, if N no of users open the same JSP, then N connections will get created. Connection sharing which could have been implemented for better performance is not possible.
    Can you give any additional inputs?

  • Best way to call EJBs from JavaBeans/JSP

    Does anyone have a favorite way for getting EJB data from a JavaBean into
              your JSPs?
              I'm looking for a way of caching the EJBHome references so the beans don't
              have to do a lookup on each page, each time they are called.
              Thanks,
              -TB
              

    How does this HelperClass keep the references cached after it looks them up?
              Is it a singleton object, or does it keep the references in static fields?
              "Argyn Kuketayev" <[email protected]> wrote in message
              news:3b1e468b$[email protected]..
              > make a HelperClass, which will have a method getXXXHome()
              > inside the Helper class you may implement cashing.
              >
              > thanks,
              > Argyn
              >
              > T. Bailey wrote in message <[email protected]>...
              > >Does anyone have a favorite way for getting EJB data from a JavaBean into
              > >your JSPs?
              > >
              > >I'm looking for a way of caching the EJBHome references so the beans
              don't
              > >have to do a lookup on each page, each time they are called.
              > >
              > >Thanks,
              > >-TB
              > >
              > >
              >
              >
              

  • Singleton object in clustered enviornment

    Hi,
              In my web application which is deployed in clustered enviornment, I am facing problem for singleton object.
              I need to share object among all servers in the clustered.
              I am using weblogic server 9.2. I have tried its Singleton services, but it doesnt work as expected.
              what could be other solution to solve the problem?

    No. If you need this type of functionality, use Coherence.
              http://www.tangosol.com/coherence.jsp
              Peace,
              Cameron Purdy
              Tangosol, Inc.
              http://www.tangosol.com/coherence.jsp
              Tangosol Coherence: Clustered Replicated Cache for Weblogic
              "Ferruccio" <[email protected]> wrote in message
              news:[email protected]..
              > Hi,
              > I have a very basic question. In a WebLogic clustered
              > environment, is a Singleton replicated? In other words, if the
              > mySingleton on node A in a cluster is updated with a piece of data,
              > will this show in the mySingleton in node B?
              >
              > Thanks
              >
              > Ciao
              > Ferruccio
              

  • Simple caching in singleton DAO

    Suppose I was to use a DAO like this in a web application. Different threads would be concurrently accessing this code from different servlets, struts actions, JSP pages, whatever.
    import java.util.Map;
    import java.util.HashMap;
    public class CacheSingletonDAO {
         private static Map items = new HashMap();
         //----- Singleton Methods --------------------------------------------------
         private static final CacheSingletonDAO instance = new CacheSingletonDAO();
         private CacheSingletonDAO() {
              items.put("1","foo");
              items.put("2","bar");
         public static CacheSingletonDAO getInstance() {
              return instance;
         //----- Public Methods -----------------------------------------------------
         public String getItem(String key) {
              Object obj = items.get(key);
              if(obj != null && obj instanceof String) {
                   return (String)obj;
              } else {
                   return null;
         public Map getItems() {
              return items;
         public void addItem(String key, String item) {
              items.put(key,item);
    }The code here is over simplified. For a real implementation of this, there would most likely be a private getItemsFromDB() method that the private constructor would call. I would also have a method like refreshCache() that would call the getItemsFromDB() method, so that I could call that to update the items HashMap with whatever is in the database. The addItem(String, String) method would first store the item in a database, then put item in the HashMap. Assume I would be using this in a single server, single JVM application. Are there any thread-safety or other problems/issues with code like this?

    I don't think this logic necessarily follows. I agree
    that the user must see all the entries in the
    drop-down list, but that doesn't mean that this class
    needs to hand the map over to the drop-down list
    instance or the UI container. Instead, the UI could
    ask this instance to write itself into the drop-down
    list.I envisioned the DAO as the model in a MVC app. Writing the drop-down seems like it is a task for the view.
    This is a very common sentiment among programmers.
    "If you're code is written wrong, then it's not my
    problem." I'm not saying that you're wrong to feel
    this way, but in general projects get finished faster
    when the interfaces between components or classes are
    tight. That is, write an interface to your class
    that helps people avoid coding mistakes. If
    getItems().add() should not be coded then you should
    try to make sure that it can't be.That makes sense.
    This is a little better. Now when somebody else codes
    getItems().add(), their code compiles (as it did
    before) but when they run some test case (assuming
    they test the right path) they will see an
    UnsupportedOperationException instead of seeing some
    occasional bad behaviour (as they would have seen
    before). But better still, write an interface that
    doesn't allow anybody else to code getItems().add() in
    the first place. I'm not trying to make your life
    more difficult, but in the long run doing this saves
    time for everybody on your project.I see your point.
    Would it be a reasonable
    solution to write String[] getItemValues(), that
    returns a copy of all the values currently in the
    HashMap? Do you need to supply the user with key-value
    pairs instead? Is there a way that you can return an
    array of those things rather than the map?You are right, there is no reason I couldn't do that. Would this cause potential performance issues? I would think giving the client the a read-only reference to the hashmap would be faster than generating an array of Object each time.
    >>
    But then my original question still is do add and
    refresh need to be synchronized? I can't think of
    anything that would be bad if they weren't
    synchronized, but maybe I am overlooking something.
    What happens if someone calls the add method while
    the refresh method is executing? I guess I need to
    show more code to address that:
    public void add(String key, String item) {
    addItemToDB(key,item);
    items.put(key.item);
    public void refreshCache() {
    items = getItemsFromDB();
    }Assume addItemToDB() returns void and inserts myitem
    into the database.
    Assume getItemsFromDB() queries the DB for all the
    items and returns a Map with all of the items.
    Do these methods need to be synchronized?
    You need to provide synchronization for the map, the
    map has no synchronization of it's own.But just synchronizing add and refreshCache won't cut it, right? I think if things happend in this order I would have an issue:
    1. Thread A calls refreshCache()
    2. refreshCache() calls getItemsFromDB()
    3. getItemsFromDB() internally has queried the DB, gotten a ResultSet and is building a collection from the result set, but the method isn't finished yet.
    4. Thread B calls add()
    5. add() calls addItemtoDB(key,item), which finishes
    6. add() puts the item in the items HashMap
    7. add() finished executing
    8. getItemsFromDB() finishes executing and returns a collection, but the collection doesn't have the item add by Thread B's add()
    9. refreshCache replaces the items HashMap with the collection returned from getItemsFromDB() and now the item that was added by Thread B's add() won't end up in the collection until next time refreshCache() is called.
    This would be the case even if add() and refreshCache() were synchronized, right?

Maybe you are looking for

  • I need to delete an old icloud account and i don't remember its password anymore

    How do I delete an old icloud account login and replace it with a new one when I can't remember the old password.  I am getting continuous messages asking for a password that it doesn't accept.

  • Problem with creating BDC program

    Hi All, I was trying to create a BDC program for transaction SE63 (language translation). I am doing it for text modules translation. For this, screen contains two fields, one is source language and another is target language and both are input disab

  • Safari - spyglass to open downloaded file in Finder fails

    Just upgraded to 9.0 mavericks - I use Pathfinder 6 - fixed (no more hang). Download in Safari work just fine and end up in the right folder but I can't use the spyglass to highlight a downloaded file in a finder winder I get an error about not findi

  • International characters not showing up in certain apps?

    I'm using Dreamweaver CS3 and international characters aren't showing up. There are blank spaces where they used to be. The characters are still there, it's just that they appear as blank spaces (I can copy and paste them and see them elsewhere). Thi

  • Web service 302 object moved error

    Hi All, Last week, IT changed the configuration on our Cisco content switch to redirect every page request to https. Everything seems to be working properly except for our Web services, which I can't seem to consume at all. Here's the error we keep g