User a commonj WorkManager on a servlet

Hi,
I'm developing a servlet in weblogic 9 and want to assing a commonj WorkManager to it for work handling. For that purpose I have defined the following resource-ref on web.xml file
<resource-ref>
<res-ref-name>wm/MyWorkManager</res-ref-name>
<res-type>commonj.work.WorkManager</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
On the code I obtain successfully the reference of that WorkManager through JNDI. The problem is that when I try to schedule the first work on that work manager i get and exception saying the work manager is shutdown.
commonj.work.WorkException: commonj.work.WorkRejectedException: [WorkManager:002916]Request belonging to WorkManager wm/MyWorkManager, application nsu-ws-connector is rejected as the WorkManager is shutdown
     at weblogic.work.j2ee.J2EEWorkManager$WorkStatus.setThrowable(J2EEWorkManager.java:326) [weblogic.jar:9.2.3.0]
     at weblogic.work.j2ee.J2EEWorkManager$WorkWithListener$1.run(J2EEWorkManager.java:229) [weblogic.jar:9.2.3.0]
     at weblogic.work.ServerWorkManagerImpl$WorkAdapterImpl.run(ServerWorkManagerImpl.java:518) [weblogic.jar:9.2.3.0]
     at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209) [weblogic.jar:9.2.3.0]
     at weblogic.work.ExecuteThread.run(ExecuteThread.java:181) [weblogic.jar:9.2.3.0]
Caused by: commonj.work.WorkRejectedException: [WorkManager:002916]Request belonging to WorkManager wm/MyWorkManager, application nsu-ws-connector is rejected as the WorkManager is shutdown
     ... 4 common frames omitted
Do I have to startup this work manager or something? Thanks a lot

Hi,
Which kind of workmanager is it..."*Application Level WorkManagers*" or "*Global WorkManagers*". Have u provided any <work-manager> tag in "weblogic.xml" as well?
Please refer to the following link...and let us know if you are doing anything special... After the Lookup to the WorkManager is Successful... How r u calling the .schedue()? or what exactly r u doing after that?
http://jaysensharma.wordpress.com/workmanagers/
And
http://jaysensharma.wordpress.com/2009/12/20/application-level-workmanager-timermanager-lookup/
Thanks
Jay SenSharma

Similar Messages

  • [WebLogic Server 11g 10.3.3] Cannot Lookup CommonJ WorkManager ?

    Hi,
    I am currently working on an application and going to use the Weblogic's CommonJ WorkManager; I tried the example in http://download.oracle.com/docs/cd/E14571_01/web.1111/e13733/toc.htm ; however I got an error
    javax.naming.ServiceUnavailableException [Root exception is java.net.UnknownHostException: Unknown protocol: 'RMI']
    Have anyone experienced this? I searched the web for answers but it seems I'm the only one getting this exception.
    The declaration of the work manager is in web.xml as follows:
         <resource-ref>
              <res-ref-name>default</res-ref-name>
              <res-type>commonj.work.WorkManager</res-type>
              <res-auth>Container</res-auth>
              <res-sharing-scope>Shareable</res-sharing-scope>
         </resource-ref>
    and I tried to lookup using the following code (basically just copy-paste from the example with some modification):
         void init() {
              try {
                   System.out.println("## executing in: " +
                             ((ExecuteThread)Thread.currentThread()).getWorkManager()
                             .getName());
                   String lookupstr = "java:comp/env/default";
                   System.out.println("## lookup >>> " + lookupstr);
                   InitialContext ic = new InitialContext();
                   WorkManager wm = (WorkManager)ic.lookup(lookupstr);
                   System.out.println("## got Java EE work manager !!!!");
                   wm.schedule(new Work(){
                        public void run() {
                             ExecuteThread th = (ExecuteThread) Thread.currentThread();
                             System.out.println("## [servlet] self-tuning workmanager: " +
                                       th.getWorkManager().getName());
                        public void release() {}
                        public boolean isDaemon() {return false;}
              catch (NamingException ne) {
                   ne.printStackTrace();}
              catch (WorkException e) {
                   e.printStackTrace();
    and the error is:
    ## executing in: default
    ## lookup >>> java:comp/env/default
    javax.naming.ServiceUnavailableException [Root exception is java.net.UnknownHostException: Unknown protocol: 'RMI']
         at weblogic.jndi.internal.ExceptionTranslator.toNamingException(ExceptionTranslator.java:34)
         at weblogic.jndi.WLInitialContextFactoryDelegate.toNamingException(WLInitialContextFactoryDelegate.java:787)
         at weblogic.jndi.WLInitialContextFactoryDelegate.getInitialContext(WLInitialContextFactoryDelegate.java:368)
         at weblogic.jndi.Environment.getContext(Environment.java:315)
         at weblogic.jndi.Environment.getContext(Environment.java:285)
         at weblogic.jndi.WLInitialContextFactory.getInitialContext(WLInitialContextFactory.java:117)
         at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:667)
         at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
         at javax.naming.InitialContext.init(InitialContext.java:223)
         at javax.naming.InitialContext.<init>(InitialContext.java:175)
         at com.example.cms.engine.ui.t5.pages.Welcome.init(Welcome.java:26)
    thanks in advance for any help,
    Harry

    How are you trying to connect to the server?
    An example:
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import java.util.Hashtable;
    public class LookUP {
        private static Context context;
        private LookUP() {
        static {
            Hashtable hashtable = new Hashtable();
            hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
            hashtable.put(Context.PROVIDER_URL, "t3://172.31.0.107:7002,172.31.0.107:7003");
            //hashtable.put(Context.SECURITY_PRINCIPAL, "username");
            //hashtable.put(Context.SECURITY_CREDENTIALS, "password");
            long begin = System.currentTimeMillis();
            try {
                context = new InitialContext(hashtable);
            } catch (NamingException e) {
                e.printStackTrace();
            long end = System.currentTimeMillis();
            long timeseconds = (end - begin) / 1000;
            System.out.println("initialcontext creation time " + timeseconds);
        public static Context getContext() {
            return context;
    }Note that in order to use this you need a certain type of wls-client in the classpath.
    When the wlclien.jart is used than t3 is automatically replaced by iiop.
    When the wlfullclient.jar is used than the t3 protocol is used (newer version of weblogic also ship a wlthint3client.jar)

  • Typecast error while lookup (J2EEworkmanager to commonJ workmanager)

    Hi,
    I am using plain web application where i want to use commonJ workmanager to do same i have done following steps
    1. Define work manager in weblogic.xml
    <work-manager>
    <name>LogWorkmanager</name>
    <min-threads-constraint>
    <count>5</count>
    </min-threads-constraint>
    </work-manager>
    2. Define resource in web.xml file
    <resource-ref>
    <res-ref-name>LogWorkmanager</res-ref-name>
    <res-type>commonj.work.WorkManager</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
    </resource-ref>
    3. Use JNDI mapping to get workmanager as:
    InitialContext ic = new InitialContext();
    commonj.work.WorkManager wm = (commonj.work.WorkManager)ic.lookup("java:comp/env/LogWorkmanager");
    Here at step 3 I am getting classcast exception as java.lang.ClassCastException: weblogic.work.j2ee.J2EEWorkManager.
    Could you please guide me where I am making mistake as I have defined resource ref point to commonj.workmanager and used same name in lookup method still why i am getting J2EEWorkManager instead of commonJ workmanager.
    Thanks,
    Yuvraj

    Can you run a little test. See if the following works:
    In your web.xml
        <!-- default weblogic work manager -->
        <resource-ref>
            <res-ref-name>default</res-ref-name>
            <res-type>commonj.work.WorkManager</res-type>
            <res-auth>Container</res-auth>
            <res-sharing-scope>Shareable</res-sharing-scope>
        </resource-ref>In your code you can use something like:
    import commonj.work.WorkManager;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    public class TestServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            getDefaultWorkManager();
        private WorkManager getDefaultWorkManager() {
            WorkManager defaultWorkManager = null;
            try {
                Context context = new InitialContext();
                defaultWorkManager = (WorkManager) context.lookup("java:comp/env/default");
                System.out.println("My default workmanager " + defaultWorkManager);
            } catch (NamingException e) {
                e.printStackTrace();
            return defaultWorkManager;
    }

  • Commonj WorkManager & TimerManager

    Has anybody had any success implementing either a commonj WorkManager or TimerManager in Weblogic 9.0? I've sifted through the specification documents and several articles that describe how to implement these, but there seems to be a missing link.
    I can't seem to get the right combination of deployment descriptors to get a TimerManager or WorkManager instance to show up in the JNDI tree. What's the secret? Is this even implemented in Weblogic 9.0?

    Hi,
    To be do not think that there would be any problem in that as in WLS 9.2 MP3 only the bugs which were found in WLS 9.2 MP2 might have been fixed and not major changes have been made in the new MP, also the JDK and other components would remain the same. Hence moving from to news MP version would not have any problem and its always recommended to use the latest versions.
    To be in a safe positon position you can upgrade your test environment and check your same production application in it and then do the same thing for production.
    You can get all the lists of fixes been made in WLS 9.2 MP3 in the below link.
    http://download.oracle.com/docs/cd/E13222_01/wls/docs92/issues/known_resolved.html
    Ravish Mody
    http://middlewaremagic.com/weblogic
    Come, Join Us and Experience The Magic…

  • How to restrice ananymous user access to portal link /irj/servlet/prt/portal/prtroot/com.sap.portal.navigation.portallauncher.default?

    Hi experts,
    We had an issue with portal access. I wonder if portal is venerable for security threats?
    Could you please let me how to restrict the unauthorized users (anonymous user) to the portal URL.
    https://HOST:50001//irj/servlet/prt/portal/prtroot/com.sap.portal.navigation.portallauncher.default .
    Appreciate your help.
    Regards
    Maruti

    Hi Maruti,
    Hope you are doing good.
    Can't you just amend the portal permissions so that this access is not possible.
    The PCD location should be:
    com.sap.portal.system/security/sap.com/NetWeaver.Portal/no_safety/com.sap.portal.navigation.portallauncher....
    Hope this helps.
    Thank you and have a nice day!
    Kind Regards,
    Hemanth

  • How to propagate User Role/Identity between containers? Servlet --- WS

    Hello!
    After a few days of code writing and extensive research on the web I am completely stopped and do not know where to move further...
    I have two containers: web and EJB. Thne I created two users at GlassFish AS (SUN Application Server) in file realm: admin and user.
    URL request to servlet asks for name and password. In the web container I get proper roles (matched to login name) when I ask:
    SessionContext ctx.getCallerPrincipal().getName
    admin or user, depending on what I used for logging in.
    From that servlet I call webservice which is resided in an EJB container...
    When I check the principal there it is always ANONYMOUS.
    The web service is called over plain http, not secured.
    If I use similar construction but with only stateless bean (not web service) I get Caller id propagation and I can see in the EJB container that admin or user logged in.
    My question is: How can I propagate Caller id with web services from web container to EJB one? I need to use roles that are defined in AS,
    I am going to use security annotations at web service side and further. But it does not work, because I all the time get only ANONYMOUS...
    I can not switch to EJB bean instead of web service due to requirement to use only http, not RMI.
    Please help me advice?
    / Sasha

    Hello!
    After a few days of code writing and extensive research on the web I am completely stopped and do not know where to move further...
    I have two containers: web and EJB. Thne I created two users at GlassFish AS (SUN Application Server) in file realm: admin and user.
    URL request to servlet asks for name and password. In the web container I get proper roles (matched to login name) when I ask:
    SessionContext ctx.getCallerPrincipal().getName
    admin or user, depending on what I used for logging in.
    From that servlet I call webservice which is resided in an EJB container...
    When I check the principal there it is always ANONYMOUS.
    The web service is called over plain http, not secured.
    If I use similar construction but with only stateless bean (not web service) I get Caller id propagation and I can see in the EJB container that admin or user logged in.
    My question is: How can I propagate Caller id with web services from web container to EJB one? I need to use roles that are defined in AS,
    I am going to use security annotations at web service side and further. But it does not work, because I all the time get only ANONYMOUS...
    I can not switch to EJB bean instead of web service due to requirement to use only http, not RMI.
    Please help me advice?
    / Sasha

  • Inserting user variables into MYSQL database using servlet

    I have a servlet that recieves user entered parameters from an html form and inserts them into a user table in MYSQL, or at least is supposed to. I can get it to update the table with specific values but not with the user variables. I know the single quote marks are for inserting specific values but without them it doesn't properly work.
    The parameters are parsed correctly into the variables, so I just can't figure out how to ge tthe variables into the database. Any help would be wonderful
    register.html:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML>
    <HEAD>
      <TITLE>Register</TITLE>
    </HEAD>
    <BODY BGCOLOR="#FDF5E6">
    <CENTER><IMG SRC="dvdti.jpg" ALIGN=middle >   </CENTER>
    <HR>
    <H1 ALIGN="CENTER">Please enter your registration details:</H1>
    <FORM ACTION="http://localhost:8080/examples/servlet/Assignment1.register">
      <BR>First Name: <input type="text" NAME="Ufirst_name"><BR>
      <BR>Last Name: <input TYPE="TEXT" NAME="Ulast_name"><BR>
      <BR>Address: <INPUT TYPE="text"  name="Uaddress"><BR>
      <BR>E-mail:     <INPUT TYPE="TEXT" NAME="Uemail"><BR
      <BR>Password: <INPUT TYPE="password" NAME="Upassword"><BR>
      <CENTER>
        <INPUT TYPE="SUBMIT" VALUE="Register">
      </CENTER>
    </FORM>
    </BODY>
    </HTML>
    register.java:
    package Assignment1;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    // Connects to a database to retrieve music data
    public class register extends HttpServlet {
      public void doGet(HttpServletRequest request,
                        HttpServletResponse response)
          throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
    // Database connection code starts here
         Connection conn = null;
         // loading jdbc driver for mysql (help in mysql.jar file in classpath)
         try{
             Class.forName("com.mysql.jdbc.Driver").newInstance();
         } catch(Exception e) {
             System.out.println(e);
         // connecting to database
         try{
              // connection string for demos database, username demos, password demo-pass
             conn = DriverManager.getConnection
            ("jdbc:mysql://mudfoot.doc.stu.mmu.ac.uk:3306/roddiea?user=roddiea&password=");
              System.out.println("Connection to database successful.");
           catch(SQLException se) {
             System.out.println(se);
    // Create select statement and execute it
      try        { Statement stmt2 = conn.createStatement();
              // Get the regdetails from the reg form
               String Ufirst_name = request.getParameter("Ufirst_name");
               String Ulast_name = request.getParameter("Ulast_name");
               String Uaddress = request.getParameter("Uaddress");
               String Uemail = request.getParameter("Uemail");
                  String Upassword = request.getParameter("Upassword");
              stmt2.executeUpdate("INSERT INTO customer(first_name, last_name, address, email, password)" + "VALUES('Ufirst_name', 'Ulast_name', 'Uaddress', 'Uemail', 'Upassword')");
              System.out.println (stmt2);
              out.println(stmt2);
              out.println(Ufirst_name + Ulast_name + Uaddress + Uemail + Upassword);
        // close the html
        out.println("</BODY></HTML>");
              stmt2.close();
             conn.close();
         }catch(SQLException se) {
             System.out.println(se);
    }Message was edited by:
    Altered_Carbon
    Message was edited by:
    Altered_Carbon
    I also realise that this is a more MYSQL titled problem, but those forums look rubbish <_<

    Investigate PreparedStatement.
    Currently you're trying to insert a value "Ufirst_name" instead of the value of the variable called Ufirst_name.
    It's possible to do this (you could do something like this: "... '" + UfirstName + "' ...") but DEFINITELLY NOT RECOMMENDED. Instead use a prepared statement.
    D.

  • User authentication on LDAP with JSP/Servlet

    Please help! What I need is a small Java Servlet or JSP that I can run from a web server that will allow users type in their username and password. The JSP will then authenticate the user (by trying to log onto the LDAP server as that user) and if successful will offer them the chance to change their password. If they do it will then communicate with the LDAP server as that user and change their password.
    The LDAP server I am using is the Sun(TM) ONE 5.1 directory server.

    You can use jsp's and servlets.
    Have a .jsp (i.e. login.jsp) that has 2 fields username / password and a submit button i.e.
    <form method="post" action="/servlet/LoginServlet">
    <input type="text" size="15" name="username" value="">
    <input type="password" size="15" name="password" value="">
    <input type="submit" name="Submit" value="Authenticate">
    </form>In your servlet (i.e. LoginServlet) is where you retrieve the username / password by doing something like:
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      String username = request.getParameter("username");
      String password = request.getParameter("password"); 
    }You would now do your LDAP authentication. see http://java.sun.com/products/jndi/tutorial/ldap/security/ldap.html
    Depending on whether the authentication was successful or not you would redirect the user to an error page or to the next .jsp (i.e changePassword.jsp) where they can change their password.

  • Execute commonj.WorkManager work on remote member of application cluster

    Hi,
    We have configured a WorkManager for our web application which works with Spring & Quartz to execute jobs asynchronously. However, all jobs get picked up by the same machine and the other members of the cluster are not given any tasks to execute.
    The commonj documentation says that a Serializable Work returns a RemoteWorkItem which can execute jobs on a remote jvm. Weblogic docs, however, say that it doesn't support this interface and implements its own cluster load balancing.
    How do we configure the Workmanager such that work is distributed across remote jvms in a cluster.
    Thanks.
    Regards
    Kaizer

    Hi,
    Do you have TestStand 2.x or are you using a later version TS 3.5.
    TestStand 2.0 didn't handle remote execution, that wasn't available until TS3.0 or TS3.1.
    This example, shows how an executable can access the same execution of a TestStand sequencefile not a remote execution.
    If you have TestStand 3.x, then there should be some examples employing remote execution within theTestStand examples folders. or try this link http://zone.ni.com/devzone/conceptd.nsf/webmain/955A560B0B0052B88625698500563621
    Regards
    Ray Farmer
    Regards
    Ray Farmer

  • How do I get the session Id associated with a user id rather than using the Servlet request on the iplanet portal server

     

    In com.iplanet.portalserver.session.Session class use the method given below,
    public SessionID getID()--->Returns the session ID
    If u need to get clientID then use the method given below,
    public java.lang.String getClientID()- Returns the client ID in this session

  • WLS 9.2 - How to create and use a WorkManager through commonj?

    My goal is simple. I want to define a custom Work Manager at the application level which an MDB uses as it's dispatch policy and I can directly access with a commonj WorkManager. I have been reading through the WLS 9.2 PDFs but so far I have not been able to get this to work. Any help would be appreciated. Thanks.
    weblogic-application.xml
    This appears to work. I can see the work manager via the weblogic console.
    <work-manager>
        <name>MyWorkManager</name>
        <response-time-request-class>
            <name>MyResponseTimeGoal</name>
            <goal-ms>1000</goal-ms>
        </response-time-request-class>
        <min-threads-constraint>
            <name>MyMinThreads</name>
            <count>20</count>
        </min-threads-constraint>
        <ignore-stuck-threads>false</ignore-stuck-threads>
    </work-manager>
    MDB Annotations
    The idea here is to have the MDB using the MyWorkManager work manager and have a commonj WorkManager available via JNDI which maps to MyWorkManager. I can tell that the MDB is using the custom work manager by looking at the request count of the work manager in the weblogic console after running some tests.
    It doesn't seem that the resource reference is working at all through. The JNDI lookup of MyWorkManager always fails.
    @MessageDriven(
            maxBeansInFreePool = "20",
            destinationType = "javax.jms.Queue",
            initialBeansInFreePool = "20",
            defaultTransaction = MessageDriven.DefaultTransaction.NOT_SUPPORTED,
            ejbName = "MyMessageBean",
            destinationJndiName = "jms/MyQueue",
            acknowledgeMode = MessageDriven.AcknowledgeMode.AUTO_ACKNOWLEDGE,
            transactionType = MessageDriven.MessageDrivenTransactionType.CONTAINER,
            dispatchPolicy = "MyWorkManager")
    @ResourceRefs ({
        @ResourceRef(
                name = "MyWorkManager",
                type = "commonj.work.WorkManager",
                auth = ResourceRef.Auth.CONTAINER,
                sharingScope = ResourceRef.SharingScope.SHAREABLE,
                jndiName = "wm/MyWorkManager")
    })This is the generated XML from ejbgen:
    ejb-jar.xml
    <resource-ref>
         <res-ref-name>MyWorkManager</res-ref-name>
         <res-type>commonj.work.WorkManager</res-type>
         <res-auth>Container</res-auth>
         <res-sharing-scope>Shareable</res-sharing-scope>
    </resource-ref>
    weblogic-ejb-jar.xml
    <resource-description>
         <res-ref-name>MyWorkManager</res-ref-name>
         <jndi-name>wm/MyWorkManager</jndi-name>
    </resource-description>
    JNDI Lookup
    This fails (naming exception) and I cannot figure out why.
    InitialContext ic = new InitialContext();
    WorkManager wm = (WorkManager)ic.lookup("java:comp/env/wm/MyWorkManager");
    Spring Bean
    I have also tried to use Spring to get a commonj WorkManager which maps to MyWorkManager. This also throws a naming exception.
    <bean id="myWorkManager" class="org.springframework.scheduling.commonj.WorkManagerTaskExecutor">
        <property name="workManagerName" value="java:comp/env/wm/MyWorkManager"/>
    </bean>Edited by: user11950954 on Sep 28, 2009 12:43 PM

    So in this case I should be able to perform a JNDI lookup and get the commonj WorkManager which maps to the WLS Work Manager?Yes, for example:
    weblogic-application.xml :-
    <work-manager>
    *<name>MyWorkManager</name>*
    <response-time-request-class>
    <name>MyResponseTimeGoal</name>
    <goal-ms>1000</goal-ms>
    </response-time-request-class>
    </work-manager>
    MDB Annotations:-
    @ResourceRefs({
         @ResourceRef(
    name = *"MyWorkManager"*,
    type = "commonj.work.WorkManager",
    auth = ResourceRef.Auth.CONTAINER,
    sharingScope = ResourceRef.SharingScope.SHAREABLE,
    jndiName = *"MyWorkManager"* )
    ejb-jar.xml :-
    <resource-ref>
    *<res-ref-name>MyWorkManager</res-ref-name>*
    <res-type>commonj.work.WorkManager</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
    </resource-ref>
    weblogic-ejb-jar.xml should be look like this :-
    <resource-description>
    *<res-ref-name>MyWorkManager</res-ref-name>*
    *<jndi-name>MyWorkManager</jndi-name>*
    </resource-description>
    JNDI Lookup:-
    InitialContext ic= new InitialContext();
    WorkManager wm= (WorkManager) ic.lookup("*java:comp/env/MyWorkManager*");
    Edited by: Betino on 29/09/2009 12:45 PM

  • User Authentication using Servlet and JSp

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

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

  • Session Rules from Servlet to JSP

    I'm getting a null pointer exception from the else statement in the JSP below when I check to see if a user has been authenticated by a servlet.
    Are there any problems with the else statement to cause an exception?
    <% /**Verify Authenticationt*/
    HttpSession mysession = request.getSession();
    String loginUrl = "/hr/servlet/SessionLoginServlet";
    if (mysession==null)
    response.sendRedirect(loginUrl);
    else {  //below code causing null pointer exception
    String loggedIn = (String) mysession.getAttribute("loggedIn");
    if (!loggedIn.equals("true"))
    response.sendRedirect(loginUrl);
    %>
    The Servlet's doPost:
    public void doPost(HttpServletRequest request, HttpServletResponse
    response)throws ServletException, IOException {
    String userName = request.getParameter("userName");
    String password = request.getParameter("password");
    if (login(userName, password, response)) {
    //send cookie to the browser
    HttpSession session = request.getSession(true);
    session.setAttribute("loggedIn", new String("true"));
    response.sendRedirect("/hr/jsp/PAStart.jsp");
    else {
    sendLoginForm(response, true);
    }

    Unfortunately, no. You'll need to say:
    if (loggedIn != null || !loggedIn.equals("true"))
    It's how the equals() works for String objects. You need two objects to check equality.

  • How to get multiple selections from jsp page in my servlet

    Hello Everyone,
    I've a list that allows users to make multiple selections.
    <select name=location multiple="multiple">
        <option>
             All
        </option>
        <option>
             Hyd
        </option>
        <option>
             Dub
        </option>
        <option>
             Mtv
        </option>
      </select>I want to get the selections made by user in jsp page from my servlet, selections can be multiple too.
    ArrayList locList = new ArrayList();
    locList = request.getParameter("location");when I do so, I get compilation error as the request returns string type. How do I then get multiple selections made by the user.
    Please let me know.

    For those kind of basic questions it would help a lot if you just gently consult the javadocs and tutorials.
    HttpServletRequest API: [http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpServletRequest.html]
    Java EE tutorial part II: [http://java.sun.com/javaee/5/docs/tutorial/doc/]
    Coreservlet tutorials: [http://courses.coreservlets.com/Course-Materials/]

  • Mildet connect to oracle DB using servlet problem ,help please

    hi guys i have a problem am tring to connect my midlet to databse through midlet but i don`t know what is the problem so far the midlet already connect to my servlet url but the servlet cant read the parameters to open the connection for database
    my servlet code
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    import java.io.*;
    import java.net.*;
    import java.sql.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.text.*;
    * @author freddy
    public class getconnection extends HttpServlet {
        Statement statement;
    ResultSet rs=null;
    String bstr=null;
    String bstr1=null;
    String bstr2=null;
    public void init()
        * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
        * @param request servlet request
        * @param response servlet response
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            try {
                /* TODO output your page here
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Servlet getConnection</title>"); 
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>Servlet getConnection at " + request.getContextPath () + "</h1>");
                out.println("</body>");
                out.println("</html>");
            } finally {
                out.close();
        // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
        * Handles the HTTP <code>GET</code> method.
        * @param request servlet request
        * @param response servlet response
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            processRequest(request, response);
      doPost(request,response);
        * Handles the HTTP <code>POST</code> method.
        * @param request servlet request
        * @param response servlet response
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            processRequest(request, response);
            DataInputStream in = new DataInputStream(
                    (InputStream)request.getInputStream());
            String sid = in.readUTF();
            String user = in.readUTF();
            String pwd = in.readUTF();
          //  "jdbc:oracle:thin:@localhost:1521"+": "+sid
            String message = message = "Name:"+bstr+" telephone:"+bstr1+" burthday:"+bstr2;
             try {
                connect(sid,user, pwd);
                message += "100 ok connected";
            } catch (Throwable t) {
                message += "200 " + t.toString();
            response.setContentType("text/plain");
            response.setContentLength(message.length());
            PrintWriter out = response.getWriter();
            out.println(message);
            in.close();
            out.close();
            out.flush();
        private void connect(String sid, String user,String pwd)
        throws Exception {
            // Establish a JDBC connection to the MYSQL database server.
            //Class.forName("org.gjt.mm.mysql.Driver");
            Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
            Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:"+sid,user,pwd);
            System.out.print("connected");
            try{
               statement =conn.createStatement();
                rs=statement.executeQuery(" Select*from WOH.P_DEMGRAPHICS where P_ID='P1000 '");
            catch(SQLException e)
            System.err.print(e);
           try{
    while (rs.next()) {
    bstr=rs.getString(2);
    bstr1=rs.getString(3);
    bstr2=rs.getString(4);
    statement.close();
       catch (SQLException e) {
    //bstr += e.toString();
    System.err.println(e);
    System.exit(1);
            // Establish a JDBC connection to the Oracle database server.
            //DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
            //Connection conn = DriverManager.getConnection(
            //      "jdbc:oracle:thin:@localhost:1521:"+db,user,pwd);
            // Establish a JDBC connection to the SQL database server.
            //Class.forName("net.sourceforge.jtds.jdbc.Driver");
            //Connection conn = DriverManager.getConnection(
            //      "jdbc:jtds:sqlserver://localhost:1433/"+db,user,pwd);
        * Returns a short description of the servlet.
        public String getServletInfo() {
            return "Short description";
        // </editor-fold>
    }Midlet code
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    import java.io.*;
    import java.util.*;
    import javax.microedition.io.*;
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    * @author freddy
    public class testOrcl extends MIDlet  implements CommandListener {
       protected String url;
        private String username;
        private Display display;
        private Command exit = new Command("EXIT", Command.EXIT, 1);;
        private Command connect = new Command("Connect", Command.SCREEN, 1);
        private TextField tb;
        private Form menu;
        private TextField tb1;
        private TextField tb2;
        DB db;
        public testOrcl() throws Exception
            display=Display.getDisplay(this);
            url="http://localhost:8084/getConnection/getconnection";
        public void startApp() {
            displayMenu();
        public void displayMenu()
        menu= new Form("connect");
         tb = new TextField("Please input database: ","",30,
                    TextField.ANY );
            tb1 = new TextField("Please input username: ","",30,
                    TextField.ANY);
            tb2 = new TextField("Please input password: ","",30,
                    TextField.PASSWORD);
            menu.append(tb);
            menu.append(tb1);
            menu.append(tb2);
            menu.addCommand(exit);
            menu.addCommand(connect);
            menu.setCommandListener(this);
            display.setCurrent(menu);
        public void pauseApp() {
        public void destroyApp(boolean unconditional) { }
        public void commandAction(Command command, Displayable screen) {
            if (command == exit) {
                destroyApp(false);
                notifyDestroyed();
            } else if (command == connect) {
                db  = new DB(this);
                db.start();
                db.connectDb(tb.getString(),tb1.getString(),tb2.getString());
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    import java.io.*;
    import java.util.*;
    import javax.microedition.io.*;
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import java.lang.*;
    * @author freddy
    public class DB implements Runnable  {
        testOrcl midlet;
         private Display display;
            String sid;
            String user;
            String pwd;
            public DB( testOrcl midlet)
            this.midlet=midlet;
            display=Display.getDisplay(midlet);
        public void start()
        Thread t = new Thread(this);
                t.start();
        public void run()
         StringBuffer sb = new StringBuffer();
                try {
                    HttpConnection c = (HttpConnection) Connector.open(midlet.url);
                   c.setRequestProperty(
                       "User-Agent","Profile/MIDP-2.1, Configuration/CLDC-1.1");
                    c.setRequestProperty("Content-Language","en-US");
                    c.setRequestMethod(HttpConnection.POST);
                    DataOutputStream os =
                            (DataOutputStream)c.openDataOutputStream();
                    os.writeUTF(sid.trim());
                    os.writeUTF(user.trim());
                    os.writeUTF(pwd.trim());
                    os.flush();
                    os.close();
                    // Get the response from the servlet page.
                    DataInputStream is =(DataInputStream)c.openDataInputStream();
                    //is = c.openInputStream();
                    int ch;
                    sb = new StringBuffer();
                    while ((ch = is.read()) != -1) {
                        sb.append((char)ch);
               showAlert(sb.toString());
                    is.close();
                    c.close();
                } catch (Exception e) {
                    showAlert(e.getMessage());
         /* This method takes input from user like db,user and pwd and pass
                to servlet */
            public void connectDb(String sid,String user,String pwd) {
                this.sid = sid;
                this.user = user;
                this.pwd = pwd;
            /* Display Error On screen*/
            private void showAlert(String err) {
                Alert a = new Alert("");
                a.setString(err);
                a.setTimeout(Alert.FOREVER);
                display.setCurrent(a);
       

    Comment out process request or rewrite & move it to a position after you read the parameters and connect to the db. Decide where you want to write to the output stream. Also, you have some superfluous casting.
    I take it that you are using netbeans? If you debug and step through the code you will get an idea of the flow. The steps should be, midlet connects with POST, doPost is called, server reads parameters, server opens connection, executes query, releases/closes connection, and writes a response to the midlet.
    Some notes about the connect method; The scope of rs may cause problems. It is unlike you will have a valid result set if you have a problem with create statement or execute. Take a look at connection pooling and be mindful how the connections are opened, used, and closed; put all the important cleanup operations in a finally. Remove system.exit from your servlet. Actually I would suggest limiting the scope of all your vars;
    If you store the username, password, and sid on the midlet, you may have trouble updating the installation base if you need to change the values for any reason. Also, you have clients which contain your database u/p, susceptible to snooping and decompilation. Use the servlet to abstract the db from the client. And use a datasource (with connection pooling) for obtaining connections to db.

Maybe you are looking for

  • How do I combine Projects into one project?

    I like to make small projects while travelling and post on facebook. When home, I would like to combine them into one longer project for my Apple TV. Any suggestions would be greatly appreciated. Thanks, Skip

  • Hi Kernel Upgradation Error

    Dear Experts, We are having one unique problem , We having one BWP server CI install on AIX + Oracle 9i, and one application server on windows application server(the server resided on diffrnt windows domain) , But now since we have installed these sy

  • Regarding Address EndAddress in SAP Script

    <i>Hi Abapers, I am having a problem while displaying the address in SAP Script through Address EndAddress. Problem is it is displaying the data correctly but it display the Region Code. Now the requirement is to display the Region Description instea

  • Ports to Forward

    Hi just got the RV220W it will sit behind a ISP DSL router. What are all the ports I need to forward from the DSL router to the Cisco RV220W for all VPN access SSL,PPTP,IPsec Thanks In advance Keith

  • Forums linking to other forums

    When I am in the Photoshop Windows forum I notice there is a link (on the right side of the screen) to the Photoshop Windows FAQ forum. Great, but why is there not also a link to Bridge Windows and Adobe Camera Raw forums? These products are most cer