5.1 Servlet Performance

Using Weblogic 5.1 SP3 under Solaris 2.7
We are using the native Performance Pack which allocates 3 Posix readers
can we or should we tune this??? Appears this is per cpu limit.
We have an unusual situation where we want to essentially do an long
running post so we can stream data back to a client much like a file
transfer.
What we are seeing is that depending on the number of Execute Threads we
see the first say 12 Clients - (Using Execute Thread Count 15) start and
we dont see our other say 288 clients until each of our 12 clients are
almost finished
processing.
It would appear that the cpu allocation timeslice is not switiching
between concurrent http clients effectively if the servlets are long
running.
Is there some tunning which can be done to change this???
I know this is an unusual situation but given the nature of
firewalls/proxyservers/load balancing hardware like ArrowPoint,F5 etc we
need to try to use http vs native
t3 protocol out to our clients who will be both jfc and web based.
Any help in this area would be greatly appreciated.
NOTE: Also set weblogic.system.acceptBacklog=100
Still CPU is pegged. Sparc ultra 5.

Larry,
There are a couple of issues here.
First a little bit of info about how the performance pack and execute
threads are related. The performance pack is a bit of code which uses the
POSIX poll() call to determine when a given socket has data available and
can thus be read from without blocking. The POSIX reader threads then make
the actual call to read() and if enough data has been sent (in the case of
HTTP the request line and all of the headers) then the request is enqueued.
The execute threads pull the request off and call the service() method of
the appropriate servlet. So for your situation changing the number of POSIX
reader threads won't help, but as you'll see below increasing the number of
execute threads will.
Once the service() method has been called on the servlet there is very
little the container can do besides wait for that call to return. It can't
reclaim the thread because the servlet specification mandates a synchronous
model; the service() method must run to completion at which point the
request is flushed and the thread can be re-assigned. If we were to somehow
reclaim the thread in the middle of the service() call, the call stack and
by consequence all of the lexically scoped variables would be lost and there
would be no way of resuming the service() call later. Lisp and other
languages have ways of packaging up the current call stack such that one
could do this, but for better or worse Java does not.
The fact that the servlet specification is like this makes some sense
because it is much easier to write synchronous programs than asynchronous
ones. Further since HTTP is fundamentally a synchronous protocol it is a
pretty good fit for most uses. Neither HTTP nor servlets were really
designed to be used in the manner you describe.
So what can you do? There are a number of options I can think of.
1. Increase the number of execute threads to the number of simultaneous
clients. This the easiest thing because it only requires a configuration
change. The downside is that it won't scale to thousands of clients per
server. Most VMs fall over, or at least get really slow, when you use that
many threads.
2. Use our HTTP tunneling support. It doesn't suffer from this problem.
When you are making your initial JNDI connection just specify http: as the
protocol rather than t3:.
3. Batch data on the server and have the client poll periodically to
retrieve it.
4. In an upcoming release we may provide support for an asynchronous
servlet programming model. If you are interested in hearing more about this
send me mail and we can discuss.
Regards,
Adam

Similar Messages

  • Webstart to Servlet Performance Issues

    Hi. I have a application that connects to a servlet to do database operations on a server. When it runs as either an application or an applet, the performance is great. However, when I try to deploy it with WebStart, the performance is terrible, a database lookup taking 40 secs to 1 minute, when a lookup would previously take 5-10 seconds. Has anyone else seen this? The hang up is in the DBConnect function listed bleow:
         public boolean DBConnect (String DBHost) {               
              String DBConnStr = DBHost;
              boolean ret = true;
              try {
                   url = new URL(DBConnStr);
              } catch (Exception ex) {
                   ret = false;
                   System.out.println("Failed to create URL " + url.toString());
              try {
                   con = (java.net.HttpURLConnection) url.openConnection();
                   con.setDoOutput(true);
                   con.setUseCaches(false); // to ensure that we do contact
                                                                     // the servlet and don't get
                                                                     // anything from the browser's
                                                                     // cache
                   con.setDoInput(true); // only if reading response
                   con.connect();
              } catch (Exception ex) {
                   ret = false;
                   System.out.println("Failed to connect to db servlet...");
              return ret;
    Thanks,
    Dan

    Hi
    I want to access a servlet from a WS Application and have performance problem Where did you set SecurityManager to null? In the servlet, or in your WS-Application?
    If I set the SecurityManager to null in the Application which should access the servlet, I can't start the Application (and it is o.k). After that I tryed in the servlet as follow:
    System.setSecurityManager(null);But, after that it wasn't better. Could you show me, how did you set SecurityManager to null (and where).
    Thanks a lot.
    P.S. In the WebStart I tryed two options: Proxi: withoutand Proxi:Webbrowser directBut it didin't help to.

  • Servlet performance

    Dear All,
    Could you explain me the follow statistic:
    The time to get complete created by servlet page - 15 s
    The time of servlet work (database access and HTML layout) - 70%
    The time of database processing (inside servlet work for sure) - 3%
    The network speed - 100Mbit
    When we try to copy dynamically generated page on Server as a file it
    appears immideatly.
    So it seems that the problem with data output from a servlet.
    What do you think, dear ALL? How can I manage it and fix?
    With regards, Alexey Ionin.

    From your statistic, database access and HTML layout are 70%. In most cases,
    database is the bottlenectk. Try to tune up your database to boost up
    performance.
    Cheers - Wei
    Alexey Ionin <[email protected]> wrote in message
    news:[email protected]..
    Dear All,
    Could you explain me the follow statistic:
    The time to get complete created by servlet page - 15 s
    The time of servlet work (database access and HTML layout) - 70%
    The time of database processing (inside servlet work for sure) - 3%
    The network speed - 100Mbit
    When we try to copy dynamically generated page on Server as a file it
    appears immideatly.
    So it seems that the problem with data output from a servlet.
    What do you think, dear ALL? How can I manage it and fix?
    With regards, Alexey Ionin.

  • Servlet performance speed

    Any advice on how to improve the performance and speed
    of this servlet or any other comments please
    public class LogInServlet extends HttpServlet {
        byte[] header;
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            // variables
            ServletOutputStream out;
            Calendar c;
            String day;
            String date;
            String timenow;
            Connection con = null;
            Statement stmt = null;
            ResultSet result = null;
            // setup output
            response.setContentType("text/html");
            out = response.getOutputStream();
            // get inputs
            String pass = (String)request.getParameter("*");
            String namenum = (String)request.getParameter("*")+
            ", "+
            (String)request.getParameter("*")+
            " ("+
            (String)request.getParameter("*")+
            // get current time
            c = Calendar.getInstance();
            try{
                // get db connection
                Context initCtx = new InitialContext();
                Context envCtx = (Context) initCtx.lookup("java:comp/env");
                DataSource ds = (DataSource)envCtx.lookup("jdbc/*");
                con = ds.getConnection();
                stmt = con.createStatement();
                result = stmt.executeQuery("*");
                // check username
                if(result.next()){
                    // check password
                    if(result.getString("*").equals(pass)){
                        // SOLVES LOWERCASE PROBLEM
                        namenum = result.getString("*");
                        day = getDay(c);
                        date = getDate(c);
                        stmt.close();
                        stmt = null;
                        stmt = con.createStatement();
                        result.close();
                        result = null;
                        result = stmt.executeQuery("*");
                        // check if setup to login
                        if(result.next()){
                            // check if logged in already
                            if(!date.equals(result.getString("*"))){
                                stmt.close();
                                stmt = null;
                                stmt = con.createStatement();
                                result.close();
                                result = null;
                                result = stmt.executeQuery("*");
                                result.next();
                                String time = result.getString(day+"_start");
                                timenow = getTime(c);
                                // check if late
                                if(checkIfLate(c,time)){
                                    stmt.close();
                                    stmt = null;
                                    stmt = con.createStatement();
                                    result.close();
                                    result = null;
                                    result = stmt.executeQuery("*");
                                    // check if timeoff booked
                                    if(!result.next()){
                                        // add late record
                                        stmt.close();
                                        stmt = null;
                                        stmt = con.createStatement();
                                        stmt.executeUpdate("*");
                                        // update login
                                        stmt.close();
                                        stmt = null;
                                        stmt = con.createStatement();
                                        stmt.executeUpdate("*");
                                        // complience
                                        stmt.close();
                                        stmt = null;
                                        stmt = con.createStatement();
                                        stmt.executeUpdate("*");
                                        // late
                                        out.write(header);
                                        out.print("</body></html>");
                                        out.close();
                                    else{
                                        // update login
                                        stmt.close();
                                        stmt = null;
                                        stmt = con.createStatement();
                                        stmt.executeUpdate("*");
                                        // complience
                                        stmt.close();
                                        stmt = null;
                                        stmt = con.createStatement();
                                        stmt.executeUpdate("*");
                                        // ok
                                        out.write(header);
                                        out.println("</body></html>");
                                        out.close();
                                else{
                                    // update loging
                                    stmt.close();
                                    stmt = null;
                                    stmt = con.createStatement();
                                    stmt.executeUpdate("*");
                                    // complience
                                    stmt.close();
                                    stmt = null;
                                    stmt = con.createStatement();
                                    stmt.executeUpdate("*");
                                    // ok
                                    out.write(header);
                                    out.println("</body></html>");
                                    out.close();
                            else{
                                out.write(header);
                                // alreadyLoggedIn
                                out.println("</body></html>");
                                out.close();
                        else{
                            out.write(header);
                            // notSetupLogin
                            out.println("</body></html>");
                            out.close();
                    else{
                        out.write(header);
                        // passwordIncorrect
                        out.println("</body></html>");
                        out.close();
                else{
                    out.write(header);
                    // nameIncorrect
                    out.println("</body></html>");
                    out.close();
            catch(Exception e){
                out.write(header);
                out.println("</body></html>");
                out.close();
            finally{
                if(result != null){
                    try{
                        result.close();
                    catch(SQLException e){
                    result = null;
                if(stmt != null){
                    try{
                        stmt.close();
                    catch(SQLException e){
                    stmt = null;
                if(con != null){
                    try{
                        con.close();
                    catch(SQLException e){
                    con = null;
        private boolean checkIfLate(Calendar c,String t){
            StringTokenizer stz = new StringTokenizer(t,":");
            int sh = Integer.parseInt(stz.nextToken());
            int sm = Integer.parseInt(stz.nextToken());
            int ch = c.get(Calendar.HOUR_OF_DAY);
            int cm = c.get(Calendar.MINUTE);
            if(ch > sh)
                return true;
            else if(ch == sh){
                if(cm > sm)
                    return true;
                else
                    return false;
            else
                return false;
        private String getTime(Calendar c){
            int t = c.get(Calendar.MINUTE);
            if(t < 10)
                return c.get(Calendar.HOUR_OF_DAY)+":0"+t;
            else
                return c.get(Calendar.HOUR_OF_DAY)+":"+t;
        private String getFullDay(String d){
            if("mon".equals(d))
                return "Monday";
            else if("tue".equals(d))
                return "Tuesday";
            else if("wed".equals(d))
                return "Wednesday";
            else if("thu".equals(d))
                return "Thursday";
            else if("fri".equals(d))
                return "Friday";
            else
                return "Sunday";
        private String getDay(Calendar c){
            int d1 = c.get(Calendar.DAY_OF_WEEK);
            if(d1 == 2)
                return "mon";
            else if(d1 == 3)
                return "tue";
            else if(d1 == 4)
                return "wed";
            else if(d1 == 5)
                return "thu";
            else if(d1 == 6)
                return "fri";
            else
                return "z";
        private String getDate(Calendar c){
            int dateI1 = c.get(Calendar.MONTH)+1;
            int dateI2 = c.get(Calendar.DAY_OF_MONTH);
            if(dateI1 < 10){
                if(dateI2 < 10)
                    return Integer.toString(c.get(Calendar.YEAR))+
                    "-"+
                    "0"+
                    Integer.toString(dateI1)+
                    "-"+
                    "0"+
                    Integer.toString(dateI2);
                else
                    return Integer.toString(c.get(Calendar.YEAR))+
                    "-"+
                    "0"+
                    Integer.toString(dateI1)+
                    "-"+
                    Integer.toString(dateI2);
            else{
                if(dateI2 < 10)
                    return Integer.toString(c.get(Calendar.YEAR))+
                    "-"+
                    Integer.toString(dateI1)+
                    "-"+
                    "0"+
                    Integer.toString(dateI2);
                else
                    return Integer.toString(c.get(Calendar.YEAR))+
                    "-"+
                    Integer.toString(dateI1)+
                    "-"+
                    Integer.toString(dateI2);
        protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException {
            processRequest(request, response);
        protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException {
            processRequest(request, response);
        public String getServletInfo() {
            return "Short description";
        public void destroy() {
        public void init(ServletConfig config) throws ServletException {
            super.init(config);
            header = "<HTML><HEAD><TITLE>*".getBytes();
    }

    DrClap / AnyOne
    The problem I'm having is that everybody uses this servlet at around the
    same time and this causes the memory usage and cycles to spike and
    halts other application running on the server.
    I was hoping that by speeding up the application,so that people could get
    in and out of the servlet quickly this would reduce the memory usage
    as some people would finish before the next people use it.
    I also wanted to decrease the amount of memory the servlet uses.
    The garbage collection and tomcat are tuned.
    I want to optimise the code so that I can restrict the JVM to use the
    least amount of memory.
    I'm assured the query strings and index's are optimised.
    The code snippet above yielded a 30% increase in execution time
    (this was using a loadtester and thousands of requests on just that piece of code)
    I'm going to give preparedstatements a try to see if it changes speed
    (the data is cleaned using javascript on the clientside)
    Questions / Comments
    Connection Pooling:
    Not if you used a connection pool, which you should be doing anyway. And if you're putting all your code >>in one giant class just to avoid creating an object, you're doing the wrong thing.That is exactly why I put the code in the one servlet.
    If I set the max connections number to the maximum number of users
    and by putting all the code in one servlet each user will use only one connection:
    1. therefore there will be no one waiting for a connection to become available (increases speed)
    2. the less connections created the less memory used
    Is this thinking correct?????
    Servlet HTML vs JSP
    I know it is correct design to keep the view away from business logic
    but
    1. Is it quicker and less memory hungry to use ServletOutputStream to print html
    or requestDispatcher to jsp?????
    }

  • Servlet performance.  File or Db access?

    Does anyone know which would be a faster method to access snippets of html code? Either open up a file and println it or grab the snippet from a database table? Also, where can I find a good tool to test the speed and performance of my servlets?

    Does anyone know which would be a faster method to
    access snippets of html code? Either open up a file
    and println it or grab the snippet from a database
    table? This heavely depends on what you do how many times and if you are caching or not. For snipplets i would think of putting it into a file and adding the file using ssi or RequestDispatcher.include() or jsp:include. Seems to be the easiest way to do.
    Also, where can I find a good tool to test the
    speed and performance of my servlets? jakarta.apache.org
    Don't know the name at the moment, but they have a project that's purpose is to simulate clients to test performance. I never used it (since for most web apps performace is not a problem) but i read a lot about it and it seems to be very flexible to simulate entire sessions, not just sending simple requests over and over again.

  • Challenge forwarding from a servlet to a JSP

    Redirecting information from a servlet to a JSP
    Hello Everyone,
         I am processing the contents of a html form using a servlet. After processing the
    information received and storing it into a javabean I am trying to pass control onto a jsp for
    display. At this stage the jsp does not display as desired due to a URL challenge. The URL
    which references my jsp is:
    http://localhot/ferngully/prefset.jspThis url has been designated to the jsp page 'prefset.jsp' by the application specific web.xml
    file (...I am using Tomcat 5!), the relevant contents of which follow:
    <servlet>
         <servlet-name>PreferenceSet</servlet-name>
         <jsp-file>/prefset.jsp</jsp-file>
    </servlet>
    <servlet-mapping>
         <servlet-name>PreferenceSet</servlet-name>
         <url-pattern>/ferngully/prefset.jsp</url-pattern>
    </servlet-mapping>If I access the page with the afore mentioned URL it displays correctly. However the URL which
    is returned to the browser after the servlet has forwarded control to the JSP is:
    http://localhost/ferngully/ferngully/PreferencesThe following form markup is used to access the servlet:
    <form name="form1" method="post" action="ferngully/Preferences"> I know that I have mapped the servlet correctly because the servlet performs it's programatic tasks happily :)
    I am using code within the servlet to forward control to the JSP, and I believe that this is the crux of my challenge.
    The code for the servlet is listed below.
    package userpreferences;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    public class PreferencesServlet extends HttpServlet
         public void init(ServletConfig config) throws ServletException
              super.init(config);
         public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
              doPost(request, response);
         public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
              String url = "/prefset.jsp";
              ServletContext servCont = getServletContext();
              RequestDispatcher reqDispatch = servCont.getRequestDispatcher(url);
              reqDispatch.forward(request, response);
    }I believe that the above highlighted code section is responsible for my challenge. I have tried changing the String url to "/ferngully/prefset.jsp",
    however there was no improvement in functionality.
    Can somebody please explain to me how I can go about directing the control of this process from the servlet to the jsp correctly? Particularly
    how I can go about making the url returned to the client correct for accessing the jsp page? Do I need to delete the mapping entry for the
    jsp page in web.xml? I am new to servlets & jsp so any help will be much appreciated.
    Thanks
    Kind Regards
    Davo

    3. >The following form markup is used to access the servlet:
    <form name="form1" method="post" action="ferngully/Preferences">Question 1:
         why do you specify your contextname in action attribute again ?
         General funda about urls:
         When you have an index.html loaded through http://localhost/index.html, then a link in that html whose url is,
         1. say, preferences.html (no forward slashes preffixed or suffixed) would load the html from the same folder.
         2. say, /ferngully/prefences.html, would attempt to load a html from the ferngully folder that is a sub-directory
    of your web-application
         3. say, /ferngully/prefences.jsp, would attempt to load a html from the ferngully folder that is a sub-directory
    of your web-application
         When you have a servlet whose url-pattern is set to intercept requests, it would intercept requests that have that
    pattern it is defined to intercept in web.xml (for example all the above requests in 1,2 and 3 would be intercepted
    by a servlet whose pattern is ferngully/*)
         Now if your action is not a specific resource (.jsp or .html), something like /preferences, this would map to a url
    /ferngully/preferences. (for which a resource should be defined in web.xml - either a servlet or a jsp)
    However the URL which is returned to the browser after the servlet has forwarded control to the JSP is:
    http://localhost/ferngully/ferngully/PreferencesTell us the url of the original html
    I know that I have mapped the servlet correctly because the servlet performs it's programatic tasks happily :)Tell us the url-appetrn of the servlet that intercepted your request
    Particularly
    how I can go about making the url returned to the client correct for accessing the jsp page?The url in the browser is always the request url, you cannot change it to the url of the jsp even which rendered the page
    through a fwd from the servlet.
    Do I need to delete the mapping entry for the
    jsp page in web.xml?Not necessary. You can access the jsp directly from the servlet while forwarding by
    1. specifying the exact path to the jsp. For example if the jsp is under a folder called jsps, your request dispatcher
    url ought to be /jsps/prefset.jsp
    2. specifying the jsp's url-pattern as specified in web.xml
    Questions Contd
    2. Why does the url pattern have to have a .jsp suffixed.
    From your code
    <url-pattern>/ferngully/prefset.jsp</url-pattern>It could equally well have been
    <url-pattern>/ferngully/prefset</url-pattern>And then your servlet would have to forward it to ("/ferngully/prefset")
    2. Your jsp-file mapping is in this form
    <jsp-file>/prefset.jsp</jsp-file>This assumes that the jsp is in the top-level folder of your web-application and not under
    any sub-directories. Correct ?
    cheers,
    ram.

  • Tomcat crashes while running servlet chat in IE

    Hi all!
    I've seen similar problems posted about three years ago, but I didn't see an answer for it.
    I'd be very grateful if you could help me.
    I'm writing a chat, the code was taken from the J.Hunter "Servlet programming book" O'reilly, "absurdly simple chat", and adjusted (I only need the Http version). It's an applet-servlet chat.
    When executed in IE, Tomcat crashes after a few (usually 5) sent messages. When executed in a debugger (I use Forte, the last available version, 4 update 1) the program works just fine...
    Another question is about debugging an applet, executed in a browser - how do I do this?
    Here is the code for the servlet:
    =================================
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class TryChatServlet extends HttpServlet
    // source acts as the distributor of new messages
    MessageSource source = new MessageSource();
    // doGet() returns the next message. It blocks until there is one.
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();
    // Return the next message (blocking)
    out.println(getNextMessage());
    // doPost() accepts a new message and broadcasts it to all
    // the currently listening HTTP and socket clients.
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
    // Accept the new message as the "message" parameter
    String message = req.getParameter("message");
    // Broadcast it to all listening clients
    if (message != null) broadcastMessage(message);
    // Set the status code to indicate there will be no response
    res.setStatus(res.SC_NO_CONTENT);
    // getNextMessage() returns the next new message.
    // It blocks until there is one.
    public String getNextMessage() {
    // Create a message sink to wait for a new message from the
    // message source.
    return new MessageSink().getNextMessage(source);
    // broadcastMessage() informs all currently listening clients that there
    // is a new message. Causes all calls to getNextMessage() to unblock.
    public void broadcastMessage(String message) {
    // Send the message to all the HTTP-connected clients by giving the
    // message to the message source
    source.sendMessage(message);
    // MessageSource acts as the source for new messages.
    // Clients interested in receiving new messages can
    // observe this object.
    class MessageSource extends Observable {
    public void sendMessage(String message) {
    setChanged();
    notifyObservers(message);
    // MessageSink acts as the receiver of new messages.
    // It listens to the source.
    class MessageSink implements Observer {
    String message = null; // set by update() and read by getNextMessage()
    // Called by the message source when it gets a new message
    synchronized public void update(Observable o, Object arg) {
    // Get the new message
    message = (String)arg;
    // Wake up our waiting thread
    notify();
    // Gets the next message sent out from the message source
    synchronized public String getNextMessage(MessageSource source) {
    // Tell source we want to be told about new messages
    source.addObserver(this);
    // Wait until our update() method receives a message
    while (message == null) {
    try { wait(); } catch (Exception ignored) { }
    // Tell source to stop telling us about new messages
    source.deleteObserver(this);
    // Now return the message we received
    // But first set the message instance variable to null
    // so update() and getNextMessage() can be called again.
    String messageCopy = message;
    message = null;
    return messageCopy;
    =============================
    The code for the applet is
    =============================
    import java.applet.*;
    import java.awt.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class TryChatApplet extends Applet implements Runnable {
    TextArea text;
    Label label;
    TextField input;
    Thread thread;
    String user;
    public void init() {
    // Check if this applet was loaded directly from the filesystem.
    // If so, explain to the user that this applet needs to be loaded
    // from a server in order to communicate with that server's servlets.
    URL codebase = getCodeBase();
    if (!"http".equals(codebase.getProtocol())) {
    System.out.println();
    System.out.println("*** Whoops! ***");
    System.out.println("This applet must be loaded from a web server.");
    System.out.println("Please try again, this time fetching the HTML");
    System.out.println("file containing this servlet as");
    System.out.println("\"http://server:port/file.html\".");
    System.out.println();
    System.exit(1); // Works only from appletviewer
    // Browsers throw an exception and muddle on
    // Get this user's name from an applet parameter set by the servlet
    // We could just ask the user, but this demonstrates a
    // form of servlet->applet communication.
    user = getParameter("user");
    if (user == null) user = "anonymous";
    // Set up the user interface...
    // On top, a large TextArea showing what everyone's saying.
    // Underneath, a labeled TextField to accept this user's input.
    text = new TextArea();
    text.setEditable(false);
    label = new Label("Say something: ");
    input = new TextField();
    input.setEditable(true);
    setLayout(new BorderLayout());
    Panel panel = new Panel();
    panel.setLayout(new BorderLayout());
    add("Center", text);
    add("South", panel);
    panel.add("West", label);
    panel.add("Center", input);
    public void start() {
    thread = new Thread(this);
    thread.start();
    String getNextMessage() {
    String nextMessage = null;
    while (nextMessage == null) {
    try {
    URL url = new URL(getCodeBase(), "/servlet/TryChatServlet");
    HttpMessage msg = new HttpMessage(url);
    InputStream in = msg.sendGetMessage();
    DataInputStream data = new DataInputStream(
    new BufferedInputStream(in));
    nextMessage = data.readLine();
    catch (SocketException e) {
    // Can't connect to host, report it and wait before trying again
    System.out.println("Can't connect to host: " + e.getMessage());
    try { Thread.sleep(5000); } catch (InterruptedException ignored) { }
    catch (FileNotFoundException e) {
    // Servlet doesn't exist, report it and wait before trying again
    System.out.println("Resource not found: " + e.getMessage());
    try { Thread.sleep(5000); } catch (InterruptedException ignored) { }
    catch (Exception e) {
    // Some other problem, report it and wait before trying again
    System.out.println("General exception: " +
    e.getClass().getName() + ": " + e.getMessage());
    try { Thread.sleep(1000); } catch (InterruptedException ignored) { }
    return nextMessage + "\n";
    public void run() {
    while (true) {
    text.appendText(getNextMessage());
    public void stop() {
    thread.stop();
    thread = null;
    void broadcastMessage(String message) {
    message = user + ": " + message; // Pre-pend the speaker's name
    try {
    URL url = new URL(getCodeBase(), "/servlet/TryChatServlet");
    HttpMessage msg = new HttpMessage(url);
    Properties props = new Properties();
    props.put("message", message);
    msg.sendPostMessage(props);
    catch (SocketException e) {
    // Can't connect to host, report it and abandon the broadcast
    System.out.println("Can't connect to host: " + e.getMessage());
    catch (FileNotFoundException e) {
    // Servlet doesn't exist, report it and abandon the broadcast
    System.out.println("Resource not found: " + e.getMessage());
    catch (Exception e) {
    // Some other problem, report it and abandon the broadcast
    System.out.println("General exception: " +
    e.getClass().getName() + ": " + e.getMessage());
    public boolean handleEvent(Event event) {
    switch (event.id) {
    case Event.ACTION_EVENT:
    if (event.target == input) {
    broadcastMessage(input.getText());
    input.setText("");
    return true;
    return false;
    =====================================
    HttpMessage
    ======================================
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class HttpMessage {
    URL servlet = null;
    String args = null;
    public HttpMessage(URL servlet) {
    this.servlet = servlet;
    // Performs a GET request to the previously given servlet
    // with no query string.
    public InputStream sendGetMessage() throws IOException {
    return sendGetMessage(null);
    // Performs a GET request to the previously given servlet.
    // Builds a query string from the supplied Properties list.
    public InputStream sendGetMessage(Properties args) throws IOException {
    String argString = ""; // default
    if (args != null) {
    argString = "?" + toEncodedString(args);
    URL url = new URL(servlet.toExternalForm() + argString);
    // Turn off caching
    URLConnection con = url.openConnection();
    con.setUseCaches(false);
    return con.getInputStream();
    // Performs a POST request to the previously given servlet
    // with no query string.
    public InputStream sendPostMessage() throws IOException {
    return sendPostMessage(null);
    // Performs a POST request to the previously given servlet.
    // Builds post data from the supplied Properties list.
    public InputStream sendPostMessage(Properties args) throws IOException {
    String argString = ""; // default
    if (args != null) {
    argString = toEncodedString(args); // notice no "?"
    URLConnection con = servlet.openConnection();
    // Prepare for both input and output
    con.setDoInput(true);
    con.setDoOutput(true);
    // Turn off caching
    con.setUseCaches(false);
    // Work around a Netscape bug
    con.setRequestProperty("Content-Type",
    "application/x-www-form-urlencoded");
    // Write the arguments as post data
    DataOutputStream out = new DataOutputStream(con.getOutputStream());
    out.writeBytes(argString);
    out.flush();
    out.close();
    return con.getInputStream();
    // Converts a Properties list to a URL-encoded query string
    private String toEncodedString(Properties args) {
    StringBuffer buf = new StringBuffer();
    Enumeration names = args.propertyNames();
    while (names.hasMoreElements()) {
    String name = (String) names.nextElement();
    String value = args.getProperty(name);
    buf.append(URLEncoder.encode(name) + "=" + URLEncoder.encode(value));
    if (names.hasMoreElements()) buf.append("&");
    return buf.toString();
    Those files are the only files needed to execute the program.

    The whole Tomcat crashes, and no exception
    displayed.
    Do I have to write the log file, or it's kept by
    Tomcat itself?yes, tomcat writes a log file, you find it in the tomcat dir. but it's just very highlevel. Having a look in it could help.
    Is there a way to write a log file by myself?sure. you could get the log file from tomcat by getting it from the ServletContext:
    ServletContext = getServletContext();
    ServletContext.log("text to log");
    When I view the output window in Forte, it doesn't
    even write that Tomcat crashed.
    I use Tomcat that is installed with the last version
    of Forte(Sun 1 Studio, update 1), I guess it's the
    last version of Tomcat also.No. The lastest is 4.1.12 and i guess it's 4.0.4 with forte.
    Get Tomcat standalone from jakarta.apache.org and try to run your servlet with the standalone tomcat. this could help since i also expirenced problems sometimes with the forte-integrated tomcat.

  • General design tip needed to write a small Jsp/servlet application

    I am developing a small application using few JSP pages and a single servlet(as it iwas told to me that, number of servlet should be 1).
    My problem is,
    I have multiple JSPs. and multiple button within each JSPs.On click of each button, requeswt should be sent to Servlet and servlet performs some logic for esch button clicked.
    I have 2 option to identify the button clicked and write the logic.
    1.Servlet will get the value of each button.I will write one 'if loop' each for one button value. Whichever (request.getParameter("btnxyz")) returns 'NOT NULL', corresponding 'if loop' gets executed.This works fine.but servlet code looks like a mess as number of if loops = total number of buttons of all jsps.
    2.Have a hidden field in each JSP.Onload of the button i will write some value to the field.On exit of JSp i will make it null.So, when button is clicked, in the servlet i will first identify the JSP from which request has come. and then identify the button as in step1.
    My question is , which option is better?
    Please suggest me other better solutions for the same.
    Thanks,
    Gowtam

    Have you considered using Struts?
    It would make your life so much easier.
    Nick

  • How should i send parameter to servlet

    i want to sent parameter to the servlet
    i am using servlet applet cumunication
    and when i am coling the servlet i want
    send one or more parameter to the servelt
    depend on that servlet perform action
    how should i sent the parameter please
    tell me,
    Rahul

    how should i sent the parameter pleaseHow should we know that ? It's your decision
    Your applet may open a (Http)URLConnection to the Servlet
    there you write your parameters in URLEncoded form to the output stream
    of the URLConnection setting the RequestMethod to POST.
    After that you read the response from the input stream.
    andi

  • Architecture Question: Servlet, Bean, or JSP?

    I've found that alot of the time, the systems I'm trying to design can use all of these to accomplish the same task. What's a good indicator of whether or not I should be using one technology over another?
    For example, most recently, I designed an html form that is used to create registration html forms for clients. I can send the data in my form to another jsp page, a servlet, or a bean. ALL THREE can accept the date and use BufferedWriter to create and write to the registration form. Why would I want to use one over the other?
    Any help here would be greatly appreciated. I am seriously lacking in proper system design knowledge.

    The concept of JSPs was created to let Web designers design pages and developers to plug in the dynamic content. So essentially the JSPs are primarily for display on.
    Servlets are good for controlling the flow.
    Typically in any medium to large application, that's the distinction you'd want to have.
    So have a single controller servlet as a central entry point into your application. That's useful for certain validations such as login etc. Then the servlet performs whatever work is required and dispatches to a JSP to display the output of the work.

  • Oc4j and international character sets

    Does anyone know if there is a problem in oc4j concerning international charactersets support?
    My pages contain non-english characters and so i use utf-8 characterset. When the page is created by a servlet the characters are displayed correctly, but when it comes from a jsp this is not the case.
    The problem is that the text is not displayed in utf-8 but in "western european (windows)" instead which is not the correct encoding. This does not happen in the servlet case above. Still if I change the borwser encoding setting
    the information is displayed correctly. But I cannot do that for every page, they are to many...
    If i try to instruct the page about the encoding the outcome is a real mess because no brwser characterset encoding configuration option seems to be suitable. I tried the following:
    - the page directive: <%@page contentType=... pageEncoding...
    - the request: request.setContentType
    - oc4j configuration: default-charset configuration in the global-application.xml config file
    - and the oracle extension <% serwriterEncoding(...) ; %>
    all of the above had no result while servlets perform swell !
    Am I missing something here?
    Does any body knows something that I do not?
    Does the jsp container mess with the encoding and sends to the browser incorrect page encoding?
    Thank you in advance,
    Joe

    HI Joe:
    Are you able to find any solution for this. I am also stuck with the same issue. Could you please share your solution to me. my email id is: [email protected]
    Thanks & Regards
    Sridhar Doki

  • ADF Faces - access to content in WEB-INF directory

    Hello,
    I create simple JSF application that use ADF Faces and deploy it to Oracle iAS. But why can i also access files in WEB-INF directory? For example, the following URL - http://myserver.si/MyApp/faces/WEB-INF/web.xml - will return the content of XML file. By my knowledge of J2EE architecture, access to this directory should be forbidden.
    Should I set some parameter on javax.faces.webapp.FacesServlet servlet filter to prevent access to WEB-INF directory? Thank you for help.
    Google also found the following links:
    - http://mail-archives.apache.org/mod_mbox/myfaces-dev/200602.mbox/%[email protected]%3E
    - http://svn.apache.org/viewcvs.cgi//myfaces/core/trunk/api/src/main/java/javax/faces/webapp/FacesServlet.java/?rev=375489&view=diff&r1=375489&r2=375488&p1=/myfaces/core/trunk/api/src/main/java/javax/faces/webapp/FacesServlet.java&p2=/myfaces/core/trunk/api/src/main/java/javax/faces/webapp/FacesServlet.java
    Regards,
    Matic

    Hi,
    the reason for this is that the WEB-INF directory is protected against direct client (browser) requests. Using Faces, the JSF servlet performs this access as a server side forward request in which case there is no container-managed protection.
    If you want to avoid this then you can write a servlet filter in fron of JSF in which you check for any occurences of directories you want to prohibit access to.
    Its not a bug, its the way J2EE is designed ;-(
    Frank

  • How to use pool connection run oracle procedure?

    Hi, All:
              I am facing a difficulty I can not find the solution. Maybe you can help
              me.
              I want to call an oracle stored procedure whenever I talk to datebase to
              make the application more efficient. I was able to run the procedure using
              oracle thin driver but not the connection pool using Weblogic jDriver for
              JDBC2.0.
              Please check the following code and see what I did wrong:
              The code in JSP file in Weblogic:
              <%-- JSP page directive --%>
              <%@ page
              import="java.io.*,java.util.*,java.sql.*,weblogic.common.*,weblogic.jdbc20.c
              ommon.*" %>
              <%-- JSP Declaration --%>
              <%!
              protected Connection con = null;
              ResultSet rset = null;
              %>
              <%-- JSP Scriptlet --%>
              <% try {
              Properties props = new Properties();
              props.setProperty("user", "james");
              props.setProperty("password", "aimjames");
              Driver myDriver =
              (Driver) Class.forName
              ("weblogic.jdbc.pool.Driver").newInstance();
              con = myDriver.connect("jdbc:weblogic:pool:hdj2Pool", props);
              String userid = (String)session.getAttribute("user.id");
              int subid =
              Integer.parseInt((String)session.getAttribute("sub.id"));
              String query = "begin pkg_select.sel_req_in_001(" + userid +
              ", " + subid + ", ?); end;";
              weblogic.jdbc.common.OracleCallableStatement cstmt =
              (weblogic.jdbc.common.OracleCallableStatement)con.prepareCall(query);
              cstmt.registerOutParameter(1,java.sql.Types.OTHER);
              cstmt.execute();
              rset = cstmt.getResultSet(1);
              When I run this JSP file, the compilation is fine but the result shows
              nothing. That's means I can not get the ResultSet for some reason.
              The working file when I use oracle thin driver (NOT use a connection pool):
              String userid = (String)session.getAttribute("user.id");
              int subid = Integer.parseInt((String)session.getAttribute("sub.id"));
              String query = "begin pkg_select.sel_req_in_001(" + userid +", " +subid
              +", ?); end ";
              CallableStatement cstmt = con.prepareCall(query);
              cstmt.registerOutParameter(1,OracleTypes.CURSOR);
              cstmt.execute();
              ResultSet rset = (ResultSet)cstmt.getObject(1);
              You may notice that I am trying to bind a parameter to an Oracle cursor. Is
              there anything I did wrong in using weblogic API? I just want to let you
              that in the weblogic JSP file, I also tried to use
              weblogic.jdbc.oci.CallableStatement and
              weblogic.jdbc20.oci.CallableStatement instead of
              weblogic.jdbc.common.OracleCallableStatement, but none of them seems work.
              I did check the bea site at
              http://www.weblogic.com/docs51/classdocs/API_joci.html#1080420 for the
              example to use:
              cstmt.registerOutParameter(1,java.sql.Types.OTHER);
              and I think I followed the exact procedure the example did.
              Please help!
              James Lee
              Artificial Intelligence in Medicine, Inc.
              2 Berkeley Street, Suite 403
              Toronto, Ontario M5A 2W3
              Tel: 416-594-9393 ext. 223
              Fax: 416-594-2420
              Email: [email protected]
              

    Joseph
    Thanks for the suggestion about latest version of Weblogic Server.
    "coding best-practices" is not mentioned in the post.
    In order to make servlet application run significantly faster, my servet how to use connection poo is much moreresonable?
    It is reasonable to expect servlet to run significantly faster with connection pooling.
    Is it true that geting and close a connection whenever
    one time database access finished?
    Already answered. Applications use a connection from the pool then return it when finished using the connection.
    Will the solution affect the servlet performance?
    Yes. Already answered. Connection pooling enhances performance by eliminating the costly task of creating database connections for the application.
    Is there any official document to introduce connection pool program?
    For the latest version
    http://download.oracle.com/docs/cd/E17904_01/web.1111/e13726/toc.htm
    http://download.oracle.com/docs/cd/E17904_01/web.1111/e13737/jdbc_datasources.htm#insertedID0

  • JSP forward issue

    I have a web application deployed on weblogic 8 server. I have a jsp (AddNewUser.jsp) which forwards to a servlet (CreateUserServlet.class) with the following code :
    <jsp:forward page="/admin/CreateUser?userID=new"/>In the CreateUserServlet class, I have overriden init(config) as follows:
    public void init(ServletConfig config)throws ServletException {
             super.init(config);
            context = config.getServletContext();
    }In the doPost method, I have some debug statements as follows:
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
    System.err.println("--------CreateUserServlet start------- ");
    //initialization code here    
    context.getRequestDispatcher("/WEB-INF/jsps/admin/createUser.jsp").forward(request, response);
    }The flow of actions is :
    1. User clicks on a link to AddNew.jsp which forwards to the CreateUserServlet
    2. The servlet performs some initialization (not shown) and forwards to createUser.jsp page
    3. The createUser.jsp page contains a form which the user fills and clicks "save".
    4. The form calls another servlet which saves the new user to the database.
    The problem now which I have is that the web application works perfectly on 4-5 test machines except for the client ( what luck huh?). For him this is what happens
    1. He clicks on a link to AddNew.jsp, he gets forwarded to the createUser.jsp page (as expected..no problem here!)
    2. He enters some data and clicks "save" and the new user gets saved to the database.(as expected..no problem here!)
    3. Now, when he tries repeating by clicking on the link to AddNew.jsp page, the debug statement "--------CreateUserServlet start------- " does not get printed to the console!!(HERE IS THE PROBLEM!) but he still gets forwarded to the createUser.jsp page! This is creating a problem because my initialization code is being skipped.
    So, the client is able to enter a new user the first time he visits the section but is not able to add thereafter.
    Any clues please?

    I wonder if what is happening is when he clicks the link to AddNew.jsp teh browser is pulling the page out of cache. That would explain why he gets the CreateUser form without hitting the CreateUserServlet.
    It is easy enough to check by enabling the access logs for your server. Then when he clicks on the link check the log to see if the request was recieved on the server and teh responce code is 304
    If it is a caching problem there are pleanty of examples of the HTML meta data tags to prevent cahcing on the forum if you search for them.

  • How to use connection pool of datasource to make applications run faster?

    Hi, erveryone
    I prepare to implement a servlet that access database and do sync with client.
    When I access database, I would like to configure a datasource in weblogic and use connection pool.
    In order to make servlet application run significantly faster, my servet how to use connection poo is much moreresonable?
    For example, my servlet has many times database access. Is it true that geting and close a connection whenever
    one time database access finished?
    If from the servlet begins, the db connection is hold till servlet finalize. Will the solution affect the servlet performance? Is there any official document to introduce connection pool program? I search some documents.
    <The Java EE 6Tutorial> introduce some simple intruduction about connection pool.

    1. Use WebLogic Servers Data Source for Database Connections.
    2. Open and close the connections where you need it. Dont open it in begin and close in finalise. That is bad practice.
    3. Even when you invoke Connection.close () webLogic will not close the connection. it will commit the transaction and return it back to the pool rather than physically closing the DB connection.
    4. You can tune data source for minimum, maximum and increments of connections that you need based on your application requirement.

Maybe you are looking for