URGENT!! synchronization in servlets

Hello
I need to synchronize access to a connection in a servlet. If I make the connection static, and put the connection in a synchronized block, will that work? The servlet is not a SingleThread servlet, so more than one request could be coming through at once. Will synchronization work for this case?
Here is a simplified example of what I mean (this is not actual code, just an illustration)...
public class test extends HttpServlet {
private static Connection con;
public doGet(HttpServletRequest req, HttpServletResponse res)
synchronized(con)
//do stuff with connection here
//output stuff
Please help!

That will work.
But a better alternative, in terms of design would be to define synchronized methods on Connection.
e.g.
public class Connection
public synchronized doStuff () { ... }
That way you are localizing the thread safety issues within Connection, and not exposing those issues to the outside world.
In future, if the Connection can support multi-threaded access, you just have to change the Connection, and not all the calling code.
The way you have done it, the onus is on ALL the callers of Connection.

Similar Messages

  • Urgent-doubt in servlets

    hi to all,
    i am using tomcat server.i have a doubt in executing packaged servlet and it shows error 404 cannot resolve symbol when i tried to access thru browser
    i have attached below the mapping content of web.xml.Actually the servlet file got executed for packageless servlet and there is a
    problem in executing the packaged servlet.
    Any help would be highly appreciable because i have tried few methods
    and it didn't work out.help me
    <?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>
    <display-name>Welcome to Tomcat</display-name>
    <description>
    Welcome to Tomcat
    </description>
    <* mapping content for packageless servlet */
    <servlet>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/servlet/HelloServlet</url-pattern>
    </servlet-mapping>
    <* mapping content for packaged servlet */
    <servlet>
    <servlet-name>HelloServlet2</servlet-name>
    <servlet-class>moreservlets.HelloServlet2</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>HelloServlet2</servlet-name>
    <url-pattern>/HelloServlet2</url-pattern>
    </servlet-mapping>
    </web-app>
    reg,
    arv

    Hi aarvindk,
    I remember <servlet-mapping> tags must appear after any <servlet> tags in web-app document.

  • Need Urgent Help with Servlets!!!

    I was just assigned a java project few days back and the thing is that i noe nuts abt JAVA!!! My first time and i admit i'm a slow learner.
    I was tasked to develop a servlet for web based query of inventory status in FIFO storage from QIS database.
    Basically, i heard according to my supervisor that this is a very simple project that may be completed in just days..but as i said this is my first Java program and i really need u guys to help me!!!! I have no idea how to start the entire coding process.
    The main page where the option buttons are is actually a form. This program have a HTTP extension i think. Below i have indicate the System and User Requirements.
    System Requirements
    * A Servlet
    * 2 option buttons
    * 1 for retrieving a Summarised Report
    * 1 for retriveving an Detailed Report
    * 1 command button for retrieval of data
    * Retrieved data will be displayed on another frame
    User Requirements
    * Be able to view Summarised Report at a click of a mouse
    * Be able to view Detailed Report also at a click of a mouse
    PLS HELP!!!!!!!!

    Justa comment...
    << according to my supervisor that this is a very simple project that may be completed in just days
    If your supervisor is so confident, then, maybe he/she should just get it done himself/herself. I really mean it. However, if that does happen, he/she should provide post-implementation support himslef/herself.
    In the meanwhile you can continue thinking about doing it the right way. Which is to first get some grasp of sorts about the various Java and other technologies and concepts you are talking about. Then have some kind of plan and follow it.
    I think at the end both you, and more importantly, your supervisor would see the difference in the result with respect to quality of work.
    Forums such as these provide an excellent wealth of information mostly because they are a means to consolidate knowledge gained by individuals from their past experience.
    However, in my opinion, it would be wrong to expect that one would be able to design and implement a real-life application just from information gathered from such forums. An example problem if you do it that way is: who will provide guaranteed support if something does not work in your real-life application. Your supervisor ?
    Instead, do the study part systematicaly. Try to convince your supervisor that thats the way to do it. Then do it. And come back with specific problems you might have.
    Best luck.

  • Urgent : Problem with Servlet Filters in Weblogic6.1

    Hi,
    We have developed an application using Tomcat4.1.24 with Weblogic6.1 Service Pack2.
    Now we are removing the Tomcat and moving the web layer into weblogic. We have implemented Servlet Filters and Listeners.
    When I converted .jar and .war files into .ear file and deployed into Weblogic6.1. But that application is not deploying. I found that Weblogic6.1 does not support Filters and Listeners from Servlet2.3.
    When I tried to deploy in the Weblogic6.1, it is giving the error as " java.lang.reflect.UndeclaredThrowableException".
    Could somebody please give me a solution how my filters and listeners can make working with weblogic6.1.
    Is there any solution.. My application is successfully working with Weblogic8.1. But I want the solution in weblogic6.1. It would be great if somebody can give me solution how to make Filters n Listeners working with Weblogic6.1.
    Thanks in advance.

    Hi Prasanna,
    Thank you for the timely reply.
    I have already done according to the process given in the url which u have given me.
    set and getFilterConfig methods are implemented in my AuthenticationFilter class. But still I could not be able deploy the application and I am not able to get the ServletContext object from Session. When I tried commenting the Filters and Listeners in my web.xml file then my .ear file was successfully deployed but I could not get the ServletContext from Session.
    Below code is from my web.xml:
    <filter>
    <filter-name>HRSuthenticationFilter</filter-name>
    <filter-class>com.peramb.hrs.servlet.AuthenticationFilter</filter-class>
    <init-param>
    <param-name>encoding</param-name>
    <param-value>UTF-8</param-value>
    </init-param>
    </filter>
    <filter-mapping>
    <filter-name>HRSAuthenticationFilter</filter-name>
    <url-pattern>/jsp/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
    <filter-name>HRSAuthenticationFilter</filter-name>
    <servlet-name>action</servlet-name>
    </filter-mapping>
    <listener>
    <listener-class>com.peramb.hrs.servlet.HRSContextListener</listener-class>
    </listener>
    When I comment the above code from web.xml it is deploying with out errors.. but I am not getting the servlet context, hence my application is not working.
    When tried uncommenting the listerns part or Filters part or bothe, My application is deploying with an error on the console. I.e,
    “<Sep 22, 2005 12:20:36 PM IST> <Error> <Management> <Error deploying application
    .\config\mydomain\applications\hrsgb.ear: java.lang.reflect.UndeclaredThrowable
    Exception>”.
    And the error in Weblogic logs is below:
    ####<Sep 22, 2005 12:20:36 PM IST> <Info> <HTTP> <spacker> <myserver> <ExecuteThread: '0' for queue: '__weblogic_admin_html_queue'> <system> <> <101047> <[WebAppServletContext(6387482,hrsgb,/hrsgb)] registering JSPServlet with initArgs '[JspConfig: verbose=true,packagePrefix=jsp_servlet,-compiler=javac,compileFlags=,workingDir=E:\bea\wlserver6.1\config\mydomain\applications\.wlnotdelete\wlap36546\WEB-INF\_tmp_war_mydomain_myserver_hrsgb,pageCheckSeconds=1,superclass=weblogic.servlet.jsp.JspBase,keepgenerated=false,precompileContinue=false,compilerSupportsEncoding=true,encoding=null,defaultfilename=index.jsp,compilerclass=null,noTryBlocks=false]'>
    ####<Sep 22, 2005 12:20:36 PM IST> <Debug> <HTTP> < spacker > <myserver> <ExecuteThread: '0' for queue: '__weblogic_admin_html_queue'> <system> <> <101158> <Exception thrown while loading hrsgb: java.lang.SecurityException: sealing violation>
    java.lang.SecurityException: sealing violation
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:229)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:51)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:190)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:183)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:294)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:281)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:250)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:310)
    at weblogic.servlet.internal.WebAppServletContext.registerEventListener(WebAppServletContext.java:2031)
    at weblogic.servlet.internal.WebAppServletContext.initFromDescriptors(WebAppServletContext.java:1471)
    at weblogic.servlet.internal.WebAppServletContext.init(WebAppServletContext.java:943)
    at weblogic.servlet.internal.WebAppServletContext.<init>(WebAppServletContext.java:878)
    at weblogic.servlet.internal.HttpServer.loadWebApp(HttpServer.java:515)
    at weblogic.j2ee.WebAppComponent.deploy(WebAppComponent.java:77)
    at weblogic.j2ee.Application.addComponent(Application.java:176)
    at weblogic.j2ee.J2EEService.addDeployment(J2EEService.java:117)
    at weblogic.management.mbeans.custom.DeploymentTarget.addDeployment(DeploymentTarget.java:364)
    at weblogic.management.mbeans.custom.DeploymentTarget.addDeployment(DeploymentTarget.java:150)
    at weblogic.management.mbeans.custom.WebServer.addWebDeployment(WebServer.java:76)
    at java.lang.reflect.Method.invoke(Native Method)
    at weblogic.management.internal.DynamicMBeanImpl.invokeLocally(DynamicMBeanImpl.java:636)
    at weblogic.management.internal.DynamicMBeanImpl.invoke(DynamicMBeanImpl.java:621)
    at weblogic.management.internal.ConfigurationMBeanImpl.invoke(ConfigurationMBeanImpl.java:374)
    at com.sun.management.jmx.MBeanServerImpl.invoke(MBeanServerImpl.java:1557)
    at com.sun.management.jmx.MBeanServerImpl.invoke(MBeanServerImpl.java:1525)
    at weblogic.management.internal.MBeanProxy.invoke(MBeanProxy.java:468)
    at weblogic.management.internal.MBeanProxy.invoke(MBeanProxy.java:209)
    at $Proxy37.addWebDeployment(Unknown Source)
    at weblogic.management.configuration.WebServerMBean_CachingStub.addWebDeployment(WebServerMBean_CachingStub.java:1337)
    at weblogic.management.mbeans.custom.DeploymentTarget.addDeployment(DeploymentTarget.java:350)
    at weblogic.management.mbeans.custom.DeploymentTarget.addDeployment(DeploymentTarget.java:150)
    at java.lang.reflect.Method.invoke(Native Method)
    at weblogic.management.internal.DynamicMBeanImpl.invokeLocally(DynamicMBeanImpl.java:636)
    at weblogic.management.internal.DynamicMBeanImpl.invoke(DynamicMBeanImpl.java:621)
    at weblogic.management.internal.ConfigurationMBeanImpl.invoke(ConfigurationMBeanImpl.java:374)
    at com.sun.management.jmx.MBeanServerImpl.invoke(MBeanServerImpl.java:1557)
    at com.sun.management.jmx.MBeanServerImpl.invoke(MBeanServerImpl.java:1525)
    at weblogic.management.internal.ConfigurationMBeanImpl.updateConfigMBeans(ConfigurationMBeanImpl.java:507)
    at weblogic.management.internal.ConfigurationMBeanImpl.invoke(ConfigurationMBeanImpl.java:376)
    at com.sun.management.jmx.MBeanServerImpl.invoke(MBeanServerImpl.java:1557)
    at com.sun.management.jmx.MBeanServerImpl.invoke(MBeanServerImpl.java:1525)
    at weblogic.management.internal.DynamicMBeanImpl.addDeployment(DynamicMBeanImpl.java:997)
    at weblogic.management.internal.DynamicMBeanImpl.addDeployment(DynamicMBeanImpl.java:984)
    at weblogic.management.internal.DynamicMBeanImpl.add(DynamicMBeanImpl.java:969)
    at weblogic.management.internal.DynamicMBeanImpl.invokeLocally(DynamicMBeanImpl.java:648)
    at weblogic.management.internal.DynamicMBeanImpl.invoke(DynamicMBeanImpl.java:621)
    at weblogic.management.internal.ConfigurationMBeanImpl.invoke(ConfigurationMBeanImpl.java:374)
    at com.sun.management.jmx.MBeanServerImpl.invoke(MBeanServerImpl.java:1557)
    at com.sun.management.jmx.MBeanServerImpl.invoke(MBeanServerImpl.java:1525)
    at weblogic.management.internal.MBeanProxy.invoke(MBeanProxy.java:468)
    at weblogic.management.internal.MBeanProxy.invoke(MBeanProxy.java:209)
    at $Proxy88.addTarget(Unknown Source)
    at weblogic.management.mbeans.custom.ApplicationManager.autoDeploy(ApplicationManager.java:930)
    at weblogic.management.mbeans.custom.ApplicationManager.addApplication(ApplicationManager.java:1039)
    at weblogic.management.mbeans.custom.ApplicationManager.addApplication(ApplicationManager.java:954)
    at weblogic.management.mbeans.custom.ApplicationManager.poll(ApplicationManager.java:851)
    at weblogic.management.mbeans.custom.ApplicationManager.poll(ApplicationManager.java:781)
    at weblogic.management.mbeans.custom.ApplicationManager.update(ApplicationManager.java:210)
    at java.lang.reflect.Method.invoke(Native Method)
    at weblogic.management.internal.DynamicMBeanImpl.invokeLocally(DynamicMBeanImpl.java:636)
    at weblogic.management.internal.DynamicMBeanImpl.invoke(DynamicMBeanImpl.java:621)
    at weblogic.management.internal.ConfigurationMBeanImpl.invoke(ConfigurationMBeanImpl.java:374)
    at com.sun.management.jmx.MBeanServerImpl.invoke(MBeanServerImpl.java:1557)
    at com.sun.management.jmx.MBeanServerImpl.invoke(MBeanServerImpl.java:1525)
    at weblogic.management.internal.MBeanProxy.invoke(MBeanProxy.java:468)
    at weblogic.management.internal.MBeanProxy.invoke(MBeanProxy.java:209)
    at $Proxy5.update(Unknown Source)
    at weblogic.management.console.webapp._domain.__upload_app._jspService(__upload_app.java:150)
    at weblogic.servlet.jsp.JspBase.service(JspBase.java:27)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:262)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:198)
    at weblogic.servlet.internal.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:284)
    at weblogic.servlet.jsp.PageContextImpl.forward(PageContextImpl.java:119)
    at weblogic.management.console.actions.ForwardAction.perform(ForwardAction.java:35)
    at weblogic.management.console.actions.internal.ActionServlet.doAction(ActionServlet.java:171)
    at weblogic.management.console.actions.internal.ActionServlet.doPost(ActionServlet.java:85)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:616)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:262)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:198)
    at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:2678)
    at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2412)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:140)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:121)
    ####<Sep 22, 2005 12:20:36 PM IST> <Error> <J2EE> < spacker> <myserver> <ExecuteThread: '0' for queue: '__weblogic_admin_html_queue'> <system> <> <160001> <Error deploying application hrsgb: Could not load hrsgb>
    ####<Sep 22, 2005 12:20:36 PM IST> <Error> <Management> < spacker> <myserver> <ExecuteThread: '0' for queue: '__weblogic_admin_html_queue'> <system> <> <141042> <Error deploying application .\config\mydomain\applications\hrsgb.ear: java.lang.reflect.UndeclaredThrowableException>
    I could not trace the problem. Please help me with some solution for the above problem

  • Need for Synchronization in Servlet

    Hi,
    If I have a method lets say saveCustInfo() and I call it from doget(). Roughly something like this:-
    Customer extends HttpServlet {
    doGet(req, res)
    parameters = ......
    saveCustInfo(parameters);
    saveCustInfo(....)
    //code for saving customer information
    Now question is, whether there is a need to synchronize on method saveCustInfo() or not???

    Thanks for the responses. Some things are clear to me but some things are still not. One of the responses said that I need to synchronize only if I am using a object or variable which is shared. But another response said that I need to synchronize if I am manipulating data inside the method.
    My method does not have shared variables or objects but definitely some data manipulation is there inside the method.
    Question is Do I need to synchronize if the some data manipulation is there locally inside the method? My understanding was that every call gets its own copy of the method on the stack so all the variables are local but still distinct.
    Please someone share their knowledge on this.
    Thanks

  • Urgent: Calling a servlet from DB?

    Hello,
    I need to call an external servlet which is in 9iAS server from Java Stored procedure.
    Can anybody give me an idea?
    Thanks,
    Viswa

    Hi Viswa,
    Use the HttpURLConnection class. See the Servlets.com Web site and Working with URLs lesson of the "Java Tutorial" as well.
    Good Luck,
    Avi.

  • Urgent!! Servlet not running

    Hi friends,
    i have installed tomcat 4.1 in D:\Tomcat 4.1
    i created following directory structure,
    test directory under D:\Tomcat 4.1\webapps
    jsp and Web-inf are under test directory
    classes directory is under Web-inf
    then i added following line to server.xml
    <Context path="/test" docBase="test" debug="0" reloadable="true"
    crossContext="true"></Context>
    then i placed web.xml under Web-inf
    web.xml is
    <?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>
    <display-name>Test</display-name>
    <description>
    Test
    </description>
    <session-config>
    <session-timeout>30</session-timeout> <!-- session times out
    after 30 minutes -->
    </session-config>
    </web-app>
    After this i tried to access the servlet (HelloWorldExample) whose class file is stored in classes directory eith following url
    http://localhost:8080/test/servlet/HelloWorldExample
    And it gives me following error
    HTTP Status 404 - /test/servlet/HelloWorldExample
    type Status report
    message /test/servlet/HelloWorldExample
    description The requested resource (/test/servlet/HelloWorldExample) is not available.
    Apache Tomcat/4.1.18
    pls help me i m feeling frustrated, i am trying it for last 3 days
    --Bhupendra Mahajan[b]

    I uncommented the lines u said in global web.xml
    restarted server
    and yes, it is WEB-INF
    and i have started getting new error
    HTTP Status 500 -
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    java.util.MissingResourceException: Can't find bundle for base name LocalStrings, locale en_US
         at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:804)
         at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:694)
         at java.util.ResourceBundle.getBundle(ResourceBundle.java:538)
         at HelloWorldExample.doGet(HelloWorldExample.java:24)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:260)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2415)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:170)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:432)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:386)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:534)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:530)
         at java.lang.Thread.run(Thread.java:536)
    Apache Tomcat/4.1.18
    what should i do next??
    --Bhupendra Mahajan

  • A better way to syncronize objects in servlets

    Hi,
    I am working on a webapp that has a servlet that invoque a instance of a object that accesses our sybase server.
    What is the best secure way to syncronize to avoid problems at the database?
    I have searched all of these but I am still confused:
    Syncronize the servlet
    public class LoginHandler extends HttpServlet implements SingleThreadModel
    Syncronize the object
    private DBManager dba = DBManager.getInstance() ;
    private String GetUserCode(String Username, String Password)
    syncronized(this) {
    DBResults rsResult = dba.ExecQuery(SQLQuery);
    Syncronize the object in the class
    public class DBManager implements Serializable
    private static DBManager _instancie = new DBManager();
    public static synchronized DBManager getInstance()
    if (_instance == null) _instance = new DBManager();
    return _instance;
    Syncronize the db connection
    try
    synchronized (ds)
    con = ds.getConnection();
    st = con.createStatement();
    rs = st.executeQuery(sqlQuery);
    if (rs.next()) rsValue = rs.getString(1);
    catch (Exception e)
    Syncronize method
    public static syncronized String getDBValue(String SQL)
    Thanks very much,
    Lorenzo

    I would not synchronize the servlet with SingleThreadModel
    I would not have all this code in the servlet at all. (Servlets handle HTTP requests, after all.) Would you want to avoid problems at the database if you didn't have a Web interface? I think so. In that case, take care of the problem in the persistence layer, as close to the database as possible.
    You don't want to do anything that will increase your sense of security and kill your performance.
    I think there's a difference between synchronization and isolation. Read up on the java.sql.Connection.setTransactionIsolation(int level) method. I believe that's pertinent.
    I think you should investigate pessimistic vs optimistic locking, isolation, dirty reads, phantom reads and writes. I'd enlist the help of the database and its admin as much as possible.

  • Loading Servlet Error - Websphere

    Hi,
    I have deployed a application in WebSphere v.4. when I am starting the Application, It is giving below error. Wht is cause pls help. Urgent.
    Error:
    Servlet Error-[UpDelScoreSheetServlet]: Failed to load servlet: java.lang.NoClassDefFoundError: java/lang/CharSequence
         at java.lang.Class.newInstance0(Native Method)
         at java.lang.Class.newInstance(Class.java(Compiled Code))
         at java.beans.Beans.instantiate(Beans.java:233)
         at java.beans.Beans.instantiate(Beans.java:77)
         at com.ibm.servlet.engine.webapp.WebAppServletManager.loadServlet(WebAppServletManager.java:141)
         at com.ibm.servlet.engine.webapp.WebAppServletManager.loadAutoLoadServlets(WebAppServletManager.java:325)
         at com.ibm.servlet.engine.webapp.WebApp.loadServletManager(WebApp.java:1217)
         at com.ibm.servlet.engine.webapp.WebApp.init(WebApp.java:145)
         at com.ibm.servlet.engine.srt.WebGroup.loadWebApp(WebGroup.java:259)
         at com.ibm.servlet.engine.srt.WebGroup.init(WebGroup.java:168)
         at com.ibm.servlet.engine.ServletEngine.addWebApplication(ServletEngine.java:856)
         at com.ibm.ws.runtime.WebContainer.install(WebContainer.java:36)
         at com.ibm.ws.runtime.Server.startModule(Server.java:617)
         at com.ibm.ejs.sm.active.ActiveModule.startModule(ActiveModule.java:511)
         at com.ibm.ejs.sm.active.ActiveModule.startAction(ActiveModule.java:355)
         at com.ibm.ejs.sm.active.ActiveObject.startObject(ActiveObject.java:722)
         at com.ibm.ejs.sm.active.ActiveObject.start(ActiveObject.java:131)
         at java.lang.reflect.Method.invoke(Native Method)
         at com.ibm.ejs.sm.agent.AdminAgentImpl.activeObjectInvocation(AdminAgentImpl.java:93)
         at com.ibm.ejs.sm.active.ActiveObject.invokeContainedObject(ActiveObject.java:525)
         at com.ibm.ejs.sm.agent.AdminAgentImpl.activeObjectInvocation(AdminAgentImpl.java:110)
         at com.ibm.ejs.sm.agent.AdminAgentImpl.invokeActiveObject(AdminAgentImpl.java:62)
         at com.ibm.ejs.sm.agent._AdminAgentImpl_Tie._invoke(_AdminAgentImpl_Tie.java:73)
         at com.ibm.CORBA.iiop.ExtendedServerDelegate.dispatch(ExtendedServerDelegate.java:532)
         at com.ibm.CORBA.iiop.ORB.process(ORB.java:2395)
         at com.ibm.CORBA.iiop.OrbWorker.run(OrbWorker.java:186)
         at com.ibm.ejs.oa.pool.ThreadPool$PooledWorker.run(ThreadPool.java:104)
         at com.ibm.ws.util.CachedThread.run(ThreadPool.java:138)

    Hi
    Sounds like you wrote your code against JDK 1.4.2 but WebSphere is probably running on 1.3.x (can't remember exactly what WAS 4 run on)
    So although your code compiled, WAS doesn't know what CharSequence is because it only became part of the java.lang package in 1.4.x
    I suggest you change your JDK down to the version used in WAS because you'll probably find other problems that you weren't expecting due to the difference in JDK versions.
    -Rich

  • Servlet Database I/O: How to "lock" a record being updated ?

    Say you have a servlet that displays a list of customers in HTML page, and a button on each customer to click to bring up another page (servlet generated) with the customer info to edit. The customer info is in a database file (could be Access or ORACLE). User makes any changes and clicks a button to update the customer record (with a servlet).
    How do you prevent two users from editing the same customer record at the same time? I do not want to lock the whole file, just a record.
    Any pointers towards info about this subject appreciated.
    Walk Good

    sridharranganathan, does your technique assume that the read operation is locked, so that two users cannot obtain the same value of LockCounter?
    I have some questions relevant to the following code:
    public class theServlet extends HttpServlet
        public void doGet(HttpServletRequest req, HttpServletResponse resp)
         throws ServletException, IOException
             Helper theHelper = new Helper();
             theHelper.setUser(req.getCookies);
             resp.setContentType("text/html");
                PrintWriter out = new PrintWriter(resp.getOutputStream());
                Connection con = null;
             try
                   SybDriver sybDriver = (SybDriver) Class.forName("com.sybase.jdbc2.jdbc.SybDriver").newInstance();
                   sybDriver.setVersion(com.sybase.jdbcx.SybDriver.VERSION_5);
                   DriverManager.registerDriver(sybDriver);
                   con = DriverManager.getConnection("jdbc:sybase:Tds:dbsrv1:3520/hospcap", "myuserid", "mypassword");                 if (con != null) {
                  if(theHelper.getUserRecord(con, this)) {
                           //do some stuff
                        else { //do some other stuff }
                        con.close();
                 }catch(Exception e) { //whatever }
                 finally { out.flush(); }
             } //end doGet()
    } //end class
    public class Helper {
        private String user = "";
        private String field1Val= "";
        private String field2Val= "";
        public boolean setUser(Cookie [] cookies) {
         // method gets the user's userid from a cookie and then:
            user = user_id_from_cookie;
       public boolean getUserRecord(Connection con, theServlet serv){
            StringBuffer sb = new StringBuffer();
            Statement stmt = null;
         try {
             //Try to get the user's info:
                stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
             StringBuffer sql = new StringBuffer("SELECT field1, field2 FROM UserRecords WHERE user_id = '" + user + "'");
             ResultSet rs = stmt.executeQuery(sql.toString());
                rs.last();
                int nrows = rs.getRow();
                if(nrows < 1) { //user doesn't have an entry in the table yet.
                 //First, get result set of records with blank userids:
                 sql.replace(0, sql.length(), "SELECT * FROM UserRecords WHERE user_id = '' OR user_id = NULL ORDER BY field1");
              rs = stmt.executeQuery(sql.toString());
                    rs.last();
                    nrows = rs.getRow();
                 if(nrows > 0) {
                     //there ARE some records with null user_id, so assign this user to the first one:
                        rs.first();
                     field1Val = rs.getString("field1").trim();
                     field2Val = rs.getString("field2").trim();
                        //QUESTION: IS IT POSSIBLE THAT TWO USERS/THREADS HAVE THE SAME VALUE OF field1Val AT THIS POINT?
                     sql.replace(0, sql.length(), "UPDATE UserRecords SET user_id = '" + user + "' ");
                     sql.append(" WHERE field1 = '" + field1Val+ "' AND user_id is NULL");
                  con.setAutoCommit(false);
                  //Trying to use transaction isolation to prevent two users from updating the same record.
                  //Does this only work if the users share the connection, con?
                  int level = con.getTransactionIsolation();
                  try {
                      if(con.getMetaData().supportsTransactionIsolationLevel(con.TRANSACTION_READ_COMMITTED)) {
                          con.setTransactionIsolation(con.TRANSACTION_READ_COMMITTED);
                            //SYNCHRONIZE ON SERVLET INSTANCE?
                      //synchronized(serv){
                            nrows = stmt.executeUpdate(sql.toString());
                  }catch(SQLException se) {
                         con.rollback();
                         con.setAutoCommit(true);
                         con.setTransactionIsolation(level);
                         stmt.close();
                         return false;
                     con.commit();
                     con.setAutoCommit(true);
                     con.setTransactionIsolation(level);
                        if(nrows < 1) { //couldn't update the db.
                         stmt.close();
                         return false;
                     else {
                         stmt.close();
                         return true;
                 else { //There aren't any unused records; deal with it.
                     stmt.close();
                     return false;
                else { // the user has an entry in the table
                    rs.first(); //should only be one record for this userid.
                    field1Val = rs.getString("field1").trim();
                    field2Val = rs.getString("field2").trim();
                    stmt.close();
                 return true;
            }catch(SQLException se) {
             //some problem not caught elsewhere
             return false;
       } // end getUserRecord
    } // end class HelperI should say that the UserRecords table now contains about 5000 records (this will grow in increments of 5000), many of which have null user_id. If the value is not null, then it contains a userid. A user can have either zero or one entry in the table.
    Here are my questions regarding the above:
    1. In the servlet, each thread will have its own instance of Helper and of Connection, correct?
    2. I want to ensure that only one thread can update a particular UserRecords table record at a time. In the getUserRecord method, please note the line where field1Val is assigned, just above the capitalized QUESTION comment. Is it possible that two threads could have the same value of field1Val at the same time?
    3. When you set the transaction isolation level for connection1, does that prevent other threads that are using other connections to the database from accessing records being updated by the thread using connection1?
    4. As you can see, I am considering passing a reference to the servlet instance into the getUserRecords method and synchronizing the update statement on the servlet instance. Will that ensure only one thread at a time can update the record, without using the transaction isolation code?
    Thanks in advance for your answer.

  • Protecting records in database, multithreading in servlets

    I have some questions (below) relevant to the following code:
    public class theServlet extends HttpServlet
        public void doGet(HttpServletRequest req, HttpServletResponse resp)
         throws ServletException, IOException
             Helper theHelper = new Helper();
             theHelper.setUser(req.getCookies);
             resp.setContentType("text/html");
                PrintWriter out = new PrintWriter(resp.getOutputStream());
                Connection con = null;
             try
                   SybDriver sybDriver = (SybDriver) Class.forName("com.sybase.jdbc2.jdbc.SybDriver").newInstance();
                   sybDriver.setVersion(com.sybase.jdbcx.SybDriver.VERSION_5);
                   DriverManager.registerDriver(sybDriver);
                   con = DriverManager.getConnection("jdbc:sybase:Tds:dbsrv1:port/appname", "myuserid", "mypassword");                 if (con != null) {
                  if(theHelper.getUserRecord(con, this)) {
                           //do some stuff
                        else { //do some other stuff }
                        con.close();
                 }catch(Exception e) { //whatever }
                 finally { out.flush(); }
             } //end doGet()
    } //end class
    public class Helper {
        private String user = "";
        private String field1Val= "";
        private String field2Val= "";
        public boolean setUser(Cookie [] cookies) {
         // method gets the user's userid from a cookie and then:
            user = user_id_from_cookie;
       public boolean getUserRecord(Connection con, theServlet serv){
            StringBuffer sb = new StringBuffer();
            Statement stmt = null;
         try {
             //Try to get the user's info:
                stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );
             StringBuffer sql = new StringBuffer("SELECT field1, field2 FROM UserRecords WHERE user_id = '" + user + "'");
             ResultSet rs = stmt.executeQuery(sql.toString());
                rs.last();
                int nrows = rs.getRow();
                if(nrows < 1) { //user doesn't have an entry in the table yet.
                 //First, get result set of records with blank userids:
                 sql.replace(0, sql.length(), "SELECT * FROM UserRecords WHERE user_id = '' OR user_id = NULL ORDER BY field1");
              rs = stmt.executeQuery(sql.toString());
                    rs.last();
                    nrows = rs.getRow();
                 if(nrows > 0) {
                     //there ARE some records with null user_id, so assign this user to the first one:
                        rs.first();
                     field1Val = rs.getString("field1").trim();
                     field2Val = rs.getString("field2").trim();
                        //QUESTION: IS IT POSSIBLE THAT TWO USERS/THREADS HAVE THE SAME VALUE OF field1Val AT THIS POINT?
                     sql.replace(0, sql.length(), "UPDATE UserRecords SET user_id = '" + user + "' ");
                     sql.append(" WHERE field1 = '" + field1Val+ "' AND user_id is NULL");
                  con.setAutoCommit(false);
                  //Trying to use transaction isolation to prevent two users from updating the same record.
                  //Does this only work if the users share the connection, con?
                  int level = con.getTransactionIsolation();
                  try {
                      if(con.getMetaData().supportsTransactionIsolationLevel(con.TRANSACTION_READ_COMMITTED)) {
                          con.setTransactionIsolation(con.TRANSACTION_READ_COMMITTED);
                            //SYNCHRONIZE ON SERVLET INSTANCE?
                      //synchronized(serv){
                            nrows = stmt.executeUpdate(sql.toString());
                  }catch(SQLException se) {
                         con.rollback();
                         con.setAutoCommit(true);
                         con.setTransactionIsolation(level);
                         stmt.close();
                         return false;
                     con.commit();
                     con.setAutoCommit(true);
                     con.setTransactionIsolation(level);
                        if(nrows < 1) { //couldn't update the db.
                         stmt.close();
                         return false;
                     else {
                         stmt.close();
                         return true;
                 else { //There aren't any unused records; deal with it.
                     stmt.close();
                     return false;
                else { // the user has an entry in the table
                    rs.first(); //should only be one record for this userid.
                    field1Val = rs.getString("field1").trim();
                    field2Val = rs.getString("field2").trim();
                    stmt.close();
                 return true;
            }catch(SQLException se) {
             //some problem not caught elsewhere
             return false;
       } // end getUserRecord
    } // end class HelperI should say that the UserRecords table now contains about 5000 records (this will grow in increments of 5000), many of which have null user_id. If the value is not null, then it contains a userid. A user can have either zero or one entry in the table.
    Here are my questions:
    1. In the servlet, each thread will have its own instance of Helper and of Connection, correct?
    2. I want to ensure that only one thread can update a particular UserRecords table record at a time. In the getUserRecord method, please note the line where field1Val is assigned, just above the capitalized QUESTION comment. Is it possible that two threads could have the same value of field1Val at the same time?
    3. When I set the transaction isolation level for connection1, does that prevent other threads that are using other connections to the database from accessing records being updated by the thread using connection1?
    4. As you can see, I am considering passing a reference to the servlet instance into the getUserRecords method and synchronizing the update statement on the servlet instance. Will that ensure only one thread at a time can update the record, without using the transaction isolation code?
    Thanks in advance for your answer.

    1. In the servlet, each thread will have its own
    instance of Helper and of Connection, correct?True
    2. I want to ensure that only one thread can update a
    particular UserRecords table record at a time. In the
    getUserRecord method, please note the line where
    field1Val is assigned, just above the capitalized
    QUESTION comment. Is it possible that two threads
    could have the same value of field1Val at the same
    time?Yes, use synchronized blocks to avoid problems.
    3. When I set the transaction isolation level for
    connection1, does that prevent other threads that are
    using other connections to the database from accessing
    records being updated by the thread using
    connection1?Yes
    4. As you can see, I am considering passing a
    reference to the servlet instance into the
    getUserRecords method and synchronizing the update
    statement on the servlet instance. Will that ensure
    only one thread at a time can update the record,
    without using the transaction isolation code?Yes.
    http://galileo.spaceports.com/~ibidris/

  • Urgent:Please Help. Need to deploy web application with servlet:(

    Tomcat 4.0 is already installed.
    Trying to deploy a web application and invoke a servlet through it.
    Here is the command I am using for deploying the application:
    http://localhost:8080/manager/install?path=/NewApplication&war=file:d:\Tomcat4\webapps\NewApplication
    The application get deployed. However, I have a problem. As soon I stop and restart the server, this application is gone.
    1. Please someone help: How should I make it permanent so that the application stays even if I restart the server.
    2. I am not able to access the servlets placed in the /WEB-INF/classes/ sub-directory under NewApplication directory.
    If you need I can cut and paste the web.xml file which will show the deployment descriptor.
    Please help: How do I make this work. I need it urgent.
    Any help will be appreciated.
    Thanks,
    Indrasish.

    The simplest solution would be to put the war file inside the webapps directory and restart the server. You should be able to access the app using the http://servername/app

  • Insert/Delete in a servlet to dbase  - URGENT!!

    I have an urgent question. If I use a query to select from values based on a variable from a JSP (subject code)...... and then based on the values returned by this query (i.e code, year and semester,unit) I then want to add/delete these values to a new table (called chosensubject), based on whether they chose the variable drop or add in the JSP!!
    How do I do this???
    I am using a servlet which picks up the data from a JSP after it is submitted to the server.
    Please Help!
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.ServletException;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.Statement;
    import java.sql.ResultSet;
    import java.sql.DriverManager;
    import java.io.*;
    import java.sql.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class loginAssign2 extends HttpServlet
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    //get the parametes from the JSP page
    String sem1c1 = request.getParameter("Sem1#1").trim();
    String us = request.getParameter("username").trim();
    String sem1c2 =request.getParameter("Sem1#2").trim();
    String sem1c3 = request.getParameter("Sem1#3").trim();
    String sem1c4 = request.getParameter("Sem1#4").trim();
    String sem2c1 = request.getParameter("Sem2#1").trim();
    String sem2c2 = request.getParameter("Sem2#3").trim();
    String sem2c3 = request.getParameter("Sem2#3").trim();
    String sem2c4 = request.getParameter("Sem2#4").trim();
    String userID = request.getParameter("userID").trim();
    String Drop1 = request.getParameter("drop1").trim();
    String Drop2 = request.getParameter("drop2").trim();
    String Drop3 = request.getParameter("drop3").trim();
    String Drop4 = request.getParameter("drop4").trim();
    String Drop5 = request.getParameter("drop5").trim();
    String Drop6 = request.getParameter("drop6").trim();
    String Drop7 = request.getParameter("drop7").trim();
    String Drop8 = request.getParameter("drop8").trim();
    String sqlQuery;
    String sqlQuery2;
    if (sem1c1 !="") {
    sqlQuery = "select*from tmpoffering where code = '" + sem1c2 + "'";
    // Iterate through the result and verify the password
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    Connection conn = null;
    try {   
    Class.forName("oracle.jdbc.driver.OracleDriver");
    conn = DriverManager.getConnection("jdbc:oracle:thin:@Midas2:1521:globaldb", "system", "manager");
    catch (Exception e) {
    out.println("Cannot close connect to database!"+e);
    if (conn != null) {
    try { // execute the query
    Statement stmt = conn.createStatement();
    ResultSet rst;
    rst = stmt.executeQuery(sqlQuery);
    // Fetch the query result, and dispaly them in a table
    while (rst.next()) {
    <<Need help here!!!! Think I need an if statement (i.e if 'drop' then delete otherswise if 'add' then insert!!!... but how do I put it into a servlet??)
         sqlQuery2 = "insert into subjectchoosen values ('code','year','sem','userID') ";
    stmt.close();
    } catch(Exception e) {
         out.println("Cannot fetch data from database!"+e);
    out.println("</table>");
    out.println("</body></html>");

    If the servlet is within an application container,
    you can locate a data source create a SQL connection an execue a query.
    DataSource ds =  (DataSource) (new InitialContetx()).lookup("my_ds");
    Connection conn = ds.getConnection();if it is only a web server
    /** sample using JSQLDriver */
    Connection conn = null;
    Statment stmt = null;
    ResultSet rs = null;
    try {
      Class.forName("com.jnetdirect.jsql.JSQLDriver");
      conn = DriverManager.getConnection(
              "jdbc:JSQLConnect://localhost/database=master",
              "sa",
      stmt = conn.createStatement();
      rs = stmt.executeQuery("select * from my_table");
    } finally {
      try {
        if (rst != null) {
          rs.close();
        if (stmt != null) {
          stmt.close();
        if (conn != null) {
            conn.close();
      catch (SQLException ex2) {
    }

  • WAP/Servlet help is needed URGENT!!!

    I've wrote this little wap-application, which update the library loans via mobile phones. I don't know why my login doesn't work properly (it gives error-messages in any cases). I believe I did everything right.
    Can anyone PLEASE help me finding my mistakes!? I give all my dukes for working version of mine application.
    This are my codes:
    Servlet-class
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    public class Uusinta extends HttpServlet {
    Connection conn;
    String TUNNUS = "2000000112222";
    String user = null;
    boolean yhteys = false;
    static String [] otsikko = {
    "<?xml version=\"1.0\" encoding=\"utf-8\"?>",
    "<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.3//EN\" \"http://www.wapforum.org/DTD/wml13.dtd\"> " ,
    "<wml>" ,
    "<!-- Possible <head> elements here. --> " ,
    "<template>" ,
    "<do type=\"accept\" label=\"Ok\" name=\"back\" >" ,
    "<prev/>" ,
    "</do>" ,
    "</template>" ,
    "<card id=\"welcome\" title=\"WAP-kirjasto\" newcontext=\"true\">" ,
    "<do type=\"accept\" name=\"back\"><noop/>" ,
    "</do>" ,
    "<p align=\"center\"><strong>TERVETULOA</strong></p>",
    "<p><br/>Kirjastokortin numero:<br/>" ,
    "<input type=\"text\" name=\"numero\" size=\"11\" format=\"*N\" maxlength=\"13\"/><br/>" ,
    "Salasana:<br/>" ,
    "<input type=\"text\" name=\"salasana\" size=\"4\" format=\"*N\" maxlength=\"4\"/><br/>" ,
    "<a href=\"skripti.wmls#Login('$(numero)','$(salasana)','kayttaja')\">Sisaan </a></p>" ,
    "</card>" ,
    "<card id=\"loginError\">" ,
    "<do type=\"prev\" label=\"Back\">" ,
    "<go href=\"#welcome\"/>" ,
    "</do>" ,
    "<p align=\"center\"><br/>Korttinumero tai salasana on vaara.</p>" ,
    "</card>" ,
    "<card id=\"lainat\" newcontext=\"true\">" ,
    "<do type=\"accept\" name=\"back\"><noop/>" ,
    "</do>" ,
    "<do type=\"options\" label=\"Lopeta\">" ,
    "<go href=\"#goodbye\"/>" ,
    "</do>" ,
    "<p><b>Lainatut kirjat:</b></p><p> " ,
    "<select name=\"item\" title=\"Lista\">"};
    static String [] r2 = {
    "</select>" ,
    "<br/><a href=\"skripti.wmls#uusiNide('$(item)','valittu')\">Uusi valittu</a><br/>" ,
    "<a href=\"skripti.wmls#uusiKaikki()\">Uusi kaikki</a></p>" ,
    "</card>" ,
    "<card id=\"virhe\">" ,
    "<p>Kirjan uusiminen ei onnistunut. Yrit&#xE4; uudelleen.</p>" ,
    "</card>" ,
    "<card id=\"uusittu\">" ,
    "<do type=\"prev\" label=\"Back\">",
    " <go href=\"#lainat\"/>",
    "</do>",
    "<p align=\"center\"><br/>Kirja on uusittu.</p>" ,
    "</card>" ,
    "<card id=\"virheet\">" ,
    "<p>Kirjojen uusiminen ei onnistunut. Yrit&#xE4; uudelleen.</p>" ,
    "</card>" ,
    "<card id=\"uusitut\">" ,
    "<do type=\"prev\" label=\"Back\">",
    " <go href=\"#goodbye\"/>",
    "</do>",
    "<p align=\"center\"><br/>Kirjat on uusittu.</p>" ,
    "</card>" ,
    "<card id=\"goodbye\" newcontext=\"true\">" ,
    "<do type=\"accept\" name=\"back\"><noop/>" ,
    "</do>" ,
    "<p align=\"center\"><br/>Kiitos k�ynnist�. Ja tervetuloa uudelleen.</p>" ,
    "</card>" ,
    "</wml>"};
    private void teeWML(PrintWriter out)
    Statement stmt;
    ResultSet result;
    boolean ok = false;
    for (int i = 0; i <otsikko.length;i++)
         out.println(otsikko);
         if(yhteys)
    try {
    stmt= conn.createStatement();
    result = stmt.executeQuery("Select * FROM lainat l join kirja k on l.nide = k.nide where tunnus = '"+this.user+"'");
    int cnt = 1;
    while(result.next())
              ok = true;
                   String nimi ="";
         if(result.getString("nimi").length() > 8)
         nimi = result.getString("nimi").substring(0,8) + "...";
         else
         nimi = result.getString("nimi");
              out.println("<option value=\""+result.getString("l.nide")+"\">"+nimi+":"
              result.getString("erapaiva")"</option>");
    result.close();
    stmt.close();
    }catch (SQLException ex) {
    System.out.println ("\nSQLException:");
    while (ex != null) {
    System.out.println ("SQLState: "+ ex.getSQLState());
    System.out.println ("Message: "+ ex.getMessage());
    System.out.println ("Vendor: "+ ex.getErrorCode());
    ex = ex.getNextException();
    else
              out.println("<option value=\"0\">nothing</option>");
         for (int i = 0; i <r2.length;i++)
              out.println(r2[i]);
    out.close();
    private void uusiNide(PrintWriter out, String nide)
    Statement stmt;
    ResultSet result;
    boolean ok=false;
         try {
    stmt= conn.createStatement();
    result = stmt.executeQuery("Select nide from lainat where tunnus='"+user+"' ");
    int cnt = 1;
    while(result.next())
              ok = true;
    result.close();
    stmt.close();
         if(ok)
              String pvm = getPvm();
              stmt = conn.createStatement();
              int a = stmt.executeUpdate("update lainat set erapaiva='"+pvm+"' where tunnus='"+user+"' AND nide='"+nide+"'");
    }catch (SQLException ex) {
    System.out.println ("\nSQLException:");
    while (ex != null) {
    System.out.println ("SQLState: "+ ex.getSQLState());
    System.out.println ("Message: "+ ex.getMessage());
    System.out.println ("Vendor: "+ ex.getErrorCode());
    ex = ex.getNextException();
         if(ok) {
         out.println("<!doctype html public \"-//w3c//dtd html 4.0 transitional//en\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">");
              out.println("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"><title>koe</title></head><body><p>OKnide</p></body></html>");
    private void uusiKaikkiNiteet(PrintWriter out)
    Statement stmt;
    ResultSet result;
    boolean ok=false;
    //t�h�n tulee viel� korttinumero
         try {
              String pvm = getPvm();
         stmt = conn.createStatement();
              int a = stmt.executeUpdate("update lainat set erapaiva='"+pvm+"' where tunnus='"+user+"'");
    }catch (SQLException ex) {
    System.out.println ("\nSQLException:");
    while (ex != null) {
    System.out.println ("SQLState: "+ ex.getSQLState());
    System.out.println ("Message: "+ ex.getMessage());
    System.out.println ("Vendor: "+ ex.getErrorCode());
    ex = ex.getNextException();
    if(ok) {
              out.println("<!doctype html public \"-//w3c//dtd html 4.0 transitional//en\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">");
              out.println("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"><title>koe</title></head><body><p>OKKaikki</p></body></html>");
    private void tarkKayttaja(PrintWriter out, String kayttaja, String password)
    Statement stmt;
    ResultSet result;
    boolean ok=false;
    String nimi = null;
    if(user !=null && password !=null)
    int salasana = Integer.parseInt(password);
    try {
    stmt= conn.createStatement();
    result = stmt.executeQuery("Select * from kortti where numero='"+kayttaja+"' and salasana="+salasana);
    while(result.next())
              ok = true;
              nimi = result.getString("nimi");
    }catch (SQLException ex) {
         System.out.println ("\nSQLException:");
         while (ex != null) {
         System.out.println ("SQLState: "+ ex.getSQLState());
         System.out.println ("Message: "+ ex.getMessage());
         System.out.println ("Vendor: "+ ex.getErrorCode());
         ex = ex.getNextException();
         if(ok) {
                   this.user= kayttaja;
                   yhteys = true;
                   //teeWML(out);
         out.println("<!doctype html public \"-//w3c//dtd html 4.0 transitional//en\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">");
              out.println("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"><title>koe</title></head><body><p>OK</p></body></html>");
              //out.close();
         teeWML(out);
    public void init(ServletConfig cfg) throws ServletException
    try{
    Driver d = (Driver)Class.forName("com.mysql.jdbc.Driver").newInstance();
    String sCon = "jdbc:mysql://localhost/kirjasto?user=oppilas&password=oppix";
    conn = DriverManager.getConnection(sCon);
    }catch(Exception e){
    System.out.println ("Exception: "+ e.getMessage());
    throw new ServletException(e.getMessage());
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws IOException, ServletException
    PrintWriter out = null;
         String kutsu = req.getParameter("toiminto");
         String uusinta = req.getParameter("uusinta");
         String password = req.getParameter("password");
         String kayttaja = req.getParameter("user");
         if (kutsu == null) {
         res.setContentType("text/vnd.wap.wml");
         out = res.getWriter();
              tarkKayttaja(out, null, null);
         if(kutsu.equalsIgnoreCase("login")) {
         res.setContentType("text/html");
         out = res.getWriter();
              tarkKayttaja(out, kayttaja, password);
         if(kutsu.equalsIgnoreCase("uusi")) {
         res.setContentType("text/html");
         out = res.getWriter();
              uusiNide(out, uusinta);
         if(kutsu.equalsIgnoreCase("uusiKaikki")){
              res.setContentType("text/html");
              out = res.getWriter();
              uusiKaikkiNiteet(out);
    public void destroy()
    try{
    conn.close();
    }catch(SQLException e){
    System.out.println ("\nSQLException:");
    System.out.println ("SQLState: "+e.getSQLState());
    System.out.println ("Message: "+ e.getMessage());
    System.out.println ("Vendor: "+ e.getErrorCode());
    public String getPvm()
         Calendar x = Calendar.getInstance();
         x.add(Calendar.DATE, 30);
              int Day = x.get(Calendar.DAY_OF_YEAR);
              Day = Day+30;
              x.set(Calendar.DAY_OF_YEAR, Day);
              int monthDue = x.get(Calendar.MONTH);
              int dayOfMonthDue = x.get(Calendar.DAY_OF_MONTH);
              int yearDue = x.get(Calendar.YEAR);
                   System.out.println(yearDue+"-"+monthDue+"-"+dayOfMonthDue);
              return (yearDue+"-"+monthDue+"-"+dayOfMonthDue);
    skriptit.wmls
    extern function uusiNide(prmIn,valittu) {
         var str, result, okInd, pInd;
         str = "http://localhost:8080/kirjasto/loans?toiminto=uusi&uusinta=" +URL.escapeString(prmIn);
         var load = URL.loadString(str,"text/html");
         okInd =String.find(load, "OKnide");
         if( okInd != -1 ) {
              result = WMLBrowser.setVar(valittu, prmIn);
              WMLBrowser.go("#uusittu");
         else {
              WMLBrowser.go("#virhe");
         return "";
    extern function uusiKaikki() {
         var str, result, okInd, pInd, val, valittu;
         str = "http://localhost:8080/kirjasto/loans?toiminto=uusiKaikki&uusinta=";
         var load = URL.loadString(str,"text/html");
         okInd =String.find(load, "OKKaikki");
         if( okInd != -1 ) {
              WMLBrowser.go("#uusitut");
         else {
              WMLBrowser.go("#virheet");
         return "";
    extern function Login(prmNum, prmPass, kayttaja) {
         var str, result, okInd, pInd, pos, nimi;
         str = "http://localhost:8080/kirjasto/loans?toiminto=login&user="+URL.escapeString(prmNum)+"&password="+URL.escapeString(prmPass);
         var load = URL.loadString(str,"text/html");
         okInd =String.find(load, "OK");
         if( okInd != -1 ) {     
              pos = String.find(load, "</p");
              nimi = String.subString(load,(okInd + 7), (pos - okInd -7));
              result = WMLBrowser.setVar(kayttaja, nimi);
              WMLBrowser.go("#lainat");
         else {
              WMLBrowser.go("#loginError");
         return "";
    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/j2ee/dtds/web-app_2_3.dtd'>
    <web-app>
    <display-name>Verkkopizzeria</display-name>
    <servlet>
    <servlet-name>Vastaa</servlet-name>
    <servlet-class>Vastaa</servlet-class>
    </servlet>
    <servlet>
    <servlet-name>Uusinta</servlet-name>
    <servlet-class>Uusinta</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>Vastaa</servlet-name>
    <url-pattern>/vastaa</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
    <servlet-name>Uusinta</servlet-name>
    <url-pattern>/loans</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    </web-app>
    DB create and inserts
    create table kortti(
    numero char(13) not null,
    nimi char(25),
    osoite char(25),
    postinro int(5),
    puhelin char(15),
    salasana int(4),
    primary key(numero)
    create table kirja(
    nide char(10) not null,
    nimi char(25) not null,
    tekija char(25) not null,
    vuosi int(4) not null,
    primary key(nide)
    create table lainat(
    tunnus char(13) not null,
    nide char(10) not null,
    erapaiva date not null,
    primary key (tunnus, nide),
    foreign key (tunnus) references kortti,
    foreign key (nide) references kirja );
    insert into kortti
    (numero, nimi, osoite, postinro, puhelin, salasana)
    values
    ('2000000112222', 'Aku Ankka', 'Akunkatu 11', 00980, '0401231234', 2222);
    insert into kortti
    (numero, nimi, osoite, postinro, puhelin, salasana)
    values
    ('2000000113333', 'Roope Set�', 'Mikonkatu 11', 00100, '0405552223', 3333);
    insert into kortti
    (numero, nimi, osoite, postinro, puhelin, salasana)
    values
    ('2000000114444', 'Mikki Hiiri', 'Kissankuja 5', 00930, '04009876545', 4444);
    insert into kortti
    (numero, nimi, osoite, postinro, puhelin, salasana)
    values
    ('2000000115555', 'Ville Vallaton', 'Mestarinrinne 4', 00310, '0952223335', 5555);
    insert into kirja
    (nide, nimi, tekija, vuosi)
    values
    ('1111-85555','Wap', 'Pekka Niskanen', 2000);
    insert into kirja
    (nide, nimi, tekija, vuosi)
    values
    ('1111-45345','Java 2', 'Pekka Niskanen', 2002);
    insert into kirja
    (nide, nimi, tekija, vuosi)
    values
    ('1111-64648','J�rki ja tunteet', 'Jane Austin', 1998);
    insert into kirja
    (nide, nimi, tekija, vuosi)
    values
    ('1111-15671','Rikos ja rangastus', 'Leo Tolstoy', 1998);
    insert into kirja
    (nide, nimi, tekija, vuosi)
    values
    ('1111-85554','Inside Wap', 'Pekka Niskanen', 2002);
    insert into lainat
    (tunnus, nide, erapaiva)
    values
    ('2000000112222', '1111-85555', '2004-5-01-11');
    insert into lainat
    (tunnus, nide, erapaiva)
    values
    ('2000000112222', '1111-45345', '2004-5-01-11');
    insert into lainat
    (tunnus, nide, erapaiva)
    values
    ('2000000112222', '1111-64648', '2004-5-01-12');
    insert into lainat
    (tunnus, nide, erapaiva)
    values
    ('2000000113333', '1111-85554', '2004-5-01-11');
    insert into lainat
    (tunnus, nide, erapaiva)
    values
    ('2000000114444', '1111-15671', '2004-5-01-12');

    So many things wrong with this post... from [url http://www.catb.org/~esr/faqs/smart-questions.html#urgent]How to Ask Questions the Smart Way:
    Don't flag your question as ?Urgent?, even if it is for you
    That's your problem, not ours. Claiming urgency is very likely to be counter-productive: most hackers will simply delete such messages as rude and selfish attempts to elicit immediate and special attention.
    There is one semi-exception. It can be worth mentioning if you're using the program in some high-profile place, one that the hackers will get excited about; in such a case, if you're under time pressure, and you say so politely, people may get interested enough to answer faster.
    This is a very risky thing to do, however, because the hackers' metric for what is exciting probably differ from yours. Posting from the International Space Station would qualify, for example, but posting on behalf of a feel-good charitable or political cause would almost certainly not. In fact, posting ?Urgent: Help me save the fuzzy baby seals!? will reliably get you shunned or flamed even by hackers who think fuzzy baby seals are important.
    If you find this mysterious, re-read the rest of this how-to repeatedly until you understand it before posting anything at all.
    Be precise and informative about your problem
    Describe the symptoms of your problem or bug carefully and clearly.
    Describe the environment in which it occurs (machine, OS, application, whatever). Provide your vendor's distribution and release level (e.g.: ?Fedora Core 1?, ?Slackware 9.1?, etc.).
    Describe the research you did to try and understand the problem before you asked the question.
    Describe the diagnostic steps you took to try and pin down the problem yourself before you asked the question.
    Describe any recent changes in your computer or software configuration that might be relevant.
    Do the best you can to anticipate the questions a hacker will ask, and to answer them in advance in your request for help.
    Simon Tatham has written an excellent essay entitled How to Report Bugs Effectively. I strongly recommend that you read it.
    Volume is not precision
    You need to be precise and informative. This end is not served by simply dumping huge volumes of code or data into a help request. If you have a large, complicated test case that is breaking a program, try to trim it and make it as small as possible.
    This is useful for at least three reasons. One: being seen to invest effort in simplifying the question makes it more likely that you'll get an answer, Two: simplifying the question makes it more likely you'll get a useful answer. Three: In the process of refining your bug report, you may develop a fix or workaround yourself
    And from [url http://www.thejword.com]The J Word:
    Code Tags
    When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read.

  • HELP URGENT:; Splitting strings in servlets

    hi ...
    I am trying to access the below servlet from another servlet in iplanet . I have to access a file and arrange the '|' delimited data in the file in a table format like in html ...
    I have used my own function inside the servlets which splits a string based on character ...But I always get
    Internal error: exception thrown from the servlet service function (uri=/servlet/ReportsDataServlet): java.lang.NullPointerException, Stack: java.lang.NullPointerException
    at ReportsDataServlet.split(ReportsDataServlet.java:82)
    at ReportsDataServlet.doPost(ReportsDataServlet.java:56)
    at ReportsDataServlet.doGet(ReportsDataServlet.java:14)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at com.iplanet.server.http.servlet.NSServletRunner.invokeServletService(NSServletRunner.java:919)
    at com.iplanet.server.http.servlet.NSServletRunner.Service(NSServletRunner.java:483)
    The sample code is shown below....I get the same error when i tries with stringokenizer as well....Pls help me fix this.....
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, Se
    rvletException
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    cont=getServletContext();
    out.println("<html><head><title>Reports Data</title></head><body bgcolor=DBD0E2>");
    String repType = request.getParameter("Rep");
    String mon = request.getParameter("month");
    String day = request.getParameter("day");
    String year = request.getParameter("year");
    String repName = repType+"."+mon+"-"+day+"-"+year+".txt";
    BufferedReader in = new BufferedReader( new FileReader("/home/lnayar/baais/xmlServlet/"+rep
    Name));
    String st;
    st = in.readLine();
    cont.log(st);
    int c =0;
    out.println("<table border=\"3\" cellpadding=\"0\" cellspacing=\"0\" width=\"800\"><tr><td>L
    ATA</td><td>WC CLLI</td><td>WC NAME</td><td>ADSL_LOCATION</td><td>ATM FLAG</td><td>ATM RELIEF DATE</td><t
    d>FRAME FLAG</td><td>FRAME RELIEF DATE</td><td>GOLD FLAG</td><td>GOLD RELIEF DATE</td><td>OVERLAY INDICAT
    OR</td><td>COUNT</td></tr>");
    while (st != null)
    c++;
    st = in.readLine();
    StringTokenizer stt = new StringTokenizer(st);
    out.println("<tr>");
    while (stt.hasMoreTokens())
    //out.println("<td>"+stt.nextToken("|")+"</td>");
    out.println("<td>hello</td>");
    out.println("</tr>");
    while (st != null)
    c++;
    st = in.readLine();
    out.println("<tr>");
    Enumeration en = split(st,"|");
    while(en.hasMoreElements())
    out.println("<td>"+en.nextElement()+"</td>");
    out.println("</tr>");
    cont.log("out while");
    out.println("</table>");
    out.println("</body></html>");
    public Enumeration split (String str, String delim)
    Vector v = new Vector();
    int pos_1;
    int pos_2;
    //Set initial delimiter positions...
    pos_1 = 0;
    pos_2 = 0;
    //Start chopping off bits from the string
    //until left boundary reaches the length of string
    while ( pos_1 <= str.length() )
    pos_2 = str.indexOf(delim, pos_1);
    if ( pos_2 < 0 )
    pos_2 = str.length();
    String sub = str.substring (pos_1, pos_2);
    pos_1 = pos_2 + 1;
    v.addElement(sub);
    return v.elements();
    d deeply appreciate if soeone could take a look at the code and tell me exactly where i am going wrong ..... Its URGENT ...
    Thx
    klv

    But there is the while statement which filters null
    values..Which is useless in your case, because you proceed to change the value of st to something else which you don't check for null.
    At any rate, what you have to do is this:
    1. Look at the stack trace to find the line number where the error occurs.
    2. Look at that line in your code.
    3. Look at each object variable in that line. Find out how it became null and fix that.

Maybe you are looking for

  • How can i remove my old photos

    how can i delete my old photos..

  • Indesign with CALS table

    Hi all, We are in process of automating XML indesign workflow. We need some input reg. the table handling in XML workflow. Which type of table is good CALS or Indesign Table. kavya

  • How can i get rid of "save keep"ads on macbookAir

         ads labelled "save Keep" appear on my screen.I can close them but they come when I am opening web sites.

  • XI JDBC Measurement

    Hi Experts, is there a possibility to measure JDBC-operations? e.g. i poll every 60 seconds with the jdbc-adapter, how much traffic is generated with this action? Im looking for a way to measure the traffic or the load of the XI. Thanks in advance Ch

  • Is anybody else having trouble downloading a Lost video

    I keep trying to download the 'what Kate did" dvideo from Lost and I keep getting a there was a downlaod error pop up. Does anybody else get this? Is it a problem with that video or me or my computer?