Questions on Servlets

I don't know WHERE the Oracle team came up with my username (mine was TheWhiteKnight), but it's funny guys.... Thanks for the laugh.
ANYwho....
I have a question. I currently am creating some objects with getter and setter methods. For example, I have created a Department object that has 4 protected static variables that coincide with the database fields for the department table in a database. I have a getter and setter method for each variable, as well as a loader, saver, updater, and validator methods. I have the object auto-validate it's info before setting the variable's. Here is the code:
(what happened to our tag?)
public class Department {
     static final Logger Dept4j = Logger.getLogger(Department.class);
      * Each variable name lines up with the database fields.
      * Database Table - Departments
     protected static int DEPARTMENT_ID;
     protected static String DEPARTMENT_NAME;
     protected static int PARENT_DEPARTMENT_ID;
     protected static boolean STATUS;
     public static String validationErrorMessage;
     public Department() {
          super();
     public int getDepartmentId() {
          return DEPARTMENT_ID;
     public static void setDepartmentId(int deptId) {
          if (validateAllDepartmentIdFields(deptId))
               DEPARTMENT_ID = deptId;
     public String getDepartmentName(){
          return DEPARTMENT_NAME;
     public static void setDepartmentName(String deptName) {
          if(validateDepartmentName(deptName))
               DEPARTMENT_NAME = deptName;
     public int getParentDepartmentId() {
          return PARENT_DEPARTMENT_ID;
     public static void setParentDepartmentId(int deptParentId) {
          if (validateAllDepartmentIdFields(deptParentId))
               PARENT_DEPARTMENT_ID = deptParentId;
     public boolean getDepartmentStatus() {
          return STATUS;
     public static void setDepartmentStatus(boolean deptStatus) {
          if (validateDepartmentStatus(deptStatus))
               STATUS = deptStatus;
Simple enough concept.  I'll not post the rest of the class as it's not relevant.  I want to be able to write a generic servlet to be able to pass all objects to (Department, User, Occupation, etc) and be able to get and set info from an HTML page reusing the same servlet to show all of the public get / set methods that I open up.  What I DON'T want to do is pass resultsets around grabbing metadata and use <% %> scriptlet tags in the front end.  I could go the custom route of writing my own tags and passing everything that way, but I'd like a different way to do this.  I'm wondering if there is any realistic way I can call a generic sort of "get all getters / setters" and populate a page of DDL's / fields with that.  I think I already have the answer, but I'd like to hear it from someone else to confirm it.  BTW, I'm using Tomcat 6.0.18 - 6.0.2x for this. Not sure if it actually matters. 
Any insight is greatly appreciated.  And as always constructive criticism is always welcomed.
- Josh                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Using a Map instead of that class might be a good alternative to a point, but i think I'll have to end up using a class like this for at least a few things. a Map might work for somethings, I'm trying to not use any scriptlets in the JSP pages if I can I help it.
Clearing the static out of that class fixed the issues. Thank you.

Similar Messages

  • Synchronize question in servlet

    Hello everybody!
    I have some question regarding synchronization in a servlet, and hope someone can help me.... (see example code below)...
    1) The methods "getNames(), addNames(), removeNames()" need to be synchronized due to that the "names" vector can be accessed by many at the same time, right?
    2) Do I need to synchronize the method "addANumber()"? why/why not?
    3) Do I need to synchronize the methods "setString(), getString()" placed in the "Test" class? why/why not?
    4) All "global" variables, i.e. the variables declared as object or class variable, need to be synchronized. Is this valid for servlet methods as well? For example the addANumber() method, or whatever method (that doesnt use global variables) I place in the Servlet class (ASR-class)
    Please all your experts out there, help me.....
    Thanx in advanced
    TheMan
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    public class ASR extends HttpServlet {
        private Vector names;
        private ServletConfig config;
        public void init(ServletConfig config) throws ServletException {
              synchronized(this) {
                this.config=config;
                names = new Vector(100,10);
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            response.setContentType("text/plain");
            PrintWriter out = response.getWriter();
            //add a name to the vector
            String theName = request.getParameter("inpName");
            addNames(theName);
            //get the vector and print that name
            Vector tmp = getNames();
            int pos = Integer.parseInt(request.getParameter("number"));
            out.println("a person " + tmp.get(pos));
            addANumber(pos);
            //remove a name
            removeNames(pos);
            //create a test object
            Test t = new Test();
            //set a string in the test object
            t.setString("yyy");
            //print that string
            out.println("test string: " + t.getString());
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            doGet(request, response);
        //needs to be synchronized?
        public int addANumber(int number){
            int adding = number + 10;
            return adding;
        public synchronized Vector getNames(){
            return names;     
        public synchronized void addNames(String theName){
            names.add(theName);
         public synchronized void removeNames(int pos){
             names.remove(pos);
    class Test {
        public String str = "xxx";
        //needs to be synchronized????
        public void setString(String str){
            this.str = str;
         //needs to be synchronized????
        public String getString(){
            return str;
    }

    The teachers, which are responsible for the
    servlet-courses that I have taken, never spoke about
    the member variables, in the same way you did. They
    used member variables and synchronized methods or
    synchtronized code blocks to access them. They never
    said that "one should not/try not to use member
    variables". I can understand this in the context of using Servlets to gain understanding on some of the issues involved with multithreading. In a classroom, servlets may pose an easier laboratory (so to speak) for learning threading concepts than something like nachOS or something like that.
    For example, they made a ordinary "page counter",
    i.e. a counter which increases by one for each "hit"
    on the page. I that example they, and I, thought it
    would be a good idea to use a member variable (a int
    counter), since all instances of the servlet will use
    the same variable. How should one construct such page
    otherwise? Local variables and databases is one way.As mentioned in an earlier post, in the real world I can think of very few reasons as to why a particular servlet may need to keep state. In terms of keeping a counter, what you would probably do is to analyze the access logs...Yes -- not a programmatic solution, but a very doable, low maintenance, and quick one. One important lesson to learn is that not all problems are best solved in code. This is probably not the right answer for a test though...
    I just got a bit confused, my teachers had no problem
    with member variables, but you guys recomend me to
    use local variables instead. Which leader should I
    follow :) ?Capitalist answer: whoever pays you :) Seriously, why not talk to your teachers about what you have learned here versus what they are teaching?
    - N

  • Question about servlet architecture

    Hello,
    I have a question about Web Application / servlet architecture and development, and haven't had any luck finding an answer so far. My plan must be either unusual, or wrong, or both, so I'm hoping the community here could point me in the right direction.
    I have quite a bit of background in OSGi, but very little in servlets. I know my architecture would work with something such as sever-side Equinox, but for the open source project I'm contemplating, I think that the more mainstream Tomcat/servler route would be better -- assuming it can be done. Here is a rather simplified scenario:
    There is a class, Manager. It could be a Java class that implements Runnable, or a non-HTTP servlet (GenericServlet?), but somehow it should be configured such that it runs as soon as Tomcat starts.
    When Manager runs, it instantiates its primary member variable: Hashtable msgHash; mshHash will map Strings (usernames) to ArrayList<String> (list of messages awaiting that user). Manager also has two primary public methods: addMsg() and getMsgs().
    The pseudocode for addMsg is:
    void addMsg(String username, String msg) {
    if username=="*" { for each msgList in msgHash { msgList.add(msg) } return;
    if username not in msgHash { msgHash.add(username, new ArrayList<String>) }
    msgHash[username].add(msg)
    And for getMsgs():
    String getMsgs(username) {
    String s = "";
    for each msg in msgHash[username] { s = s + msg; }
    return s;
    Once Manager has started, it starts two HTTP Servlets: Sender and Receiver, passing a reference back to itself as it creates the servlets.
    The HTML associated with Sender contains two text inputs (username and message) and a button (send). When the send button is pressed and data is POSTed to Sender, Sender takes it and calls Manager.addMsg(username.value, message.value);
    Receiver servlet is display only. It looks in the request for HTTP GET parameter "username". When the request comes in, Receiver calls Manager.getMsgs(username) and dumps the resulting string to the browser.
    In addition to starting servlets Sender and Receiver, the Manager object is also spawning other threads. For example, it might spawn a SystemResourceMonitor thread. This thread periodically wakes up, reads the available disk space and average CPU load, calls Manager.addMsg("*", diskAndLoadMsg), and goes back to sleep for a while.
    I've ignored the synchronization issues in this example, but during its lifecycle Manager should be idle until it has a task to do, using for example wait() and notify(). If ever addMsg() is called where the message string is "shutdown", Manager's main loop wakes up, and Manager shuts down the two servlets and any threads that it started. Manager itself may then quit, or remain resident, awaiting a command to turn things back on.
    Is any of this appropriate for servlets/Tomcat? Is there a way to do it as I outlined, or with minor tweaks? Or is this kind of application just not suited to servlets, and I should go with server-side Equinox OSGi?
    Thanks very much for any guidance!
    -Mike

    FrolfFla wrote:
    Hello,
    I have a question about Web Application / servlet architecture and development, and haven't had any luck finding an answer so far. My plan must be either unusual, or wrong, or both, so I'm hoping the community here could point me in the right direction.
    I have quite a bit of background in OSGi, but very little in servlets. I know my architecture would work with something such as sever-side Equinox, but for the open source project I'm contemplating, I think that the more mainstream Tomcat/servler route would be better -- assuming it can be done. Here is a rather simplified scenario:
    There is a class, Manager. It could be a Java class that implements Runnable, or a non-HTTP servlet (GenericServlet?), but somehow it should be configured such that it runs as soon as Tomcat starts.You can configure a servlet to be invoked as soon as Tomcat starts. Check the tomcat documentation for more information on that (the web.xml contains such servlets already though). From this servlet you can start your Manager.
    >
    When Manager runs, it instantiates its primary member variable: Hashtable msgHash; mshHash will map Strings (usernames) to ArrayList<String> (list of messages awaiting that user). Manager also has two primary public methods: addMsg() and getMsgs().
    The pseudocode for addMsg is:
    void addMsg(String username, String msg) {
    if username=="*" { for each msgList in msgHash { msgList.add(msg) } return;
    if username not in msgHash { msgHash.add(username, new ArrayList<String>) }
    msgHash[username].add(msg)
    And for getMsgs():
    String getMsgs(username) {
    String s = "";
    for each msg in msgHash[username] { s = s + msg; }
    return s;
    Once Manager has started, it starts two HTTP Servlets: Sender and Receiver, passing a reference back to itself as it creates the servlets. Not needed. You can simply create your two servlets and have them invoked through web calls, Tomcat is the only one that can manage servlets in any case. Servlets have a very short lifecycle - they stay in memory from the first time they are invoked, but the only time that they actually do something is when they are called through the webserver, generally as the result of somebody running the servlet through a webbrowser, either by navigating to it or by posting data to it from another webpage. The servlet call ends as soon as the request is completed.
    >
    The HTML associated with Sender contains two text inputs (username and message) and a button (send). When the send button is pressed and data is POSTed to Sender, Sender takes it and calls Manager.addMsg(username.value, message.value);
    Receiver servlet is display only. It looks in the request for HTTP GET parameter "username". When the request comes in, Receiver calls Manager.getMsgs(username) and dumps the resulting string to the browser.This states already that you are going to run the servlets through a browser. You run "Sender" by navigating to it in the browser. You run "Receiver" when you post your data to it. Manager has nothing to do with that.
    >
    In addition to starting servlets Sender and Receiver, the Manager object is also spawning other threads. For example, it might spawn a SystemResourceMonitor thread. This thread periodically wakes up, reads the available disk space and average CPU load, calls Manager.addMsg("*", diskAndLoadMsg), and goes back to sleep for a while.Since you want to periodically run the SystemResourceMonitor, it is better to use a Timer for that in stead of your own thread.
    >
    I've ignored the synchronization issues in this example, but during its lifecycle Manager should be idle until it has a task to do, using for example wait() and notify(). If ever addMsg() is called where the message string is "shutdown", Manager's main loop wakes up, and Manager shuts down the two servlets and any threads that it started. Manager itself may then quit, or remain resident, awaiting a command to turn things back on.
    Is any of this appropriate for servlets/Tomcat? Is there a way to do it as I outlined, or with minor tweaks? Or is this kind of application just not suited to servlets, and I should go with server-side Equinox OSGi?
    Thanks very much for any guidance!
    -MikeI don't see anything that cannot be done in a normal java web environment, as long as you are aware of how servlets operate.

  • Question about servlet.xml setting

    <?xml version="1.0" encoding="UTF-8"?>
    <!-- Example Server Configuration File -->
    <Server port="8025" shutdown="TEARSDOWN">
    <!-- Comment these entries out to disable JMX MBeans support used for the
    administration web application -->
    <Listener className="org.apache.catalina.core.AprLifecycleListener"/>
    <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener"/>
    <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
    <Listener className="org.apache.catalina.storeconfig.StoreConfigLifecycleListener"/>
    <!-- Global JNDI resources -->
    <GlobalNamingResources>
    <!-- Test entry for demonstration purposes -->
    <Environment name="simpleValue" type="java.lang.Integer" value="30"/>
    <!-- Editable user database that can also be used by
    UserDatabaseRealm to authenticate users -->
    <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
    <Resource name="jdbc/mp" auth="Container"
    type="javax.sql.DataSource" driverClassName="oracle.jdbc.driver.OracleDriver"
    url="jdbc:oracle:thin:@172.25.43.224:1521:mp"
    username="mpuser" password="mp" maxActive="20" maxIdle="10"
    maxWait="-1"/>
    <Resource name="jdbc/passport" auth="Container"
    type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://218.1.14.134:3306/xmnext_passport?autoReconnect=true"
    username="zhouzhijun" password="zhouzhijun*1234567" maxActive="20" maxIdle="10"
    maxWait="-1"/>
    </GlobalNamingResources>
    <!-- Define the Tomcat Stand-Alone Service -->
    <Service name="Catalina">
    <!-- Define a non-SSL HTTP/1.1 Connector on port 8080 -->
    <Connector URIEncoding="utf-8" acceptCount="100" connectionTimeout="20000" disableUploadTimeout="true" enableLookups="false" maxHttpHeaderSize="8192" maxSpareThreads="75" maxThreads="150" minSpareThreads="25" port="8084" redirectPort="8443"/>
    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector enableLookups="false" port="8009" protocol="AJP/1.3" redirectPort="8443"/>
    <!-- Define the top level container in our container hierarchy -->
    <Engine defaultHost="localhost" name="Catalina">
    <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase" />
    <!-- a Realm is setUp for JOSSO -->
    <Realm className="org.josso.tc55.agent.jaas.CatalinaJAASRealm"
    appName="app1"
    userClassNames="org.josso.gateway.identity.service.BaseUserImpl"
    roleClassNames="org.josso.gateway.identity.service.BaseRoleImpl"
    debug="1" /> // I am not sure realm can set twice like this?
    <Host appBase="webapps" autoDeploy="false" name="localhost" unpackWARs="true" xmlNamespaceAware="false" xmlValidation="false">
    <!-- a Valve for JOSSO -->
    <Valve className="org.josso.tc55.agent.SSOAgentValve" debug="9" /> when I set this valve, the tomcat seems running abnormal...
    </Host>
    </Engine>
    </Service>
    </Server>
    Could you help me to check this file setting? Just check this "servlet.xml". Thank you very much!

    <?xml version="1.0" encoding="UTF-8"?>
    <!-- Example Server Configuration File -->
    <Server port="8025" shutdown="TEARSDOWN">
    <!-- Comment these entries out to disable JMX MBeans support used for the
    administration web application -->
    <Listener className="org.apache.catalina.core.AprLifecycleListener"/>
    <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener"/>
    <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
    <Listener className="org.apache.catalina.storeconfig.StoreConfigLifecycleListener"/>
    <!-- Global JNDI resources -->
    <GlobalNamingResources>
    <!-- Test entry for demonstration purposes -->
    <Environment name="simpleValue" type="java.lang.Integer" value="30"/>
    <!-- Editable user database that can also be used by
    UserDatabaseRealm to authenticate users -->
    <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
    <Resource name="jdbc/mp" auth="Container"
    type="javax.sql.DataSource" driverClassName="oracle.jdbc.driver.OracleDriver"
    url="jdbc:oracle:thin:@172.25.43.224:1521:mp"
    username="mpuser" password="mp" maxActive="20" maxIdle="10"
    maxWait="-1"/>
    <Resource name="jdbc/passport" auth="Container"
    type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://218.1.14.134:3306/xmnext_passport?autoReconnect=true"
    username="zhouzhijun" password="zhouzhijun*1234567" maxActive="20" maxIdle="10"
    maxWait="-1"/>
    </GlobalNamingResources>
    <!-- Define the Tomcat Stand-Alone Service -->
    <Service name="Catalina">
    <!-- Define a non-SSL HTTP/1.1 Connector on port 8080 -->
    <Connector URIEncoding="utf-8" acceptCount="100" connectionTimeout="20000" disableUploadTimeout="true" enableLookups="false" maxHttpHeaderSize="8192" maxSpareThreads="75" maxThreads="150" minSpareThreads="25" port="8084" redirectPort="8443"/>
    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector enableLookups="false" port="8009" protocol="AJP/1.3" redirectPort="8443"/>
    <!-- Define the top level container in our container hierarchy -->
    <Engine defaultHost="localhost" name="Catalina">
    <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase" />
    <!-- a Realm is setUp for JOSSO -->
    <Realm className="org.josso.tc55.agent.jaas.CatalinaJAASRealm"
    appName="app1"
    userClassNames="org.josso.gateway.identity.service.BaseUserImpl"
    roleClassNames="org.josso.gateway.identity.service.BaseRoleImpl"
    debug="1" /> // I am not sure realm can set twice like this?
    <Host appBase="webapps" autoDeploy="false" name="localhost" unpackWARs="true" xmlNamespaceAware="false" xmlValidation="false">
    <!-- a Valve for JOSSO -->
    <Valve className="org.josso.tc55.agent.SSOAgentValve" debug="9" /> when I set this valve, the tomcat seems running abnormal...
    </Host>
    </Engine>
    </Service>
    </Server>
    Could you help me to check this file setting? Just check this "servlet.xml". Thank you very much!

  • Question about servlet in a package

    hello
    i use tomcat4.0,and write a simple servlet "Hello.java",put it in "C:\jakarta-tomcat-4.0\webapps\ee\WEB-INF\classes",i input "http://127.0.0.1:8080/ee/servlet/Hello",the code works well,but after i add a package declaration "package hi;" in front of my servlet,and put it in "C:\jakarta-tomcat-4.0\webapps\ee\WEB-INF\classes\hi\",wheather i input "http://127.0.0.1:8080/ee/hi/servlet/Hello" or "http://127.0.0.1:8080/ee/servlet/hi/Hello",both of them don't work,why?and how can i call a servlet that is in a package from the browser? thanks!
    my code:
    package hi;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Hello extends HttpServlet{
         public void service(HttpServletRequest req,
              HttpServletResponse resp)
              throws IOException,
                   ServletException{
              resp.setContentType("text/html");
              PrintWriter out=new PrintWriter(resp.getOutputStream());
              out.print("<html>");
              out.print("<body>");
              out.print("hello world!");
              out.print("</body>");
              out.print("</html>");
              out.close();

    Hi,
    Open your ee/web-inf/web.xml file and add these lines.
    <servlet>
    <servlet-name>
    Hello
    </servlet-name>
    <servlet-class>
    hi.Hello
    </servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>
    Hello
    </servlet-name>
    <url-pattern>
    /Hello
    </url-pattern>
    </servlet-mapping>
    Start the tomcat and give the URL,
    http://127.0.0.1:8080/ee/servlet/Hello
    Hope this helps.
    If you don't have a web.xml file there, you can add these lines in your Tomcat\conf\web.xml file.
    Sudha

  • Help - A few questions on Servlets.

    Is Connection an Interface or Class?
    Can a class extend HttpServlet & implement Applet?
    Apart from res.SendRedirect(), what are the other methods of redirecting to a servlet/JSP from a servlet?
    In a single page, without using frames, can we have the upper part(kind of header) & lower part(kind of footer) be represented by one servlet & the middle part of the page be represented by another servlet?

    Is Connection an Interface or Class?Depends which "Connection" you are talking about, but the API documentation for it will tell you that.
    Can a class extend HttpServlet & implement Applet?No, Applet isn't an interface. I can't see any point in doing that anyway.
    Apart from res.SendRedirect(), what are the other
    methods of redirecting to a servlet/JSP from a
    servlet?There's a forward() method, but it doesn't "redirect" in the technical meaning of the term. It does result in transferring control from one servlet to another, however.
    In a single page, without using frames, can we have
    the upper part(kind of header) & lower part(kind of
    footer) be represented by one servlet & the middle
    part of the page be represented by another servlet?What does "represented by" mean here?

  • One question about Servlet

    Container will use HttpServletRequest and HttpServletResponse objects to encapsulate
    a special HTTP request(received from WebClient) and Response gernerated by servlet
    My qeustion is :
    if same webclient requests two times, then Container will use same HttpServletRequest
    and HttpServletResponse objects or use different objects for each time?

    The Container can implement this any way it wants. You should NOT assume that the request and response objects are the same for each cycle.

  • General Question about Servlet !!!

    Hello my name is Raj,
    My problem as a beginner is to compile a servlet but not servlet alone becoz theres a several class imported in this servlet.
    Should I compile every .java and then the servlet....coz when I compile the servlet with a normal jdk (latest one) it gives error of importing class...
    Well at first I have an error of path where the servlet.jar not included..but I managed to work it out...
    what should I do...
    regards,
    raj aryan maholtra

    hi raj,
    your assumption is right, you need to compile Some.java first & then compile MyServlet.java. Ensure that Some.class is in a classpath that can be found by MyServlet
    Regards,
    sathish
    Well Miss v sreedevi ,
    I did the classpath and still it doesnt work compile
    coz of the importing class...
    My .java files looks like this in the folder under the
    tomcat-webapps-servlet
    -MyServlet.java
    -Some.java
    And I import the Some.java in my MyServlet.java
    stuff.
    Well should I compile the Some.java stuff first and
    then the MyServlet.java....
    regards,
    raj

  • Some question about servlet

    wy my jdk don't have the class javax.servlet.* and javax.servlet.http.*;

    Servlets are included in j2ee api.
    Servlets is an open specification given by sun the vendors has to implement the specifications.
    like:TOMCAT,WEBLOGIC.
    For the above reasons that is not included in JDK.These packages available with servlet-api.jar which is coming with tomcat.
    You can get servlet packages in j2ee api also.

  • Newbie Question - Accessing Servlet Class file

    im trying to run my servlet class file but am not able to do so. I've compiled my servlet and the class file generated is under build...web-inf/classes as it should be. Now how i do access this through the browser , isnt it just not localhost:29080/MyWebApp/HelloServlet. Thanks
    -newbie

    Hi There,
    Are you using Java Studio Creator to develop your application? If so this tutorial will help you get started.
    http://developers.sun.com/prodtech/javatools/jscreator/learning/tutorials/2/jscintro.html
    Please also visit the tutorials page at
    http://developers.sun.com/prodtech/javatools/jscreator/learning/tutorials/index.jsp
    Thanks
    K

  • Question about Servlets

    Hi,
    I am running WebSphere and when i put my sevlets directly under the classes folder and map it in the web.xml file, they seem to work fine.
    But when i try to put those servlets in few folders under classes folder, its not able to find it.
    I even mapped my servlet like this
    <servlet id="Servlet_5">
    <servlet-name>CurrentworkflowReport</servlet-name>
    <display-name>CurrentworkflowReport</display-name>
    <description>CurrentworkflowReport</description>
    <servlet-class>arm.pdm.CurrentworkflowReport</servlet-class>
    </servlet>
    <servlet-mapping id="ServletMapping_3">
    <servlet-name>CurrentworkflowReport</servlet-name>
    <url-pattern>arm.pdm.CurrentworkflowReport</url-pattern>
    </servlet-mapping>
    Could you please tell me what i am doing wrong.
    Thanks in advance

    try:
    <url-pattern>/CurrentworkflowReport</url-pattern>

  • File generating question in servlet

    Dear all,
    I've generated online reports using servlet. Now I need to export these reports to excel at clients' local machine. How to generate the excel file at client's side? or Is that a way to invoke a dialog box to let the user choose the directory to download the file generated at the server side? Somebody says there's an existing funciton in asp to do that. I don't know whether servlet has same function. If anyone knows the answer or could give me a hint, I greatly appreciate that.
    Regards,
    Grace

    Simply change the format of the response content type to be Excel application/vnd.ms-excel... Even if you throw HTML, Excel will parse it and display it as an Excel sheet.
    The only disadvantage I have seen is that, you will not be able see Hyperlinks, Images, etc...
    Let us say u have a HTML Table like:
    <TABLE>
    <TR>
    <TD>Pazhanikanthan</TD>
    <TD>URL</TD>
    <TD><IMG SRC='http://www.pazhanikanthan.com/images/test.gif'></IMG></TD>
    <TR>
    </TABLE>
    In the HTML you would have seen a static text, Hyperlink and the Image. But when you try to open the same table in Excel, what happens is Excel does not recognise the HTML Tags and then parses them and only takes up the content which it can display so u will be seeing only a single cell containing the content
    Pazhanikanthan
    I believe that is a feature which we cannot change... if in case u need to do such things, then you might have to go for special APIs like JExcel, JIntegra, etc.
    These wont be suitable for your case as you do not want anything to be done in the server side.
    Thanks and regards,
    Pazhanikanthan. P

  • Two questions about servlets

    Hi,
    I'd like to ask you some questons about servlets :
    1) do servlets need a particular JVM on the server. I mean RMI servers need to be started on the server side, while usual applets are loading into the client browser. Are servlet beeing loaded by the browser or do they require something specific on the server side?
    This is because I can only post files on my server, but can't execute java code
    2) can servlets access the server files ? This is because my applets can only load files within the codebase directory on the server. However, i'd like to be able to get something like File.lisFiles() on the server's content. With applets, I have a security problem
    Thanks a lot.
    vincent

    Hi,
    1) Servlets need to be run (deployed) on an application server (i.e. WebLogic, Websphere) which works in conjunction with the web server. When the web server (HTTP Server) receives a request for a servlet from a browser, it passes the request to the application server where the servlet is deployed on which handles the request and provides a response. The JVM will be included in the application server.
    2) Servlets do NOT run in the sandbox that applets run in and thus have complete access to file on the server. This is because the site running the servlets know exactly what code they're deploying on their server and thus have no security concerns.
    If you're site is running on an ISP's server, then you're likely out of luck unless they give you admin access to an application server that runs on their server which allows you to deploy servlets onto.
    makes sense?...
    vc

  • A general design question using servlets

    Hello all,
              We have 2 WebLogic app./web servers. Lets call the first one Server A and
              the other Server B. Server A shows a web page to the client/browser and that
              has links to Server B. Now there is some authentication information that
              needs to be passed to Server B too. We were thinking of embedding that
              information in the web page itself. So a link on a page served by Server A
              could look like:
              Login to Server B
              Now the issue with such a solution is that the login token is exposed to the
              browser and the client. This would lead to the token being copied and pasted
              for replay attacks on Server B. I was thinking of better ways to solve this
              issue. PLease let me know if you have faced such issues earlier and a better
              solution using Servlets/JSP etc..
              Thanks.
              

              Either use a cookie by setting its domain name your two servers share, or add very
              short timeout. In later case, you generate the token with very short timeout in
              one server, use redirect to send the request to the second server, then use the
              session objects in both servers to indicate the user login. When you logout, you
              need kill the session objects on both servers.
              "Gaurav Khanna" <[email protected]> wrote:
              >Hello all,
              >
              >We have 2 WebLogic app./web servers. Lets call the first one Server A
              >and
              >the other Server B. Server A shows a web page to the client/browser and
              >that
              >has links to Server B. Now there is some authentication information that
              >needs to be passed to Server B too. We were thinking of embedding that
              >information in the web page itself. So a link on a page served by Server
              >A
              >could look like:
              >Login to Server
              >B
              >
              >Now the issue with such a solution is that the login token is exposed
              >to the
              >browser and the client. This would lead to the token being copied and
              >pasted
              >for replay attacks on Server B. I was thinking of better ways to solve
              >this
              >issue. PLease let me know if you have faced such issues earlier and a
              >better
              >solution using Servlets/JSP etc..
              >
              >
              >Thanks.
              >
              >
              

  • Hi a question on Servlets

    how to access a properties file from Servlet
    because to get access to servlets we cannot ask user to login as localhost & all those things

    how to access a properties file from Servlet Which properties file ?
    You can use the getResourceAsStream to load a properties file.
    getResourceAsStream("package/my.properties");or you can use the Servet Configuration Parameters to get the name of the properites file. but this is not portable and against the J2EE specification.
    You can use the ServletContext to determine the real path of your web context and calculate the absulte path of the properties file which is stored
    context relative.
    String webInfDir = getServletConfig().getServletContext().getRealPath("/WEB-INF");
    because to get access to servlets we cannot ask user to login as localhost & all those things???
    andi

Maybe you are looking for