Implementing a clock using servlets

I have a servlet that I want to display a clock. What is the best way to go about it?

I want to display the time digitally on the page. I could get the current time from Calendar but if I were to do that I would have displayed on the website the time when the page loaded. I could then tell the page to update every minute, but that wouldn't be very efficient. Is there a better way?

Similar Messages

  • Question about implementing a clock using a Timer object

    Hello all, I'm not sure if this is the correct forum to post this question but I think so, as it regards a Swing component. I want to add a timer (a clock that starts at 0:00 and keeps track of how long the app is running) to a frame. I am just curious if using a Timer is the proper way to keep track of time, and just repaint() the clock object every second? (or more frequently if desired)... or is there a better way to do this? Thanks in advance for any comments/feedback/help!
    Brian

    Hello,
    Timer is not accurate. You can use Timer to display your component repeteadly, and System.currentTimeMillis() at each call to deduce the elapsed time.

  • How to invoke a jsp page from java which does not use Servlets?

    Hello,
    I am working in Documentum. I am trying to invoke a jsp page from another java page which does not use Servlets.
    I tried doing this by just instantiating the java class related to the jsp page from my present java class.In my java class related to the jsp page, I have defined onInit() and onRender() methods.
    Now, I am trying to call the jsp page from my present java class by just instantiating the java class related to the jsp page. This throws a java.lang.NullPointerException.
    Any comments or suggestions on this.Any help would be appreciated.
    Thanks,
    Ranjith M.V

    RanjithM.V wrote:
    Hello,
    Thanks for the reply. One important thing I forgot to mention. I am also using xml component.And?
    As this is the standard way used for coding in Documentum, I do not want to use Beans.Well, JSP's should, in and of themselves, contain no functional code. It should all be only display.
    Without that is it not possible?What did I say? I said,
    masijade wrote:
    It is possible, but I very, very, very, much doubt, that it would be worth the effort.And, if you don't know how, a forum is not truely going to be able to help you implement it (at least not in less than a few years time, at which point it would be outdated).
    >
    Appreciate your understanding and help.
    Thanks,
    Ranjith M.V

  • Uploading a file to server using servlet (Without using Jakarta Commons)

    Hi,
    I was trying to upload a file to server using servlet, but i need to do that without the help of anyother API packages like Jakarta Commons Upload. If any class for retrieval is necessary, how can i write my own code to upload from client machine?.
    From
    Velu

    <p>Why put such a restriction on the solution? Whats wrong about using that library?
    The uploading bit is easy - you put a <input type="file"> component on the form, and set it to be method="post" and enctype="multipart/form-data"
    Reading the input stream at the other end - thats harder - which is why they wrote a library for it. </p>
    why i gave the restriction is that, i have a question that <code>'can't we implement the same upload'</code>
    I was with the view that the same can be implemented by our own code right?

  • Outputting JPEG using servlets

    hi
    Im trying to output the JPEG created by the StockGraphProducer class i found on Javaworld to a webpage using a servlet output stream.
    The original code used a file output stream i have included a snippet of it below. I have also included my servlet where i have tried to amend it to render JPEG to the webpage but im not usre abotu it or what bits i need to change in the StockGraphProducer
    I woudl be very grateful if someone could take a quick look at this .
    thanks
    public class StockGraphProducer implements ImageProducer
      private static int ImageWidth = 300;
      private static int ImageHeight = 300;
      private static int VertInset = 25;
      private static int HorzInset = 25;
      private static int HatchLength = 10;
       *  Request the producer create an image
       *  @param stream stream to write image into
       *  @return image type
    // i want to try and use a servlet output stream to send the JPEG to the user insteadof outputstream.
    public String createImage(Outputstream stream) throws IOException
        plottedPrices = new Point2D.Double[5];
        int prices[] =  {105, 100, 97, 93, 93};
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(stream);
    //do i remove the stream paaremter from createiamge and above function???
        BufferedImage bi = new BufferedImage(ImageWidth + 10,
                                             ImageHeight,
                                             BufferedImage.TYPE_BYTE_INDEXED);
        graphics = bi.createGraphics();
        graphics.setColor(Color.white);
        graphics.fillRect(0, 0, bi.getWidth(), bi.getHeight());
        graphics.setColor(Color.red);
        createVerticalAxis();
        createHorizontalAxis();
        graphics.setColor(Color.green);
        plotPrices(prices);
        encoder.encode(bi);
        return "image/jpg";
    public final class GraphRenderer extends HttpServlet
         public void doGet(HttpServletRequest request,
                               HttpServletResponse response)
           throws IOException, ServletException
              HttpSession session = request.getSession(true);
                   response.setContentType("image/jpeg");
              ServletOutputStream sos= response.getOutputStream();
      //the original code
       /* try
           FileOutputStream f = new FileOutputStream("stockgraph.jpg");
           StockGraphProducer producer = new StockGraphProducer();
           producer.createImage(f);
           f.close();
        catch (Exception e)
          e.printStackTrace();
    //i want to try and use a servlet output stream so that the JPEG is sent to the webpage     i tried the following butim not sure about it. I got rid of the outputstream parameter from StockGraphProducer and left it empty and tried .
              try
                   StockGraphProducer producer = new StockGraphProducer();
                          producer.createImage();
                   //i dont think i need this part.      
                   /*Dimension size= producer.getPreferredSize();
                   BufferedImage image = new BufferedImage((int)size.getWidth(),                (int)size.getHeight(), BufferedImage.TYPE_INT_RGB);
                   Graphics g= image.createGraphics();
                   gp.paint(g);*/
                   // Send back image i dont think this is correct
                   JPEGImageEncoder encoder= JPEGCodec.createJPEGEncoder(sos);
                   JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image);
                   param.setQuality(1.0f, false);
                   encoder.setJPEGEncodeParam(param);
                   encoder.encode(image);
              catch(Exception ex)
              {

    Hi,
    I need to create a program where I get an Image from DB and then display it in Browser using servlets.
    I was looking at the StockGraphProducer, but it seems the code is not fully posted.
    I would greatly appreciate anyone who has this StockGraphProducer program would email me or post it.
    Thanks in advance.
    my email address is [email protected]
    Again Thanks

  • Alarm Clock using Java 2D

    Hey Guys,
    I have built an analog clock in java using swing and gregorian calender. Now my professor wants me to add an alarm functionality to it. Any ideas of how to implement this into the already existing code. The folllowing is the code i have written so far..everything works except i dont know how to implement the alarm functionality. Assistance needed ASAP, as its due by this wednesday!!
    /** Analog Clock using Java Graphics 2D Component */
    import java.awt.*;
    import java.awt.Graphics2D;
    import javax.swing.*;
    import java.util.*;
    import java.awt.event.*;
    /** Built on JPanel..Used class Timer for repeatedly executing
    the clocktimer thread/
    public class AnalogClock extends JPanel
    ImageIcon img;
    private GregorianCalendar m_calendar;
    private int[] x=new int[2];
    private int[] y=new int[2];
    private java.util.Timer clocktimer=new java.util.Timer();
    /**You could set the TimeZone for the clock here. I used the Dfault time
    zone from the user so that every time the program runs on different
    computers the correct time is displayed*/
    private TimeZone clockTimeZone=TimeZone.getDefault();
    //Constructor
    public AnalogClock()
    this.setPreferredSize(new Dimension(210,210));
    this.setMinimumSize(new Dimension(210,210));
    //schedules the clocktimer task to scan for every 1000ms=1sec
    clocktimer.schedule(new TickTimerTask(),0,1000);
    //The Clock Face instance method
    public void paint(Graphics g)
    g.setColor(Color.orange);
    g.fillRect(0,0,this.getWidth(),this.getHeight());
    drawCardinals((Graphics2D)g);
    drawHands((Graphics2D)g);
    //Endpoints of the Clock Hand
    void clockMinutes(int startRadius,int endRadius,double theta)
    theta-=Math.PI/2;
    x[0]=(int)(getWidth()/2+startRadius*Math.cos(theta));
    y[0]=(int)(getHeight()/2+startRadius*Math.sin(theta));
    x[1]=(int)(getWidth()/2+endRadius*Math.cos(theta));
    y[1]=(int)(getHeight()/2+endRadius*Math.sin(theta));
    //The Hours/Cardinals of the clock
    /** Set Stroke sets the thickness of the cardinals and hands*/
    void drawCardinals(Graphics2D g)
    g.setStroke(new BasicStroke(9));
    g.setColor(Color.black);
    for(double theta=0;theta<Math.PI*2;theta+=Math.PI/6)
    clockMinutes(100,100,theta);
    /**Draws a sequence of connected lines defined by arrays of x and
    *y coordinates. Each pair of (x, y) coordinates defines a point.
    *The figure is not closed if the first point
    differs from the last point./
    g.drawPolyline(x,y,2);
    //The Hand of the Clocks instance method
    public void drawHands(Graphics2D g)
    double h=2*Math.PI*(m_calendar.get(Calendar.HOUR));
    double m=2*Math.PI*(m_calendar.get(Calendar.MINUTE));
    double s=2*Math.PI*(m_calendar.get(Calendar.SECOND));
    g.setStroke(new BasicStroke(9));
    clockMinutes(0,55,h/12+m/(60*12));
    g.setColor(Color.red);
    g.drawPolyline(x,y,2);
    clockMinutes(0,70,m/60+s/(60*60));
    g.setColor(Color.blue);
    g.drawPolyline(x,y,2);
    clockMinutes(0,70,s/60);
    g.setColor(Color.black);
    g.drawPolyline(x,y,2);
    g.fillOval(getWidth()/2-8,getHeight()/2-8,16,16);
    //method to update/refresh the clock every second
    class TickTimerTask extends TimerTask
    public void run()
    m_calendar=(GregorianCalendar)GregorianCalendar.getInstance(clockTimeZone);
    repaint();
    The Main File is below:
    import javax.swing.JFrame;
    import java.awt.Toolkit;
    public class AnalogClockView extends JFrame
    public static void main(String[] args)
    JFrame frame = new JFrame();
    frame.setSize(300, 400);
    frame.setTitle("My Java Project Clock");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setIconImage(Toolkit.getDefaultToolkit().getImage("Clock.gif"));
    AnalogClock m_AnalogClock=new AnalogClock();
    frame.add(m_AnalogClock);
    frame.setVisible(true);
    Edited by: sIrIUs_bLAcK on Aug 31, 2008 11:17 PM

    some items unrelated to your main question:
    *) When drawing in JPanels and other JComponents, you should override paintComponent, not paint. Also, the first method in this override should be super.paintComponent(g). This will refresh your screen and will eliminate the need for your having to fill the rectangle with a color on each iteration of paintComponent. You'll have to call setBackground(Color c) on your drawing JPanel somewhere in the initialization code though.
    *) If you're using a Timer with Swing apps, consider using a Swing Timer. It works well and has the added convenience of having all code in it's actionlistener called on the event dispatch thread, the main Swing thread.
    *) Finally, when posting your code, please use code tags so that your code will retain its formatting and be readable. To do this, you will need to paste already formatted code into the forum, highlight this code, and then press the "code" button at the top of the forum Message editor prior to posting the message. You may want to click on the Preview tab to make sure that your code is formatted correctly. Another way is to place the tag &#91;code] at the top of your block of code and the tag &#91;/code] at the bottom, like so:
    &#91;code]
      // your code block goes here.
      // note the differences between the tag at the top vs the bottom.
    &#91;/code]or
    {&#99;ode}
      // your code block goes here.
      // note here that the tags are the same.
    {&#99;ode}Edited by: Encephalopathic on Aug 31, 2008 5:29 PM

  • Implement Naming convention using code inspector

    Hi,
    We have to implement naming convention using code inspector,if anybody has already done it plz help
    me inunderstanding the problem.
    help is appreciated.

    We're also using the code inspector for naming conventions.
    Try this link:
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/library/nw/how to build a new check for the code inspector
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/library/webas/abap/evaluating the quality of your abap programs and other repository objects with the code inspector

  • Why do you still use servlet since the jsp is powerful?

    Jsp is servlet,I think.
    Jsp is more useful, because it's auto compile,output HTML easily and need not deploy.
    Would you please tell me anything must be implemented by servlet?

    just using jsp is as "wrong" as just using servlets.
    first it depends on what you are doing.
    Servlets are best fit for complex programming stuff i.e. business logic. JSP are best fit for userinterface task, to present data, for a lot of html work.
    so normally you use servlet for request processing, than you put the response data in a bean and redirect the request to a jsp which gets the presentation data from the bean.
    So, it's not jsp or servlet better or worse, they are, together with beans the three musketiers.... :-)

  • User Authentication using Servlet and JSp

    Hi,
    I am developing a web app where i need to implement user Authentication to allow members to view and upload files on a certain directory say /data
    For this i am using a servlet as a controller which then forwads request to other jsps/servlets based on user response. I tried using servlet mapping in web.xml so that all browser requests would be directed to controller servlet and would branch from there on. However the problem all RequestDispatcher.forward() requests redirected to the servlet putting it in a loop.
    Is there another way to achieve this. (Apart from using form-based Basic Authentication).
    I am using Resin 1.2.8 servlet/jsp container.
    Any response as soon as possible would be appreciated.
    Thanks,
    Kushagra

    RequestDispatcher.forward() cause the HTTP request to be sent through the request processing flow as if the original request for the resource being forwarded to.
    It seems the servlet mapping you are talking about in web.xml should be made more specific. i.e. the mapping should be such that only your so called controller servlet will match up.
    You might want to specify the mapping for the controller servlet to be noticeably/effectively different from the mapping for other servlets and JSPs.

  • Two processes using Servlet

    Hi,
    I have implemented an algorithm to solve a problem that takes about 2-4 min using servlet. I want to show some gif while my algorithm runs on the browser (e.g. "please wait!" running across screen or something like that).
    I don't know how to do that. Kindly guide me (some tutorial link may help).

    See this thread. It may help.
    http://forum.java.sun.com/thread.jspa?threadID=554229&messageID=2713586

  • Call java class by using servlet

    i written simple servlet with doGet(0. I need call java class when i run servlet
    my requirement is when i start the server i will call servlet it will redirect to another page.
    but before that servlet will run java class. which i have written externally.
    i need to run java class by using servlet then it will redirect to another page.
    could you give the proper solution

    You don't call classes - you call methods.
    There's nothing special about servlets except the requirement that they implement HttpServlet. Servlets and other classes they interact with all get compiled into WEB-INF/classes on the server.
    To forward a request to, say, "other.jsp" you do:
    getServletContext().getRequestDispatcher("/other.jsp").forward(request,response);

  • Implementing SingleThreadModel on a Servlet

    Can someone explain to me what are the implications of implementing SingleThreadModel on a Servlet?
    I have this servlets that serves images "on-the-fly" to the browsers, my first version was not implementing SingleThreadModel and was accessed mainly by XMLHttpRequest, assynchronously, but then i only had to get a image at a time to a given page.
    Now i have several images on a page, so it was starting giving problems, so i remove the assynchronous access and implemented SingleThreadModel, it seems ok but i wonder what the implications are.
    Should i create two servlets for one/many images? Should i not implement SingleThreadModel and take care of the threads myself? Or is ok using SingleThreadModel ?
    Thanks all

    The implications are that you make that servlet a bottleneck, because requests to it cannot run in parallel. The fix for this is not to handle threads for yourself. That is what the servlet container is for. The fix is to modify your servlet so that it is thread-safe. The first major step here is to stop using static and instance variables to store data, although I can't imagine why a servlet that serves out an image file would need to use variables in that way. There may be more complexities but if you understand threading properly you should be able to track them down.

  • Open Jasper Report in new page using servlet

    Guys,
    Looks very simple but i am having problem making this process work. I am using 11.1.1.4
    This is my use case:
    - From a employee page, user clicks on a menu item to open report for current employee. I need to pass appropriate report parameters to servlet and open report into new page.
    I can successfully call servlet using commandmenuitem and set request parameters and call servlet from backing bean.... but that doesn't open report in a new page.... any way i can do this?
    Another option i tried was that using gomenuitem and setting target=blank but in that case i need to pass the parameter using servlet url which i like to avoid.(in case i need to pass many parameters in future) (also values will be set on page so i need to generate url when then click the menuitem...... so there are some hoops and loops i need to go through) I don't know a way to pass the request parameter using backing bean to servlet... i don't think it is possible.
    Those are the two approaches i tried.
    If you have any better approach...I would appreciate if you can let me know. (i have searched on internet for two days now.... for the solution)
    -R
    Edited by: polo on Dec 13, 2011 7:22 AM

    Hi,
    Hope following will useful
    http://sameh-nassar.blogspot.com/2009/10/using-jasper-reports-with-jdeveloper.html
    http://www.gebs.ro/blog/oracle/jasper-reports-in-adf/

  • How to define target window when redirecting within frames using servlet?

    Howdy:
    Is there a way to define target window when redirecting within frames using servlets?
    How to do it in JSP as well?
    T.I.A.
    Oriental Spirit

    Your servlet (or JSP) can't decide where it is going to be displayed. The browser has already decided that when it makes the request to your servlet.

  • Using servlet to generate XML file

    What I want to do is simple but can't work. Hope you guys can give me a hint.
    I succesfully generate XML file in command line using Oracle XML parser and class generator. Then I was trying to do it using servlet. it compiles fine but generate NullPointer exception at the line:
    Emp e1= new Emp(); //Emp is the root of XML
    I suspect the Emp constructor can't correctly find the globalDTD in its superclass -CGDocument. Please note this only happens in servlet setting, not is command line setting. Any suggestion to get arounf this?
    Another unrelated question is that when I create a XML file using the Oracle XML parser, it seems all the elements a file has to be added once, otherwise the compiler will compalain about the missing element. this will be inconvinient when I constructing a big XML file, which I 'd liek to split into small piece and add them up. Maybe there is a good way but I just don't know it.
    my email: [email protected]

    Hi,
    I'm running into the same problem deploying the classes generated by the class generator. Code works fine from JDeveloper, but had to put my DTD in the directory where my classes are. Deploying the classes with Apache's JServ gives me a NullPointer exception on the first addNode method. I guess it can't find the DTD. I tried to put the DTD in many locations but this didn't fix the problem. Any suggestions?
    Steve,
    Did you fix this problem? Thanx!
    null

Maybe you are looking for