Servlet Methods

Hi all,
Can anyone pls tell me how to access a servlet method from a simple java file. I want to access a parameter from a servlet from a simple java file which is run by a process in linux and which is not a part of my web application. I tried to do it this way :
my servlet code :
public class MonitorServlet extends HttpServlet
     private static final long serialVersionUID = 1L;
     String lastPollingTime = null;
     public void init()
          lastPollingTime = AccessServerManager.lastPollDate;
     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
          request.setAttribute("lastPollingTime", lastPollingTime);
and I am trying to retrieve the value of "lastPollingTime" in my java file like this :
HttpServletRequest request = null;
String strLastPollDate = (String) request.getAttribute("lastPollingTime");
trying this I am not able to get the value of the "lastPollingTime".
Can anybody plese help...all the comments are welcome..
regards
horizon7

Yeah I can guess what is going wrong: NullPointerException. Which is blatantly obvious because you declare request as a null-reference in your console application but then you invoke a method on that null reference.
the request object is created by the webserver when a request is made by a client and is therefore only available in the servlet or jsp that handles the request. You have absolutely no way to access this object from the console application (which will most likely run in a different JVM instance altogether), so I would suggest rethinking the design of the application.
A better design would be to let a servlet output XML to the client with the lastPollingTime as an xml element. Then from your console application you can use URLConnection to fetch the output from the servlet and parse the XML output to get the lastPollingTime.

Similar Messages

  • How can I call a servlet method from a javascript function

    I want to call l a servlet method from a javascript function.
    Does any one have an example of code.
    Thinks in advance

    Actually, as long as the servlet returns valid javascript, you can indeed "call it" from the client. It will initiate a request and return the result to the browser.
    This example uses Perl, but it could be easily modified to go to a servlet instead.
    Note that it is only supported in DOM browsers (IE6+/NN6+/etc)
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
    <html>
    <head>
    <title> Test server-side JS </title>
    </head>
    <body>
    <script type="text/javascript">
    function checkIt(variable, value)
    var newScript = "cgi-bin/validateJS.cgi?"+variable+"="+value;
    var body = document.getElementsByTagName('body').item(0)
    var scriptTag = document.getElementById('loadScript');
    if(scriptTag) body.removeChild(scriptTag);
    script = document.createElement('script');
    script.src = newScript;
         script.type = 'text/javascript';
         script.id = 'loadScript';
         body.appendChild(script)
    </script>
    <p>Test.</p>
    <form id="f1" action="">
    <input type="text" name="t1" id="t1" onChange="checkIt(this.name, this.value)">
    </body>
    </html>
    validateJS.cgi
    #!/opt/x11r6/bin/perl
    use CGI qw(:all);
    my @valArray = split(/=/,$ENV{QUERY_STRING});
    print "Content-type: text/javascript\n\n";
    # myPass is the password
    $myPass = "foobar";
    if ("$valArray[1]" eq "$myPass")
    print "alert(\"Success!!\")";
    else
    print "alert(\"Failure!!\")";

  • Mapping the servlets' methods

    take a look at the following please:
    package somePackage;
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class Employees extends HttpServlet {
         private static final long serialVersionUID = 1L;
         public Employees() {
            super();
         protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              MapAction(request, response);
         protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              MapAction(request, response);
         public void MapAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              String action = request.getParameter("act");
              if(action == null) ShowEmployees(request, response);
              else if(action.equals("1")) InsertEmployee(request, response);
              else if(action.equals("2")) UpdateEmployee(request, response);
              else if(action.equals("3")) DeleteEmployee(request, response);
              else ShowBadRequestError(request, response);
         public void ShowEmployees(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         public void InsertEmployee(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         public void UpdateEmployee(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         public void DeleteEmployee(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         public void ShowBadRequestError(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }as you can see that i am mapping the query string "act" (which represent an action on the servlet) to one of the servlets' methods using
    the basic Switch statement, i know that this addressed under web frameworks specially MVCs, but so far am looking for the ways i can
    handle that using generic code rather than using framework, so are there any other ways to map to the servlet methods other than switch
    or if statements?

    Take a look at the various REST implementations out there. Another possibility is to use reflection to map some kind of construct such as Service#Method to automatically locate the problem class and method to invoke.
    As an aside, your methods other than doGet and doPost should probably be private.
    - Saish

  • Calling servlets methods

    Hi,
    I have a servlet which calculates values i.e. calcServlet. I have another servlet which contains a method which uses JFreechart to plot values in a line chart i.e. plotServlet.
    I want to pass the values in calcServlet to the method in plotServlet which will then be displayed in a web page.
    Now I thought I could do something like the following in calcServlet:
    plotServlet ps = new plotServlet();
    ps.plotChart(values[]);This doesn't seem to be working and I keep getting an error saying getWriter has been called twice...From what I've read it isn't the correct way to call the method anyhow. It can be called from a html form (This isn't suitable for me)...
    I would really appreciate if someone would give me a simple example on how to call another servlet method.
    Many thanks in advance.

    Don't do it!
    As the other poster said, create a graphing class. I'll call it MyGraphClass. This class is not a servlet! It is a pure graphing generator.
    You can give it a method like this: public void output(OutputStream out) { }. The calc servlet would then have code like this:
    myGraphClass = new MyGraphClass(...);
    myGraphClass.process(data);
    OutputStream out = response.getOutputStream();
    myGraphClass.output(out);Do you see how this works?
    The cool thing here is you can use this MyGraphClass in many contexts. Maybe you want to use it for something totally different, like a GUI application that displays data, etc. It has no dependencies on servlets. All it does is generate its output.
    Oh and don't forget, you need to set the output content type or the image will not display!

  • Calling non standard servlet methods

    How can we call the non standard servlet methods like OPTIONS, HEAD, TRACE, etc.? Like to call the GET method of the servlet located on server xyz from some HTML page, we write the HTML form as follows :
    <form name="frmname" action="http://xyz.com/servlet/MyServlet" "method=get">
    So what should we write to call the other methods?
    Ankit.

    You can't do it directly from HTML, you need to open a connection over HTTP and then send the appropriate HTTP request. Not all web servers support these methods.

  • Calling a servlet method from another class

    hi...
    if i make a servlet (that keeps the log for website users' logins and logouts, for example) and i want a method that adds an entry into a logfile, for example:
    public void log(String line) {
    //put "line" into some log file...
    and then i set this servlet to loadonstartup, how can i call the log() function from other classes or servlets? can i do it without making the servlet an entry in servletContext?
    im sorry if i'm not being very clear, the caffeine's getting to me...
    thanks
    lazlo

    I don't know, why would you do that anyway? Just make an ordinary class, not a servlet, and make "log" a static method in that class. (If you need initialization, use a static initializer.) Put that class where the real servlet can see it and call it from there.

  • Open File in a Servlet-Method

    Hi @ all,
    I want to open a simple textfile in my Servlet-Java Method
    on a Resin Aplication Server. But I don't know how I have
    to build my path. I actually don't know on which plattform
    the Resin is running (not I set up the Resin), but I think its a Windows- or Unix-PC.
    How should I build the path? ("../test.txt" or "c:\resin\tmp\test.txt")
    Thanks and bye
    Ben

    Forward slashes works fine on Windows. Backslash does not work on unix. And "c:" does not exist on unix. So of the two you mention, "../test.txt" is far more portable.
    Other options are to require the filename (or directory) in the startup parameters for the servlet, or to use ClassLoader.getResource().

  • Servlet Methods - doGet, doPost

    Hi,
    I understoot that GET request -> doGet(), POST request-> doPost() methods are overrids by the HttpServlets....
    do we need to use both methods in the Servlets class..?
    For example, I am sending POST request into the Servlets class... so i can override only doPost()  method to handle the client inputs

    There they are just for?
    Just read the HttpServlet API [1] documentation. It shall be clear. If you don't understand the HTTP spec [2] either, I highly reommend you to read that too.
    [1] http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpServlet.html
    [2] http://www.w3.org/Protocols/rfc2616/rfc2616.html

  • How to invoke a Servlet method from application

    please help me.the scenario is as follows
    1)a servlet is placed on the server and application has invoked servlet with URL and URL Connection class
    but how do i call a certain method of servlet on the server from the application.Let suppose the servlet's method to be invoked is print(String s).How it can be done from application.

    As GrayMan suggested, Servlets are intended to be used for HTTP communication.
    If you want to open common logic to multiple clients, use EJBs, CORBA or some type of Web Service (SOAP, XML-RPC).
    When you send a request to a servlet, the doPost or doGet method will be invoked. Products such as STRUTS allow you do 'map' to other classes. I suggest avoiding this.
    Personally, I avoid STRUTS like a bad disease. Using STRUTS instead of just learning Servlets/JSP adds a lot of overhead. I prefer performance over development time. A good example of this is that ANY request that comes in over the WEB has ALL variables from the calling page (text boxes, radio buttons and such) made avaialable through the HttpServletRequest.getParameter(String parameterName) method. STRUTS requires you to build a subclass of it's ActionForm classes that is nothing more than a JavaBean with fields that match that of the web page. STRUTS will look at all the parameters in the request and all the fields in the Bean and assign any matches from the request to the Bean. The Bean is instanciated and the matching logic performed just to give you access to objects you already have access to.
    Just my 2 cents, avoid STRUTS like an STD.

  • How to call a specific method in a servlet from another servlet

    Hi peeps, this post is kinda linked to my other thread but more direct !!
    I need to call a method from another servlet and retrieve info/objects from that method and manipulate them in the originating servlet .... how can I do it ?
    Assume the originating servlet is called Control and the servlet/method I want to access is DAO/login.
    I can create an object of the DAO class, say newDAO, and access the login method by newDAO.login(username, password). Then how do I get the returned info from the DAO ??
    Can I use the RequestDispatcher to INCLUDE the call to the DAO class method "login" ???
    Cheers
    Kevin

    Thanks for the reply.
    So if I have a method in my DAO class called login() and I want to call it from my control servlet, what would the syntax be ?
    getrequestdispatcher.include(newDAO.login())
    where newDAO is an instance of the class DAO, would that be correct ?? I'd simply pass the request object as a parameter in the login method and to retrieve the results of login() the requestdispatcher.include method will return whatever I set as an attribute to the request object, do I have that right ?!!!!
    Kevin

  • Concurrent processing of POST requests and automatic flushing of the servlet response buffer in WLS6.1.

              Hi all,
              I encountered the following 2 servlet problems in WLS 6.0/ 6.1:
              1. Processing concurrent POST requests
              WLS seems to disallow concurrent executions of any servlet's doPost servlet method.
              When two clients attempt to send a request to a servlet using POST, the socond
              one
              is blocked until the first customer is served. In essence, the servlet ends up
              operating in
              1-user mode. I just learned from Jervis Liu that the problem is solved in WLS6.0
              if you disable http-keepalive.
              For WLS 6.1 a partial workaround is to make the servlet work in a single-thread
              mode (by implementing the javax.servlet.SingleThreadModel interface). In this
              case,
              WLS dispatches concurrent requests to different instances of the servlet.
              This doesn't completely eliminate the problem - still only one customer can be
              connected at a time. The improvement is that once the first customer is disconnects,
              the second can be served even if the doPost method for the first has not finished
              yet.
              2. Flushing the response buffer in WLS 6.1
              The servlet response buffer is not flushed automatically until doPost ends, unless
              you
              explicitly call response.flushBuffer(). Closing the output stream doesn't flush
              the
              buffer as per the documentation.
              I see that other people are experiencing the same problems.
              Has anyone found any solutions/workarounds or at least an explanation.
              Any input would be highly appreciated.
              Thanks in advance.
              Samuel Kounev
              

    Thanks for replying. Here my answers:
              > Did you mark your doPost as synchronized?
              No.
              > Also, try testing w/ native i/o vs not ... is there a difference?
              With native I/O turned off I get a little lower performance, but the
              difference is not too big.
              Best,
              Samuel Kounev
              > Peace,
              >
              > --
              > Cameron Purdy
              > Tangosol Inc.
              > << Tangosol Server: How Weblogic applications are customized >>
              > << Download now from http://www.tangosol.com/download.jsp >>
              >
              > "Samuel Kounev" <[email protected]> wrote in message
              > news:[email protected]...
              > >
              > > Hi all,
              > >
              > > I encountered the following 2 servlet problems in WLS 6.0/ 6.1:
              > >
              > > 1. Processing concurrent POST requests
              > >
              > > WLS seems to disallow concurrent executions of any servlet's doPost
              > servlet method.
              > >
              > > When two clients attempt to send a request to a servlet using POST, the
              > socond
              > > one
              > > is blocked until the first customer is served. In essence, the servlet
              > ends up
              > > operating in
              > > 1-user mode. I just learned from Jervis Liu that the problem is solved in
              > WLS6.0
              > >
              > > if you disable http-keepalive.
              > >
              > > For WLS 6.1 a partial workaround is to make the servlet work in a
              > single-thread
              > >
              > > mode (by implementing the javax.servlet.SingleThreadModel interface). In
              > this
              > > case,
              > > WLS dispatches concurrent requests to different instances of the servlet.
              > > This doesn't completely eliminate the problem - still only one customer
              > can be
              > >
              > > connected at a time. The improvement is that once the first customer is
              > disconnects,
              > > the second can be served even if the doPost method for the first has not
              > finished
              > > yet.
              > >
              > > 2. Flushing the response buffer in WLS 6.1
              > > The servlet response buffer is not flushed automatically until doPost
              > ends, unless
              > > you
              > > explicitly call response.flushBuffer(). Closing the output stream doesn't
              > flush
              > > the
              > > buffer as per the documentation.
              > >
              > > I see that other people are experiencing the same problems.
              > >
              > > Has anyone found any solutions/workarounds or at least an explanation.
              > > Any input would be highly appreciated.
              > >
              > > Thanks in advance.
              > >
              > > Samuel Kounev
              =====================================================
              Samuel D. Kounev
              Darmstadt University of Technology
              Department of Computer Science
              DVS1 - Databases & Distributed Systems Group
              Tel: +49 (6151) 16-6231
              Fax: +49 (6151) 16-6229
              E-mail: mailto:[email protected]
              http://www.dvs1.informatik.tu-darmstadt.de
              http://skounev.cjb.net
              =====================================================
              [att1.html]
              

  • How to send Oracle rowid to servlet? | Problem with national characters.

    There is same possibility how to send rowid to servlet?
    I have now definition like this:
    <af:image source="/imageservlet?Par1=#{bindings.Col1.inputValue}"/>
    But If column contents national characters, servlet methods obtained changed these characters.
    My idea is to use not primary key for row, but use oracle rowid. It is simply possible?
    Use something like this:
    <af:image source="/imageservlet?Rowid=#{bindings.Rowid}"/
    Or Do you have ideas how to solve problem with national characters ?
    Thanks
    FiL

    Hi,
    Although your workaround works.
    I think this is a simple encoding problem.
    I simply need to make sure all parameters and pages are encoded with a char set which contains the national characters you mentioned.
    This is a bit dependent on the exact technology your using, but most can be done via the web.xml:
      <jsp-config>
          <jsp-property-group>
              <url-pattern>*.jsp</url-pattern>
              <page-encoding>UTF-8</page-encoding>
          </jsp-property-group>
      </jsp-config>     This forces all JSP pages to be encoded in UTF-8
    Adding the following parameter sometimes helps as well, although I think this one is a bit dated:
    You said your using a servlet so your servlet needs a similar block for its pattern
      <context-param>
        <param-name>PARAMETER_ENCODING</param-name>
        <param-value>UTF-8</param-value>
      </context-param>If you want to be 100% sure the encoding is set right make sure thepages contain:
    <%@ page contentType="text/html;charset=utf-8"%>Or depending on your view technology the syntax can be a bit different
    -Anton

  • Thread Safe Issue with Servlet

    I saw the following statement in one of the J2EE compliant server documentations:
    "By default, servlets are not thread-safe. The methods in a single servlet instance are usually executed numerous times simultaneously (up to the available memory limit)."
    I'm quite concerned with this statement for the primary reason that (I'm trying to reason by reading it out loud) servlets are not going to be thread-safe especially when available memory hit really really low!! So, when the application is still having sufficient memory, we will not likely run into concurrency problems, i.e the happy scenario for a short period after server is started. BUT, good things don't last long.. Anyway, hope someone can explain to me with more insights. Thanks.

    Don't worry, memory occupation and thread safety are not related at all.
    In my opinion, the following is the meaning of the statement you quote.
    Since the servlet specification doesn't force any implementation to spawn a new servlet object upon each request (and this should be a real memory hit!), nor to synchronize calls to servlet methods, you should always code your servlet in a "stateless" fashion: you should be aware the same method on the same object could (and probably will) be called concurrently if multiple concurrent client requests are submitted.
    Hope I've been clear enough...

  • How to convert old Java Servlets to OSGi "Servlet" Bundles

    Hello I'm looking for some help/insight on the best way to convert some of our old Java Servlet code into new OSGi Bundles that can be accessed as servlets.  I'd like to be able to install the new bundles then access them on one of our CQ instance using something like "/servlet/servlet_name".
    So far I've been able to create a new bundle, and install it into CQ but I haven't been able to access the bundle at the servlet mapping URL that I would expect.  So far what I've found online has lead me to believe that I need to use the Felix Annotations to describe my servlet.
    @Component(immediate = true, metatype = true, label = "Servlet Name")
    @Service
    @Properties({
        @Property(name = Constants.SERVICE_DESCRIPTION, value = "Servlet Name"),
        @Property(name = "sling.servlet.methods", value={"GET"}),
        @Property(name = "sling.servlet.paths", value = "/servlet/my_servlet_mapping"),
        @Property(name = Constants.SERVICE_VENDOR, value = "VendorName")
    public class TellAFriend extends HttpServlet {...
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
    Once I have this installed, and running without an error in the logs for CQ I tried to go on my local instance to http://localhost:4502/servlet/my_servlet_mapping but I only get 404 Resource Not Found errors.  I've even gone to the Sling Resource Resolver and it doesn't resolve to anything either.
    Is there more than the Servlet Information need into the Annotations to convert "old" code into a new OSGi Servlet Mapped Bundle?

    I must be missing something else configuration wise since I created a new Servlet basically using the code you provided above.  I deployed it as part of the bundle that I'm trying to create.
    The bundle installs and stars fine but I still can't access the servlet.  Are there CRXDE based configurations that are requried too to configure Servlets. 
    Here's my test servlet file.  I tried going to http://localhost:4502/servlet/TestCQServlet and just get the same 404 error I'm getting for the other 2 Servlets Java classes in my Bundle.
    import java.io.IOException;
    import javax.servlet.ServletException;
    import org.apache.felix.scr.annotations.sling.SlingServlet;
    import org.apache.sling.api.SlingHttpServletRequest;
    import org.apache.sling.api.SlingHttpServletResponse;
    import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
    @SlingServlet(paths = "/servlet/TestCQServlet", methods = "GET")
    public class TestCQServlet extends SlingSafeMethodsServlet {
        // @Reference
        // private Repository repository;
        private static final long serialVersionUID = 6239754936223276983L;
        @Override
        protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
            response.setHeader("Content-Type", "application/json");
            response.getWriter().print("whatever");

  • DB row lock from servlet.

    Hi to all,
    we're developing a J2EE application (with NO Ejb, actually we cannot use them) in which users can select orders from a DB2 database, modify the order, or create a new order. Any order is implemented by a class (Order.java) that exposes methods to execute SELECTs, INSERTs and UPDATEs to the db2 order table; the class mantains a Connection to the database and it's responsible to manage the connection, resultset, prepared statement and so on, and it's possible to specify if we want only read data (executing a select) or read for update the data (so, executing a select ... for update).
    Users can access the data via web: the instances of Order are created by a servlet, which load the data and show them passing the Order instance to a JSP that fills up a form.
    The problem is we want to lock the row corrisponding to the data mapped into Order instance. Initially, we thought we can instantiate an Order, load data with a select for update, saving on a session the instance, and redirect to the Jsp for visualization, without closing the connection; when the user send data via a form, the order is retrieved from the session, updates are performed and session closed. Unluckily, this approach does not work 'cause the Web Container rolls back automatically all unclosed connection. The row lock is lost.
    In very few words, we are trying to keep-alive a Connection after a Servlet method ends. It seems that Servlet specification 2.3 does not allow this, while specification 2.2 does.
    How can we avoid this problem ? We cannot just implement an application-level Lock manager, because the database is a legacy database and data are concurrently accessed by legacy applications.
    Any suggestion would be very appreciated.
    Thanx in advance !
    Claudio.

    Heck (can you say "hec|<" or will the **** filter nuke it?), I had a reply all written up.
    And then I noticed you were cross-posting.
    Please don't.

Maybe you are looking for

  • NEW! Free Dreamweaver templates WITH Fireworks vector files

    I just released some free Dreamweaver templates that include not only the Dreamweaver template dwt file, but also the original pre-sliced Fireworks file with all the template graphics. The templates include the dwt, Fireworks file, pure CSS menus, ar

  • Implementing Logging in Web Dynpro

    Hi All,      I was able to define a new Log Controller of type location and able to write the traces(logs) into the default trace file according to the severity. But When i change  the severity for the exsisting Log Configurator "com.sap.tc.webdynpro

  • Windows 8 Printer over network offline -HP

    Hello I am using windows 8 in my office.I have installed HP Laserjet 1020 on one system and I have shared it. Now on another PC i have installed it as a network  shared printer. But the problem is it shows offline after reboot.Sometimes though it wor

  • Recovery not completing

    Hello,  I have a A105-2091 that I am trying to restore. The recovery disk loads the RAMDRIVE, pauses and says "PLEASE WAIT", the cursor appears for a few seconds and the machine reboots, starting the process over, and over, and over.... BIOS is at 2.

  • Vista 32 vs. 64-bit; B

    How can I find out if my Vista Home OS is 32 or 64 bit's? And whether or not it is BETA?