A Servlet question...

hi,
What happen to the Servlet if there are thousands Forms were being submitted ? Will there be thousands of instances of doGet or doPost being created to handle the requests ? My answer is NO, but I am not quite clear why ? Would you please explain ?
Thanks !
P

You're right, the answer is no, because there's no such thing as an instance of a method. However, generally a server will create a certain number of threads to concurrently handle requests, and once it has as many threads as it's configured to, queues the rest of the requests. I think typically each thread will create an instance of the servlet. Here's some documentation from javax.servlet.http.HttpServlet:
Servlets typically run on multithreaded servers,
so be aware that a servlet must handle concurrent
requests and be careful to synchronize access to shared resources.
Shared resources include in-memory data such as instance or class variables and external objects
such as files, database connections, and network
connections. See the
Java Tutorial on Multithreaded Programming for more
information on handling multiple threads in a Java program.
Anyone have corrections or additions?

Similar Messages

  • Basic jsp and servlet question (JSP Model 2)

    Hi
    I want to make an website where i use JSP Model 2 architecture. However I got a basic question
    1. I need to separate business logic from presentation with the use of jsp and servlets. Meaning I want no html code in the servlet. Can you give a simple example of how this can be done? If I map my implementation of httpServlet to a jsp page in web.xml and override doPost() and doGet(). The calls to the jsp page comes to the servlet as it should. I want to process some methods (calling sessionbeans or similar which in turn calls entitybeans) and then show the jsp page.
    How do I show the jsp page without mixing html in the servlet as I've done below:
    doGet(HttpServletRequest req, HttpServletResponse res)
    PrintWriter p = response.getWriter();
    p.print("<html><body>Hello world</body></html>"); //I dont want to do //this, I want to display the JSP site
    doPost(HttpServletRequest req, HttpServletResponse res)
    //doSomething
    }Message was edited by:
    CbbLe

    You should treat your servlet class much like a controller, where you can then use JSP as the view. The way you achieve this is to use the forward() method in RequestDispatcher.
    Say you've got a servlet class org.yoursite.controller.YourController:
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
      //Set some value for use in the JSP file associated wth me
      req.setAttribute("greeting", "Hello world!");
      //Done with our business logic, off we go to the JSP file
      ServletContext app = getServletContext();
        RequestDispatcher disp;
        disp = app.getRequestDispatcher("/some/jsp/file.jsp);
        disp.forward(req, resp);
    }Now in your JSP file:
    <h1>Example</h1>
    <div>
      I just want to say <%= request.getAttribute("greeting") %>
    </div>Going to that servlet now executes business logic and then points to the JSP file for the view. You can forward from servlet to servlet too if needs be. The string you pass to forward() is whatever would be in the URI of the request so any <servlet-mapping> configurations in web.xml are used ;)
    There is some pretty in-depth documentation on the J2EE blueprints website, namely service-to-worker and front-controller patterns. I dare say if you're looking for this sort of code you'll want to look at the composite view pattern too (also on blueprints).

  • Basic Servlet question

    I have a servlet that reads information from a logfile and displays it on the page. The log file is being written as users login and logout to the application. I want the log file to be renamed at midnight exactly to current date. My question is should I have a thread that sleeps till date change and then renames the file and distroy itself. I am new to programming. Would every webuser will be sharing the same thread or every webuser will have a seprate instance of the thread.
    little sample code would be helpfull.
    Thanks in advance!!!

    I would have a thread that sleeps until midnight, then calls a method in your logfile class to have it rename itself and start a new log file. While the renaming occurs, you can synchronize the logging or suspend the logging.

  • Servlet questions

    Hi you all,
    I have been using servlets for the last 2 months, but I still have a couple of questions I haven't found the answer to:
    1 - "A Servlet stays in memory between requests." --> But for how long? When a servlet is first requested it stays in memory (JVM), to process further requests... But for how long does it stays there? until the gc is called? And if the user userA makes a request for the servlet servletA, will the servlet servletA be available to process the request for the userB? I know that only a copy of a servlet is load into the JVM, but does this mean that the JVM will only have one instance for a given servlet?
    2 - "When the Servlet is initialized, its service(ServletRequest req, ServletResponse res) method is called for every request to the Servlet. The method is called concurrently (i.e. multiple threads may call this method at the same time) so it should be implemented in a thread-safe manner."
    Should I use sincronized methods here?? If a servlet is processing a request, and another request is made, won�t the container create a queue of request to be processed by the servlet?
    These are some of the questions I am having at the moment...
    Can anyone give me any hints on them?
    Thanks in advance,
    MeTitus

    Sorry for bringing this old post to the top again, but I havent found the answers to the questions I posted... and since I am in the beginning with servlets, I think I really must understand how everything works. Can anyone help me on this matter, I would very much appreciate your help.
    Many thanks,
    Marco

  • Another URL/Servlet question...

    Say a user types in:
    http://www.ttonline.org?country=italy/
    In the servlet that services this request, how can I retrieve the string "italy" ?
    Would it be something like
    String value = req.getParamter("country") ?
    And what do you call the stuff on the right hand side of the question mark ? Is that the query string?
    Just in case you want to know why I would have such a URL, is because we want to have different URLs for each country so we can track the number of hits from each country.
    Many thanks,

    In your doGet (or a method performed from the doGet) do the following
         String[]  countries = request.getParameterValues("country");
         // this block of code is to find the form that has been submitted and
         // get the value of the parameter as appropriate.  Each HTML page
         // can only have one instance of a variable name regardless of how
         // many forms it contains.
         if countries != null  && countries .length > 0) {     
              country  = countries [0];     
         }That will get you the parameter value you are looking for.
    good luck!

  • A really good servlet question

    I have a command line driven program on my web server. I need to write a servlet that will...
    start the program
    send the program commands
    return the results of the commands to a webpage
    my guess on what I need to do to accomplish this is to some how manipulate the stdin and stdout. can this be accomplished from a servlet? Does any one know where I might find some example of simular code? or maybe a tutorial on java stdin and stout?
    Ron_W

    Thanks you scsi_boy for your response.. After looking at your code, I think I have only one more question. If run.exec() returned a process that continuously loops until a use types in some key (like 'Q' for quit) could java interact with that process? or more to the point.....
    BufferedReader br = new BufferedReader(new InputStreamReader(perlProcess.getInputStream()));if the above code can read the output from a running process, can the below code send strings to that process?
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(perlProcess.getOutputStream()));Thanks Ron_W

  • Repeated acces to shared resources in servlets question.

    Hello everybody,
    I've made a few servlets by now and i was wondering if it is safe to use the following code if lots of users acces the servlet at approximately the same time. (multi-threaded not single-threaded servlet).
    public class someServlet ..
    private String receivedParam;
    private HttpSession session;
    //A function that receives the request
    public void receiveRequest(HttpServletRequest req,HttpServletResponse res)
    session = req.getSession();
    receivedParam = req.getParam("param");
    session.setAttribute("Action",receivedParam);
    Do Something using sesion and receivedparam...
    Is It better to do the following:
    public class someServlet ..
    //A function that receives the request
    public void receiveRequest(HttpServletRequest req,HttpServletResponse res)
    String receivedParam =null;
    HttpSession session =null;
    session = req.getSession();
    receivedParam = req.getParam("param");
    session.setAttribute("Action",receivedParam);
    Do Something using sesion and receivedparam...
    Lots of feedback appreciated.

    NO! You dumb ass !
    It's not safe!Replying to yourself after almost 2.5 years must be great!!! :-)

  • Javascript pop-up in servlets question

    I have a problem when i call a pop-up script it actually opens a blank screen upon clicking. I would like to know how do i make sure that when i click that it doesent direct to me a new page. I just want to stay in the same page.
    I tried using return in the end but still no solution.
    if (successCons) {
         output.println("<html>");
         output.println("<body>");
         output.println(" <SCRIPT LANGUAGE='JavaScript'>");
         output.println("alert('Surgery successfully assigned to the customer')");
         output.println(" </SCRIPT> ");
         output.println("</html>");
         output.println("</body>");
         return;
       }Thanks

    If that was true i wouldn't have a chance
    to make a javascipt alert box pop up.It is true. Your argument falls apart because Java, and servlets, having nothing to do with javascript, don't prevent, control, or modify javascript functionality.
    The point was, ask how to do the javascript functionality in a javascript forum. You might want to test it out on a couple static HTML pages first, because Servlets are just a means of delivering HTML content to the browser (if that HTML contains javascript or not).

  • Jsp to get info out of servlet question

    Hey, I'm looking for a good site or tutorial with examples in how to get info out of a bean or servlet.
    for example I have a bean that querys a db for info. how do I print that info to a jsp page with out using the out.printWriter? I know I need to use the <jsp:useBean...
    but after I instantiate the bean how do I pull info off of it?

    The Sun Java Developer site has a tutorial for almost everything. Check out the J2EE tutorial at http://java.sun.com/j2ee/tutorial/1_3-fcs/index.html
    There is a section on using JavaBeans in JSP pages.

  • General JSP-Servlet question

    Hi! All
    I created a web application using JSP and without using a single servlet. A friend of mine suggests that JSP should never be used by itself. JSP and servlets should go hand in hand.
    Is there a drawback to the application created using only JSP?
    Please advice.

    Whenever you are writing a web application,you should use MVC architecture. That is a better approach for performance and scalability
    To quote from J2EE Patterns Catalog
    <MVC>
    Several problems can arise when applications contain a mixture of data access code, business logic code, and presentation code. Such applications are difficult to maintain, because interdependencies between all of the components cause strong ripple effects whenever a change is made anywhere. High coupling makes classes difficult or impossible to reuse because they depend on so many other classes. Adding new data views often requires reimplementing or cutting and pasting business logic code, which then requires maintenance in multiple places. Data access code suffers from the same problem, being cut and pasted among business logic methods.
    The Model-View-Controller design pattern solves these problems by decoupling data access, business logic, and data presentation and user interaction.
    </MVC>

  • Tomcat servlet question.

    I created a really simple servlet named Log ( "Hello World") that was created in a Packet called World.
    When I try to run this servlet using
    http://1#.3#.1#4.1#9:8080/World/servlet/Log
    Tomcat generated this error :
    Error: 500
    Location: /World/servlet/Log
    Internal Servlet Error:
    java.lang.NoClassDefFoundError: Log (wrong name: World/Log)
         at java.lang.ClassLoader.defineClass0(Native Method)
    How can I call this servlet ?
    I has been using servlets with websphere without problems.
    Thanks in advance.

    JSP's don't have to be registered but they can. Servlets that are not in packages can be put directly into WEB-INF/classes and not registered.
    As a caveat,this may not apply for all servers. I know that weblogic requires that all servlets be registered and mapped to an alias.

  • Servlet question, pls help

    We have a jsp page with servlet works well in a server. Now we need to move it to another server (server2). I copied jsp page and a jar file that compiles all the class files (servlet) into the server2 and modified web.xml file in server2 too for servlet definition and URL mappings. When I run the servlet - http://www.company.com/myservlet, I got the error of "The server encountered an unexpected condition which prevented it from fulfilling the request".
    I am just wondering if I need to recompile the jar file in server2 or I missed some procedure to deploy the application? What should I do to make a servlet works in a new server?
    Thanks for your help in advance?

    hopefully, when you say server1 and server2 we are not saying these servers support different versions of JSP and Servlet.
    make sure they do support the same thing, otherwise if server1 supports new versions and your servlets/jsp use those, server2 will complain.
    you can go ahead and grab those dirty stack trace and let me know what you found out.

  • Simple Servlet question, pls help

    This is my form submission part in my jsp page
    <form name="updateForm" method="POST" action="/Update"> This is my web.xml
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <!DOCTYPE web-app
        PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app>
      <servlet>
        <servlet-name>/Update</servlet-name>
        <servlet-class>UpdateMap</servlet-class>
      </servlet>
    </web-app>This is my UpdateMap.java
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    public class UpdateMap extends HttpServlet
        public UpdateMap()
    }I put my UpdateMap.class in WEB-INF/classes/ directory but when I clicked the submit button in my jsp page, I got The requested resource (/Update) is not available error

    Found my own error. The jsp submission code should be
    <form name="updateForm" method="POST" action="Update"> But I still got error when submit
    The specified HTTP method is not allowed for the requested resource ( POST method of HTTP is not supported by this URL.)Pls help.
    Thanks

  • Hi plz check it out servlets question

    <a href:/servlet/HelloServlet>post</a>
    <a href:/servlet/HelloServlet method = "post">post</a>
    in both cases which method processed.. whether it doGet() or doPost() or what..
    plz answer for this qestion
    regards
    sampath

    what about learning some HTML first?
    <a href="servlet/HelloServlet">post</a>
    <!--
        NOT <a href:/servlet/HelloServlet>post</a>
    --> this will create a normal hyperlink with the caption "post" and the related URL "servlet/HelloServlet"
    <a href:/servlet/HelloServlet method = "post">post</a>depending on the browser this might create a hyperlink but when you click on it it should produce an error...
    A "normal" hyperlink generates a GET request to the server (as e.g. a url directly typed to the address bar).
    when you use forms (<form>) you could specify that the browser should use an other method
    <form method="POST" action="servlet/HelloServlet">
        <input type="submit" value="SUBMIT">
    </form>to see which method will be invoked / processed by your hyperlink you could do the following:
    - implement ALL available doXXX methods
    - add one line of code to each of them: System.out.println("processing a XXX request...") // where XXX is the type of method (see doXXX, e.g. Get, Post, ...)

  • Handling servlet errors

    I know its not the proper place to ask servlet questions, but I am really left thinking. I am developing a login application and I wanto to display the error messages in the login.jsp, which are thrown by the LoginServlet.
    I justw ant to display my custom messages in the same login page saying : "Your username must me 8 characters long" or whatever. I dont want to go to a different error.jsp page.
    Any suggestions would be greatly appreciated. I am looking for something like adding to ActionErrors and then catching them in jsp pages using <html:errors> as we do in Struts.
    Sudarshan

    Hi,
    in a simple scenario, I created a message in the session (attribute) and reference it on the JSP page
    ${sessionScope.message}
    Frank

Maybe you are looking for