Retrieve ServletContext from non-servlet class

A servlet calls a method which is located in another class which is not a servlet. Within this method of the non-servlet class, i need to access the ServletContext of the servlet that has called the method. What i am currently doing is simply passing the ServletContext as a parameter to the method.
I would like to avoid passing the ServletContext all the time, so i'm wondering if it's possible, from the non-servlet class, to retrieve the ServletContext of the servlet which has called the method of the non-servlet class.

Thanks J-Fine, that's a smart suggestion. BTW in the meantime i figured out that passing the ServletContext is not that bad idea, after all it reflects the structure of the app. However if i'll change my mind again i'll do like you suggested.

Similar Messages

  • Accessing ServletContext from non-servlet class

    How i can get information servletcontext from a normal java class?
    I am using Tomcat.
    I have put some Strings in to the servlet context and i want to get this information from a normal java class.
    I think there was a way to do it with getServlet() but this is deprecated.

    One way to do this would be to store the info in some class of your own as a static member(arraylist/hashmap or something) and then retrieve it from your java class.
    May you can populate static field i the init() method of one of your servlet and have that servlet load on tomcat startup.

  • Read web.xml from a non-servlet class

    Hi all, I need to read the web.xml file fron a standard class in a web project.
    I know how to do it from a servlet or a jsp page, but is it possible to do from a non-servlet class?
    Thank you,
    Gabriele

    It's a XML file. So best approach would be to use some Java-XML API to parse the XML file into useable nodes. E.g. JAXP, DOM4J, JXPath, etc.

  • Non-servlet class in servlet program

    hi,
    I declare a non-servlet class which is defined by myself in a servlet class. I passed the complie but got an runtime error said NoClassDefFoundError. Does anyone can help me? Thanks.
    The following is my code.
    //get the search string from web form
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.net.*;
    import java.util.*;
    public class SearchEngines extends HttpServlet {
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {   
    String searchString = (String) request.getParameter("searchString");
         String searchType = (String) request.getParameter("searchType");
         Date date = new java.util.Date();
         response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    Vector doc_retrieved = new Vector();
    BooleanSearch bs = new BooleanSearch();
    doc_retrieved=bs.beginSearch(searchString, searchType);
    out.println("<HTML><HEAD><TITLE>Hello Client!</TITLE>" +
                   "</HEAD><BODY>Hello Client! " + doc_retrieved.size() + " documents have been found.</BODY></HTML>");
    out.close();
    response.sendError(response.SC_NOT_FOUND,
    "No recognized search engine specified.");
    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    doGet(request, response);
    // a search engine implements the boolean search
    import java.io.*;
    import java.util.*;
    import au.com.pharos.gdbm.GdbmFile;
    import au.com.pharos.gdbm.GdbmException;
    import au.com.pharos.packing.StringPacking;
    import IRUtilities.Porter;
    public class BooleanSearch{
         BooleanSearch(){;}
         public Vector beginSearch(String searchString, String searchType){
              Vector query_vector = queryVector(searchString);
              Vector doc_retrieved = new Vector();
              if (searchType.equals("AND"))
                   doc_retrieved = andSearch(query_vector);
              else
                   doc_retrieved = orSearch(query_vector);
              return doc_retrieved;
         private Vector queryVector(String query){
         Vector query_vector = new Vector();
              try{
                   GdbmFile dbTerm = new GdbmFile("Term.gdbm", GdbmFile.READER);
              dbTerm.setKeyPacking(new StringPacking());
              dbTerm.setValuePacking(new StringPacking());
              query = query.toLowerCase();
              StringTokenizer st = new StringTokenizer(query);
              String word = "";
              String term_id = "";
              while (st.hasMoreTokens()){
                   word = st.nextToken();
                   if (!search(word)){
                        word = Stemming(word);
                        if (dbTerm.exists(word)){
                   //          System.out.println(word);
                             term_id = (String) dbTerm.fetch(word);
                             query_vector.add(term_id);
              catch(GdbmException e){
                   System.out.println(e.getMessage());
              return query_vector;
         private Vector orSearch(Vector query_vector){
              Vector doc_retrieved = new Vector();
              try{
                   GdbmFile dbVector = new GdbmFile("Vector.gdbm", GdbmFile.READER);
                   dbVector.setKeyPacking(new StringPacking());
                   dbVector.setValuePacking(new StringPacking());
                   int doc_num = dbVector.size();
                   String doc_id = "";
                   String temp = "";
                   for (int i = 1; i <= doc_num; i++){
                        boolean found = false;
                        doc_id = String.valueOf(i);
                        temp = (String) dbVector.fetch(doc_id);
                        StringTokenizer st = new StringTokenizer(temp);
                        while (st.hasMoreTokens() && !found){
                             temp = st.nextToken();
                             StringTokenizer st1 = new StringTokenizer(temp, ",");
                             String term = st1.nextToken();
                             if (query_vector.contains(term)){
                                  doc_retrieved.add(doc_id);
                                  found = true;
              catch(GdbmException e){
                   System.out.println(e.getMessage());
              return doc_retrieved;
         private Vector andSearch(Vector query_vector){
              Vector doc_retrieved = new Vector();
              try{
                   GdbmFile dbVector = new GdbmFile("Vector.gdbm", GdbmFile.READER);
                   dbVector.setKeyPacking(new StringPacking());
                   dbVector.setValuePacking(new StringPacking());
                   int doc_num = dbVector.size();
                   String doc_id = "";
                   String temp = "";
                   for (int i = 1; i <= doc_num; i++){
                        Vector doc_vector = new Vector();
                        boolean found = true;
                        doc_id = String.valueOf(i);
                        temp = (String) dbVector.fetch(doc_id);
                        StringTokenizer st = new StringTokenizer(temp);
                        while (st.hasMoreTokens()){
                             temp = st.nextToken();
                             StringTokenizer st1 = new StringTokenizer(temp, ",");
                             String term = st1.nextToken();
                             doc_vector.add(term);
                        for (int j = 0; j < query_vector.size(); j++){
                             temp = (String) query_vector.get(j);
                             if (doc_vector.contains(temp))
                                  found = found & true;
                             else
                                  found = false;
                        if (found)
                             doc_retrieved.add(doc_id);
              catch(GdbmException e){
                   System.out.println(e.getMessage());
              return doc_retrieved;
         private String Stemming(String str){
              Porter st = new Porter ();
              str = st.stripAffixes(str);
              return str;          
         private boolean search(String str){
              //stop word list
              String [] stoplist ={"a","about","above","according","across","actually","adj","after","afterwards","again",
                                       "against","all","almost","alone","along","already","also","although","always","am","among",
                                       "amongst","an","and","another","any","anyhow","anyone","anything","anywhere","are",
                                       "aren't","around","as","at","away","be","became","because","become","becomes","becoming",
                                       "been","before","beforehand","begin","beginning","behind","being","below","beside",
                                       "besides","between","beyond","billion","both","but","by","can","cannot","can't",
                                       "caption","co","co.","could","couldn't","did","didn't","do","does","doesn't","don't",
                                       "down","during","each","eg","eight","eighty","either","else","elsewhere","end","ending",
                                       "enough","etc","even","ever","every","everyone","everything","everywhere","except",
                                       "few","fifty","first","five","for","former","formerly","forty","found","four","from",
                                       "further","had","has","hasn't","have","haven't","he","he'd","he'll","hence","her","here",
                                       "hereafter","hereby","herein","here's","hereupon","hers","he's","him","himself","his",
                                       "how","however","hundred","i'd","ie","if","i'll","i'm","in","inc.","indeed","instead",
                                       "into","is","isn't","it","its","it's","itself","i've","last","later","latter","latterly",
                                       "least","less","let","let's","like","likely","ltd","made","make","makes","many","maybe",
                                       "me","meantime","meanwhile","might","million","miss","more","moreover","most","mostly",
                                       "mr","mrs","much","must","my","myself","namely","neither","never","nevertheless","next",
                                       "nine","ninety","no","nobody","none","nonetheless","noone","nor","not","nothing","now",
                                       "nowhere","of","off","often","on","once","one","one's","only","onto","or","other","others",
                                       "otherwise","our","ours","ourselves","out","over","overall","own","per","perhaps","pm",
                                       "rather","recent","recently","same","seem","seemed","seeming","seems","seven","seventy",
                                       "several","she","she'd","she'll","she's","should","shouldn't","since","six","sixty",
                                       "so","some","somehow","someone","sometime","sometimes","somewhere","still","stop",
                                       "such","taking","ten","than","that","that'll","that's","that've","the","their","them",
                                       "themselves","then","thence","there","thereafter","thereby","there'd","therefore",
                                       "therein","there'll","there're","there's","thereupon","there've","these","they","they'd",
                                       "they'll","they're","they've","thirty","this","those","though","thousand","three","through",
                                       "throughout","thru","thus","to","together","too","toward","towards","trillion","twenty",
                                       "two","under","unless","unlike","unlikely","until","up","upon","us","used","using",
                                       "very","via","was","wasn't","we","we'd","well","we'll","were","we're","weren't","we've",
                                       "what","whatever","what'll","what's","what've","when","whence","whenever","where",
                                       "whereafter","whereas","whereby","wherein","where's","whereupon","wherever","whether",
                                       "which","while","whither","who","who'd","whoever","whole","who'll","whom","whomever",
                                       "who's","whose","why","will","with","within","without","won't","would","wouldn't",
                                       "yes","yet","you","you'd","you'll","your","you're","yours","yourself","you've"};
              int i = 0;
              int j = stoplist.length;
              int mid = 0;
              boolean found = false;
              while (i < j && !found){
                   mid = (i + j)/2;
                   if (str.compareTo(stoplist[mid]) == 0)
                        found = true;
                   else
                        if (str.compareTo(stoplist[mid]) < 0)
                             j = mid;
                        else
                             i = mid + 1;
              return found;
         }

    please show us the full error message.
    it sounds like a classpath problem...

  • Error :Unable to retrieve data from iHTML servlet for Request2 request

    I open bqyfile to use HTML in workspace.
    When I export report to excel in IR report.
    Then I press "back" button I get error"Unable to retrieve data from iHTML servlet for Request2 request "
    And I can not open any bqyfiles in workspace.
    Anybody gat the same question? Thanks~

    Hi,
    This link will be helpful, the changes is made in the TCP/IP parameter in the registry editor of Windwos machine. I tried the 32 bit setting for my 64 bit machine (DWORD..) and it worked fine for me..
    http://timtows-hyperion-blog.blogspot.com/2007/12/essbase-api-error-fix-geeky.html
    Hope this helps..

  • Add non-servlet class to Tomcat

    Hi,
    does anyone know, what I have to do, to be able
    to use a simple non-servlet class file in my
    jsp-pages.
    e.g.
    MyClass.class
    In my jsp page:
    <%
    MyClass m = new MyClass( );
    %>
    I was told that I simply have to put it in the
    web-inf/classes directory, but that doesn't seem
    to work ...
    Any help would be appreciated! Thanx. chris

    You need to use the "import" statement or else use the full class name. Also, some servers don't handle the default package well so you may want to try placing the class in a package.
    e.g. if class is mypackage.MyClass, it is placed in web-inf/classes/mypackage/MyClass.class
    In the JSP, code:
    <%@ page import="mypackage.MyClass" %>
    <%
    MyClass m = new MyClass();
    %>or you could use "useBean" to avoid scriptlets.

  • Display from non-MIDlet class?

    Display from non-MIDlet class?
    I havel a method in my main MIDlet that flashes up a message as an Alert:
    public void doAlert(String sAlertText) {
           Alert alSending;
           alSending = new Alert(null, sAlertText, null, AlertType.INFO);
           alSending.setTimeout(3000);
            m_display.setCurrent(alSending);
        }m_display is declared and instantiated in the main MIDlet:
    public class Boss extends MIDlet implements CommandListener {
            public static Display m_display;
            public Boss() {       /** Constructor*/
                    m_display = Display.getDisplay( this );
    }Now when I try to call this from another class:
         new Boss().doAlert("Eat lead, Bambi!");I get: "SecurityException: Application not authorized to access the restricted API". The same happens if I try to use a reference to a MIDlet, rather than to a Display. Apparently, you can't instantiate a MIDlet from with another MIDlet / class.
    So, how do you obtain a reference to the currently-running MIDlet or its Display from a different class?

    Thanks for your reply, but i finally solved it. I found a way of getting a reference to my MIDlet, so i had the control of its display.
    Maybe it could be a good idea having some classes to write to the cellular's screen without being a MIDlet, like System.out.* classes in traditional Java.
    See you.
    David.

  • Get real path in non servlet class

    Hi,
    I've created a ServletContextListener class that loads a thread at application startup and kills it and application shutdown.
    The thread periodically monitors a specific file. I need to pass a real file path to the thread, but because the thread class is not a servlet, I cannot use the getServletContext().getRealPath("").
    What are my options?

    The ServletContextListener has access to both the ServletContext as well as the Thread.
    So the solution can be to get the path in the listener and pass it as a parameter to the constructor or a setter method of the thread.

  • Retrieving contacts from non working c1-02 mobile

    my mobile is switching on but stops working aafter the welcomee and time screen...... i want to restore the contacts i saved in my mobile........ is there any possibility of doing so? if so, how? my mobile model is nokia c1-02

    What you have discovered is the reason to *not* use LDAP URLs for CDP and AIA extensions in your PKI. To access those URLs, the account must access to the URLs. In your output, it is quite clear that the local account does not have necessary permissions
    (you also use FILE URLs for publication, which again is not recommended).
    The best practice is to use a single URL for the CDP extension. It should be an HTTP URL that is hosted on a highly available (internally and externally accessible) Web cluster.
    For the AIA extension, it should contain two URLs: one for the CA certificate - again to an internally and externally accessible, highly available Web cluster and one for the OCSP service - also
    an internally and externally accessible, highly available Web cluster.
    the other issue is that the root CA is *not* trusted when run by a non-domain account. How are you adding the trusted root CA. It is recommended to do this by running
    certutil -dspublish -f RootCA.crt.
    This will ensure that the computer account trusts the root CA. In your output, the root CA certificate is not trusted.
    Brian

  • NON-SERVLET, NON-EJB DYNAMIC CLASS RELOAD

    hi,
              In weblogic 5.1, is there a way to reload a class from the clientclasses directory without restarting the server? it's just a class in the clientclasses used by the JSPs. a kind of hotdeploy for NON-EJB, NON-SERVLET CLASS. SPECIFIC guidance will be immensely appreciated..
              Thanks in advance
              Vijay
              

    please show us the full error message.
    it sounds like a classpath problem...

  • Non servlet to use resource

    Hi all,
    is it possible for non-servlet classes (located in WEB-INF/classes) to load/use resource of web application just as Servlet doing with getServletContext().getResource() ?
    I am using Tomcat 6.
    Any hought would be really appreciated.
    thanks

    It is better to use the Class.getResourceAsStream method or the ResourceBundle.getBundle methods to locate resources in the classpath. You could pass the servletContext object to the other classes but this violates the separation between presentation and business logic and should be avoided.

  • Accessing the ServletContext from a class that is not a Servlet?

    Is there any way of accessing the ServletContext from a class that is not a
              Servlet? The class is being used as part of a Web Application.
              Thanks.
              

    http://www.mozilla.org/mirrors.html
    Mozilla has download mirrors around the globe. If it is on the list, it is trustworthy.

  • How to retrieve information from XML using servlets

    Hi
    I have a scenario like this
    File-->XI-->J2ee application(HTTP Receiver adapter)
    I want to know how XI sends xml file as a query string file name?
    What ever may be the case i just need to retrieve the information from Request object and display the same in browser(JSP).How to do that, I am totally confused, please anyone help me!
    Code help is highly rewarded.
    Thanx

    Hi Rajesh!
    I have tried your code. But some where i went wrong. Please correct me: I am using NWDS2.0.9
    my web.xml:
    <?xml version="1.0" encoding="UTF-8"?>
    <!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>
        <display-name>WEB APP</display-name>
        <description>WEB APP description</description>
        <servlet>
            <servlet-name>DisplayRes</servlet-name>
            <servlet-class>com.quinnox.DisplayRes</servlet-class>
        </servlet>
        <servlet-mapping>
              <servlet-name>DisplayRes</servlet-name>
              <url-pattern>/DisplayRes/*</url-pattern>
         </servlet-mapping>
    </web-app>
    my application.xml:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE application PUBLIC "-//Sun Microsystems, Inc.//DTD J2EE Application 1.3//EN"
                                 "http://java.sun.com/dtd/application_1_3.dtd">
    <application>
        <display-name>ReceiverEntpr</display-name>
        <description>EAR description</description>
        <module>
            <web>
                <web-uri>HttpReceiver.war</web-uri>
                <context-root>/HttpReceiver</context-root>
            </web>
        </module>
    </application>
    and my servlet code:
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.PrintWriter;
    import java.io.Writer;
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Result;
    import javax.xml.transform.Source;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.xml.sax.EntityResolver;
    import org.xml.sax.SAXException;
    import com.sun.java_cup.internal.parser;
    import com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl;
    public class DisplayRes extends HttpServlet {
         public void doGet(HttpServletRequest requset, HttpServletResponse response) throws ServletException, IOException
              doWork(requset, response);
         public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
              doWork(req, resp);
         private void doWork(HttpServletRequest req, HttpServletResponse resp) throws IOException
              String path = null;
              PrintWriter out = null;
              PrintWriter p2=resp.getWriter();     
              try
                   resp.setContentType("text/xml");
                   out = resp.getWriter();
                   out.println("hi");
                   path = req.getPathInfo();
                   if(req.getContentLength() != -1){
                   outputURI(req.getInputStream(), out);
              } catch (IOException ioe) {     return;     
         //private void outputURI(InputStream resultStream, Writer out) {
              private void outputURI(InputStream resultStream, PrintWriter out) {
              if (resultStream == null) {
    //             no default file
    //            logger.error("No File to return");
              return;
              try {
              DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    //            Class clazz = loader.loadClass("org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
    //            DocumentBuilderFactoryImpl factory = (DocumentBuilderFactoryImpl) clazz.newInstance();
    //            DocumentBuilder parser = factory.newDocumentBuilder();
              parser.setEntityResolver(new ClassPathEntityResolver());
              printXML(parser.parse(resultStream), out);
              resultStream.close();
              } catch (Exception e) {
    //            logger.error("Trying to parse the output " , e);
         //private void printXML(Document document, Writer writer) throws Exception {
              private void printXML(Document document, PrintWriter writer) throws Exception {
              Transformer transformer = TransformerFactory.newInstance().newTransformer();
              Source source = new DOMSource(document);
              Result output = new StreamResult(System.out);
              transformer.transform(source, output);
    //             Write as XML so that entity references can be resolved.
              if (writer != null) {
              transformer.transform(source, new StreamResult(writer));
    Please tell me how to display in servlet.
    If it is better to display in a browser. Please send me the code.
    Thanks

  • Retrieve data from a bean into a Servlet

    Hi,
    I created a simple JSP file called index.jsp situated in application root, then I associated this JSP with a java bean in order to collect data after the form submission, the attribute Action inside the Form tag points on a Servlet called Login situated in the application com.myapp.servlets package.
    the problem is that, using the scope="session" in the JSP page, I'm able to get catch the bean generated after the submission of the form, even the action is the Servlet called Login neither a back to the currest JSP or a redirection to another JSP, but in the same time, when I try to use bean methods to read the data (username, password) it gives null as result, I'm not able to understand the behavior of the bean which is created via Form submission but unreachable via the Servlet.
    herese the code
    the JSP (index.jsp)
    <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
    <jsp:useBean id="MyBean" scope="session" class="com.datalog.beans.LoginBean"/>
    <jsp:setProperty name="MyBean" property="*"/>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <title>Document sans nom</title>
    </head>
    <body>
    <table width="100%" border="1">
      <tr>
        <td> </td>
      </tr>
      <tr>
        <td><form name="form1" method="post" action="doLogin">
          <table width="100%"  border="0" cellspacing="0">
            <tr>
              <td width="30%">username : </td>
              <td><input name="username" type="text" id="username"></td>
            </tr>
            <tr>
              <td>password : </td>
              <td><input name="password" type="password" id="password"></td>
            </tr>
            <tr>
              <td> </td>
              <td><input type="submit" name="Submit" value="Envoyer"></td>
            </tr>
          </table>
        </form></td>
      </tr>
      <tr><!-- in case when try to use without a servlet call-->
        <td>username after submission <jsp:getProperty name="MyBean" property="username" /><br>
         password after submission <jsp:getProperty name="MyBean" property="password" /></td>
      </tr>
    </table>
    </body>
    </html>The bean (LoginBean.java)
    package com.datalog.beans;
    import java.io.Serializable;
    public class LoginBean implements Serializable {
        private String username;
        private String password;
        public LoginBean(){
            System.out.println("i'm the bean ... "+this);
        public String getPassword() {
            return password;
        public void setPassword(String password) {
            this.password = password;
            System.out.println(this.password);
        public String getUsername() {
            return username;
        public void setUsername(String username) {
            this.username = username;
            System.out.println(this.username);
    }Servlet (Login.java)
    * Created on 14 d�c. 2004
    * TODO To change the template for this generated file go to
    * Window - Preferences - Java - Code Style - Code Templates
    package com.datalog.cpservlets;
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import com.datalog.beans.LoginBean;
    * Servlet Class
    * @web.servlet              name="Login"
    *                           display-name="Name for Login"
    *                           description="Description for Login"
    * @web.servlet-mapping      url-pattern="/Login"
    * @web.servlet-init-param   name="A parameter"
    *                           value="A value"
    public class Login extends HttpServlet {
        public Login() {
            super();
            // TODO Auto-generated constructor stub
        public void init(ServletConfig config) throws ServletException {
            super.init(config);
            // TODO Auto-generated method stub
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException,
            IOException {
            // TODO Auto-generated method stub
            super.doGet(req, resp);
        protected void doPost(
            HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            PrintWriter out = response.getWriter();
            out.println("<br><br>Servlet (Login) in use.<br>");
            out.println("username from request.getParameter : "+request.getParameter("username")+"<br>");
            out.println("password from request.getParameter : "+request.getParameter("password")+"<br>");
            out.println("<br><br>Trying to use the bean...<br>");
            HttpSession session = request.getSession();
            LoginBean myBean = (LoginBean)session.getAttribute("MyBean");
            out.println("supposed bean adr : "+myBean);
            out.println("<br>username from myBean.getUsername : <b>"+myBean.getUsername()+"</b><br>");
            out.println("<br>password from myBean.getPassword : <b>"+myBean.getPassword()+"</b><br>");
    }thank's.

    The code that would populate the bean is here:
    <jsp:useBean id="MyBean" scope="session" class="com.datalog.beans.LoginBean"/>
    <jsp:setProperty name="MyBean" property="*"/>
    When this code runs, it
    1 - creates a LoginBean (if one is not already present)
    2 - Populates the loginBean from the request parameters.
    But this code is currently running when you generate the login page - not when you push the submit button.
    Solutions
    1 - Submit the form to a JSP page which runs the jsp:setProperty tag and then forwards to your Login servlet
    2 - Retrieve the request parameters in your servlet and populate the bean. The jakarta commons BeanUtils are the standard way to go here. They are actually preferable to the jsp:setProperty tag which has some "features" in its use.
    Cheers,
    evnafets

  • Retrieving data from oracle database and displaying using servlets

    //DataRetrieving.class file
    import java.io.*;
    import java.sql.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class DataRetrieving extends HttpServlet{
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws
    ServletException, IOException{ 
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("A program for connecting oracle database");
    try
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL", "scott","tiger");
    Statement stmt = con.createStatement();
    ResultSet r = stmt.executeQuery ("SELECT ename,job,sal,comm,deptno FROM emp");
    while ( r.next() )
         String bar = r.getString("ename");
         String bar1 = r.getString("job");
         float bar2 = r.getInt("sal");
         float bar3 = r.getInt("comm");
         int bar4 = r.getInt("deptno");
         //out.println(r.getString(0)+" "+r.getString("ename"));
         out.println("hi");
         out.println(bar1);
    r.close();
    stmt.close();
    con.close();
    catch (Exception e)
    out.println("ERROR : " + e);
    //web.xml file
    <?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>Hello</servlet-name>
    <servlet-class>DataRetrieving</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>Hello</servlet-name>
    <url-pattern>/DataRetrieval</url-pattern>
    </servlet-mapping>
    </web-app>
    while running the servlet , i am unable to retrieve the data
    The error message i am getting is
    A program for connecting oracle database
    ERROR : java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
    after running the servlet.
    what could be the problem?

    import java.io.*;
    import java.sql.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class myserv extends HttpServlet
    public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
    res.setContentType("text/html");
    PrintWriter pw=res.getwriter();
    pw.println("Connecting data base");
         try
         Class.forName("oracle.jdbc.driver.OracleDriver");
         Connection con=Drivermanager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");
         Stamtenet st=con.createStament();
         Resultset rs=con.executeQurey("select * from emp");
         while(rs.next())
         rs.getInt("empno")+" "+rs.getDouble("sal"));
         }catch(Exception e)
    }

Maybe you are looking for

  • Session variable

    I created a period status session variable which i want to use as a filter in answers. This variable takes note of the last closed period (month - YYYYMDD) when the accounting team closes it in their books. I currently have open periods taking the va

  • IMac Safari jumps once and stops...

    I am using iMac OS X version 10.9.4 and it runs (not any more) Safari 7.0.5 I was working on online photobook and once closed it didn't wont to open again. I need to finish the book but unable toopen Safari. As the only browser on Mac can't get any i

  • UAG External Load Balancing and ISATAP

    Hi Experts, I am deploying a UAG Array to be used for Direct Access. The Array will consist of two servers and use an F5 External Load Balancer. In addition and in similarity to 90% of the other corporate intranets out there, the internal network is

  • Strange Style Issue

    For some reason all of the forms created by ADDT in my app seem to have tables that collapse in on themselves. They display all the fields and labels, but the total width of the box containing them wants to squish in and enclose only about half of th

  • PGP Whole disk Encryption but for Windows Partition only ?

    Hi, Slightly unusual situation here. I want to use my MacBook Pro at work and home. OSX at home and XP at work. Now at work they have a strict policy of only allowing computers on the network with PGP Whole disk Encryption. I've looked into this and