Use of Threads with JSP's

Can you use threads in a web application that uses JSP's plus Servlets and Beans ?
We have a JRUN 3.1 application using JSPs, Servlets and Beans. Shortly after we went live it became apparent that any 2 users using the same object experienced problems as one object was overwriting another. In a panic the problem was solved by whacking SYNCHRONISED on all objects.
Now we want to write another application, are there strategies for using Threads with JSPs?
Would this be part of the webserver configuration or would the application be coded in a certain way ?
Please can you give me a simplistic answer or point me to some documentation that gives a simple overview.
Thanks Steve

Hi,
You can use thread with jsp, i am sending u a example
package thread;
import java.io.Serializable;
public class TaskBean implements Runnable, Serializable {
private int counter;
private int sum;
private boolean started;
private boolean running;
private int sleep;
public TaskBean() {
counter = 0;
sum = 0;
started = false;
running = false;
sleep = 100;
protected void work() {
try {
Thread.sleep(sleep);
counter++;
sum += counter;
} catch (InterruptedException e) {
setRunning(false);
public synchronized int getPercent() {
return counter;
public synchronized boolean isStarted() {
return started;
public synchronized boolean isCompleted() {
return counter == 100;
public synchronized boolean isRunning() {
return running;
public synchronized void setRunning(boolean running) {
this.running = running;
if (running)
started = true;
public synchronized Object getResult() {
if (isCompleted())
return new Integer(sum);
else
return null;
public void run() {
try {
setRunning(true);
while (isRunning() && !isCompleted())
work();
} finally {
setRunning(false);
And JSP page start.jsp
<% session.removeAttribute("task"); %>
<jsp:useBean id="task" scope="session"
class="thread.TaskBean"/>
<% task.setRunning(true); %>
<% new Thread(task).start(); %>
<jsp:forward page="status.jsp"/>
///////////////// status .jsp
<jsp:useBean id="task" scope="session"
class="thread.TaskBean"/>
<HTML>
<HEAD>
<TITLE>JSP Progress Bar</TITLE>
<% if (task.isRunning()) { %>
<SCRIPT LANGUAGE="JavaScript">
setTimeout("location='status.jsp'", 1000);
</SCRIPT>
<% } %>
</HEAD>
<BODY>
<H1 ALIGN="CENTER">JSP Progress Bar</H1>
<H2 ALIGN="CENTER">
Result: <%= task.getResult() %><BR>
<% int percent = task.getPercent(); %>
<%= percent %>%
</H2>
<TABLE WIDTH="60%" ALIGN="CENTER"
BORDER=1 CELLPADDING=0 CELLSPACING=2>
<TR>
<% for (int i = 10; i <= percent; i += 10) { %>
<TD WIDTH="10%" BGCOLOR="#000080"> </TD>
<% } %>
<% for (int i = 100; i > percent; i -= 10) { %>
<TD WIDTH="10%"> </TD>
<% } %>
</TR>
</TABLE>
<TABLE WIDTH="100%" BORDER=0 CELLPADDING=0 CELLSPACING=0>
<TR>
<TD ALIGN="CENTER">
<% if (task.isRunning()) { %>
Running
<% } else { %>
<% if (task.isCompleted()) { %>
Completed
<% } else if (!task.isStarted()) { %>
Not Started
<% } else { %>
Stopped
<% } %>
<% } %>
</TD>
</TR>
<TR>
<TD ALIGN="CENTER">
<BR>
<% if (task.isRunning()) { %>
<FORM METHOD="GET" ACTION="stop.jsp">
<INPUT TYPE="SUBMIT" VALUE="Stop">
</FORM>
<% } else { %>
<FORM METHOD="GET" ACTION="start.jsp">
<INPUT TYPE="SUBMIT" VALUE="Start">
</FORM>
<% } %>
</TD>
</TR>
</TABLE>
</BODY>
</HTML>
////////////////////////////// stop.jsp
<jsp:useBean id="task" scope="session"
class="thread.TaskBean"/>
<% task.setRunning(false); %>
<jsp:forward page="status.jsp"/>
deploy it into ur server and run start.jsp
and see whatb happens

Similar Messages

  • Using java bean with jsp

    hello friends,
    i'm new to jsp. i want to create an html form that accepts username and a value from four radio buttons and display back the entered name and checked radio button's value using java bean.
    i use the <jsp:setProperty id="" property="*"> method. i don't know how to access the radio buttons value from the html.
    also when i use an additional field other than username the jsp page is showing error.
    Please give me the correct method to use java bean with jsp in this circumstance.
    thank you.

    thank you, but i have a problem left. the case is like this.
    i got the jsp and bean worked fine when i have a sinle input text field.
    but when i added a second text field i recieved the following error.
    javax.servlet.ServletException: basket.newbean.getUserPass()Ljava/lang/String;
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:825)
         org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:758)
         org.apache.jsp.newform.process_jsp._jspService(process_jsp.java:69)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    where userPass is the new form element. I have made the subsequent chanes in my bean program and jsp file.
    pls hlp.

  • Scope when using a JavaBean with JSP

    what is the meaning of this question .....?
    "Which of the following can not be used as the scope when using a JavaBean with JSP? "
    question 4
    site :http://java.sun.com/developer/Quizzes/jsptut/

    The question is clearly written. I don't see how you can be confused. But let's assume you are since you would not have posed the question.
    Dumbed-down:
    There are 4 scopes or areas of variable visibility in JavaServer Pages. Which of those can areas can not be used with JavaBeans?
    Does that help?

  • How to generate html-code using csv input with JSP or JAVA???

    Hello,
    I want to read out a .csv-file and generate html-code dynmically with JSP in an EP6 Application. The problem is, that the csv-file can’t be located or openend.
    BTW if every knows a good tutorial or weblog for this, please post the link.
    It’s located in a par-archive under:
    />dist>files
    I tried various methods, in the doContent mehtod or with JSP. Everytime same result.
    Here part of the code I tried in the doContent():
    public class CSV extends AbstractPortalComponent
        public void doContent(IPortalComponentRequest request, IPortalComponentResponse response)
            String strWRoot = request.getWebResourcePath();
            String contentCSV="", line="";
            String linesep = System.getProperty("line.separator");
            File fileLoadCSV = new File(strWRoot+"/files/ma_infosysteme.csv");
            boolean exCSV = fileLoadCSV.exists();
            boolean reCSV = fileLoadCSV.canRead();
            int a=0;
            if(exCSV&&reCSV){
                response.write("ok");
                try {
                  BufferedReader inputCSV = new BufferedReader(new FileReader(fileLoadCSV));
                  while((line=inputCSV.readLine())!=null){
                    contentCSV=contentCSVlinelinesep;
                    a++;
                  inputCSV.close(); 
                catch(IOException ioex){
                    System.out.println("Fehler");  
            else {
                response.write("not ok");
            response.write("<br>Wroot: "+strWRoot);
            response.write("<br>File: "+fileLoadCSV);
            response.write("<br>exists: "+exCSV);
            response.write("<br>read: "+reCSV);
            response.write("<br>Input: "+contentCSV);
    The Output is:
    not ok
    Wroot: /irj/portalapps/DHTML
    File: \irj\portalapps\DHTML\files\ma_infosysteme.csv
    exists: false
    read: false
    Input:
    So thanks to everyone who can give me a good hint.
    Bye.

    Without really looking too much into this it looks like the problem is with the way in which you are trying to open the file. I believe that when creating a File object you need to use a physical path. By using the getWebResourcePath() method you are retrieving the URL to this file and not the physical path name. There is another method (can't remember the exact name) called getPublicResourcePath() (or something similar) which will return the physical path to this file, i.e. c:\usr\sap\.....etc. If you try it this way it may well work
    I hope this helps
    D

  • Interpretation of the use of threads with Sessions in the JMS Specification

    Hello,
    I’ve been interacting with two JMS Providers which do a different interpretation of the JMS Specification with the use of different threads for accessing to a session and session’s related objects.
    The question is:
    When a client is consuming messages asynchronously, is it possible to access session’s related objects from a thread different to the one dedicated to the asynchronous consumption, on (thread of control)?
    -     Never?
    -     Yes, but the client should provide explicit synchronization.?
    Our execution scenario is:
    1.- Messages are consumed asynchronously from a dedicated thread.
    2.- From other thread, messages consumed are acknowledged.
    In the JMS specification there is, at least, two parts where this issue is treated:
    1.- The first one (4.4.1 - page 60):
    +“There are no restrictions on the number of threads that can use a Session object or those it creates. The restriction is that the resources of a Session should not be used concurrently by multiple threads. It is up to the user to insure that this concurrency restriction is met. The simplest way to do this is to use one thread. In the case of asynchronous delivery, use one thread for setup in stopped mode and then start asynchronous delivery. In more complex cases the user must provide explicit synchronization.”+
    This extract, makes me think that it is possible the access from different threads, but If I do that, I should provide explicit synchronization.
    2.- The second one (4.4.6 – page 62,63)
    +"Once a connection has been started, any session with a registered message listener(s) is dedicated to the thread of control that delivers messages to it. It is erroneous for client code to use this session or any of its constituent objects from another thread of control. The only exception to this is the use of the session or connection close method"?+
    This extract, could be interpreted as that the concurrent access is never allowed in the described situation.

    I think the key words are in 4.4.6 (and also the javadoc for Session): "Once a connection has been started, any session with a registered message listener(s) is dedicated to the thread of control that delivers messages to it".
    My interpretation of this is that you when you register a message listener and call connection.start(), the thread which delivers messages to the listener should be thought of as "using the resources of the session" (as mentioned in 4.4.1) continuously until the connection is stopped (or until the session or connection is closed). it doesn't matter whether the session is executing onMessage() or not.
    Given this, both 4.4.1 and 4.4.6 say the same thing: that once you have registered and started a message listener, the only thing you can do to the session from another thread is to close it.
    I agree the spec could be clearer. In particular the words "In more complex cases the user must provide explicit synchronization" in 4.4.6 should be clarified to state what this actually means rather than give a hint.
    Please note that work has just started on updating the JMS specification, so now is a great time to report areas of the JMS spec which would benefit from clarification. If you'd like this to be considered for clarification, please report it in the official JSR 343 issue tracker at http://jms-spec.java.net
    Nigel

  • Using java files with JSP

    Ok, so im pretty new to this JSP lark and have a question.
    I have Java Classes resting in .java files, i need to know how
    do i link these files to my .jsp page so that the classes/variable etc.
    declared with the java files are recognised when they are come
    across in the .jsp file.
    I dont know if I have explained that properly.

    Just include this statement at the top of your jsp:
    <%@page import="yourpackage.yourclass"%>
    The .java files should of course be compiled into .class files prior to using (and you don't include the extension when importing).

  • Problem using JDBC driver with JSP

    Hi, I am trying to connecto to my mysql server via a JSP page, but it seems that there is a problem with the driver call or something in my configuration that unables me to connect. I have the mysql-connector-java-3.0.7-stable driver.
    This is how my classpath looks like:
    CLASSPATH=/home/hooper/Sources/mysql-connector-java-4.0.7-stable/lib:/home/hooper/Sources/mysql-connector-java-3.0.7-stable/com:/home/hooper/Sources/mysql-connector-java-3.0.7-stable/mysql-connector-java-3.0.7-stable-bin.jar:/usr/java/j2sdk1.4.1_02:.:/usr/java/j2sdk1.4.1_02/lib/tools.jar:/usr/java/j2sdk1.4.1_02
    And this is my JSP page code:
    <%@ page language="java" import= "java.sql.*"%>
    <%
    Connection con = null;
         String userName = "hooper";
         String password = ""; //No password
         String url = "jdbc:mysql://localhost/test";
         //Load the Driver class file
         Class.forName("com.mysql.jdbc.Driver");
         //Make a connection to the MySQL database
         con = DriverManager.getConnection (url, userName, password);
         out.println ("Database connection established");
              if (con != null){
                   //Close the connection
                   con.close();
    %>
    And this is the error I get from Tomcat4.1.18:
    HTTP Status 500 -
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: com.mysql.jdbc.Driver
    root cause
    javax.servlet.ServletException: com.mysql.jdbc.Driver
    I hope someone can help me with this.
    Thanks,
    Luis

    Hi..
    Try using this way
    String userName = "hooper";
    String password = ""; //No password
    String url = "jdbc:mysql://localhost:3306/test";
    Class.forName("org.gjt.mm.mysql.Driver");
    try to download the driver for mysql and add it to your classpath
    Hope this works
    Regd
    Vasi

  • Using boost::thread with Sun Studio C++ gives error

    Hi,
    I'm trying to compile a code which uses the boost thread library, but I get the following error:
    CC -library=stlport4 -features=tmplife -features=tmplrefstatic -mt -c -o t t.cpp
    "/opt/boost/include/boost/thread/pthread/mutex.hpp", line 142: Error: The function "pthread_mutex_timedlock" must have a prototype.
    "/opt/boost/include/boost/thread/pthread/mutex.hpp", line 142: Error: The function "pthread_mutex_timedlock" must have a prototype.
    "/opt/boost/include/boost/thread/detail/thread.hpp", line 344: Error: boost::thread::thread(boost::thread&) is not accessible from boost::move(boost::detail::thread_move_t<boost::thread>).
    "/opt/boost/include/boost/thread/pthread/recursive_mutex.hpp", line 179: Error: The function "pthread_mutex_timedlock" must have a prototype.
    "/opt/boost/include/boost/thread/pthread/recursive_mutex.hpp", line 179: Error: The function "pthread_mutex_timedlock" must have a prototype.
    5 Error(s) detected.
    make: *** [t] Error 5the sample source code in question here just a single include:
    #include <boost/thread.hpp>This is with boost 1.40.0. I wonder what I'm doing wrong..
    Akos

    OK, I tried latest version of CC from Sun Studio 12 update 1 and can say that
    - the error about constructor not being accessible is Sun C++ compiler "feature" (only called feature because it existed for so long) that allows binding of rvalues to non-const references; this "feature" will probably be turned off in the next release. It can't be changed in a patch because client's code might rely on it.
    - the other errors are also not Boost-specific: the result of incompatibility of Linux headers and Sun C++ compiler; more thorough investigation is due, but in the past we had several problems like this. This particular can be solved by adding
    -D_GNU_SOURCE to compile line.

  • Problem in using java bean with jsp

    Hi,
    This is my code and i get this error. Not able to trace the mistake.
    bean.html
    <html>
    <head>
    <meta http-equiv="Content-Language" content="en-us">
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>Fname</title>
    </head>
    <body>
    <form method="POST" action="http://localhost:8080/beanjsp.jsp">
         <p>Fname: <input type="text" name="T1" size="20"></p>
         <p>Lname: <input type="text" name="T2" size="20"></p>
         <p> </p>
         <p> </p>
         <p><input type="submit" value="Submit" name="B1"><input type="reset" value="Reset" name="B2"></p>
    </form>
    </body>
    </html>
    beanjsp.jsp
    <jsp:useBean id="bean" class="beans.FirstBean" scope="application" />
    <jsp:setProperty name="bean" property="fname" param="T1" />
    <jsp:setProperty name="bean" property="lname" param="T2" />
    THE FIRST NAME IS <%=bean.getFname() %>
    THE LAST NAME IS <%=bean.getLname() %>
    FirstBean.java
    //CREATING A BEAN
    package beans;
    import java.io.*;
    public class FirstBean
         private String fname;
         private String lname;
         FirstBean()
              fname="";
              lname="";
         public void setFname(String fn)
              fname=fn;
         public void setLname(String ln)
              lname=ln;
         public String getFname()
              return fname;
    public String getLname()
              return lname;
    error report
    org.apache.jasper.JasperException: /beanjsp.jsp(2,0) The value for the useBean class attribute beans.FirstBean is invalid.
         org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:39)
         org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:405)
         org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:146)
         org.apache.jasper.compiler.Generator$GenerateVisitor.visit(Generator.java:1223)
         org.apache.jasper.compiler.Node$UseBean.accept(Node.java:1116)
         org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2163)
         org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2213)
         org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2219)
         org.apache.jasper.compiler.Node$Root.accept(Node.java:456)
         org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2163)
         org.apache.jasper.compiler.Generator.generate(Generator.java:3270)
         org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:189)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:286)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:267)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:255)
         org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:556)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:293)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)I have placed the beans package folder containing FirstBean.class inside classes folder of ROOT directory.
    I don't know what s wrong with my code :( ... Plz help asap.
    Thanks,
    Akshatha

    I have placed the beans package folder containing FirstBean.class >inside classes folder of ROOT directory.Place it in the WEB-INF/classes folder
    ram.

  • Using RDBMS Realm with JSP, again

    I submitted this post using the web interface after I "asked Bea" and now it
    seems like I'm a total newbie :) So I repost to make it more readable..
    Hi,
    I am fairly new to J2EE and I am trying to figure out how I can apply the
    RDMSRealm to restrict access to jsp files
    Do I use ACL's in the database to restrict access to jsp's or,
    Do I use the web.xml deployment descriptor in the a similar fashion as the
    Gold_customer in the petstore,
    What is the difference?
    Does anyone know about a nice example?
    Sincerely,
    ilya

    We have used the <security-constraint> tags in web.xml. This tag specifies which
    'security roles' has access to specific resource collection (e.g. one or more
    servlets or JSPs). The 'security roles' are then mapped in weblogic.xml to one
    ore more groups and/or users as defined in the group and user tables in the RDBMS.
    regards,
    Simen R.
    "ilya" <[email protected]> wrote:
    I submitted this post using the web interface after I "asked Bea" and
    now it
    seems like I'm a total newbie :) So I repost to make it more readable..
    Hi,
    I am fairly new to J2EE and I am trying to figure out how I can apply
    the
    RDMSRealm to restrict access to jsp files
    Do I use ACL's in the database to restrict access to jsp's or,
    Do I use the web.xml deployment descriptor in the a similar fashion as
    the
    Gold_customer in the petstore,
    What is the difference?
    Does anyone know about a nice example?
    Sincerely,
    ilya

  • Using owa_cookie.send with JSPs

    Hello all... I have a procedure that I use owa_cookie.send to send a cookie in the HTTP header. How do I get it from a JSP now? If I include this cookie in my xxx.home procedure, do I need to do anything special to be able to get it when I navigate to my JSP?
    Thank you all in advance.
    Jonathan Coreil

    -- GET_ALL returns an array of name/value pairs of all HTTP_COOKIES
    -- sent from the browser. The name/value pairs appear in the order
    -- that they were sent from the browser.
    PROCEDURE owa_cookie.get_all
    (names OUT vc_arr,
    vals OUT vc_arr,
    num_vals OUT INTEGER);
    the number of vals is > 0 if the cookie is stored at the clients side. I implement it just.
    I quest the number of cookies
    if l_NumVals = 0 then
    Send cookie;
    redirect_URL('...');
    else
    get_Cookie_Content;
    end if;
    It may not help you. Please specify your problem if possible.
    Regards Torsten

  • How Use Multi Pages with JSP pages

    I have a lot of records, so i want to display from 10 to 10 and use a numeric menu in the botton of the page. the problem is how a make that with java code and html or java script.
    thanks for your help
    LeonMex. from M�xico City

    Search for pager taglibs. Ur solution lies there.
    Moreover u can refer www.jsptags.com , I am using the pager taglib from jsptags and it's quite easy to use.
    Hope that Helps.
    thanks and regards.

  • How to use threads in JSP???

    hello
    i want to use threads with JSP.
    i want to write a jsp page which will
    start 2 different threads. the 1st thread should just display a message and the second page should redirect this page to another jsp page.
    till the redirection is goin on, the message should be displayed in the browser from the 1st thread.
    i dont know actually how to use threads in JSP by implementing the Runnable insterface, if not m then how do i do it ??
    thanx
    Kamal Jai

    Why do you want to use threads to do this ??
    If you write a message and do a redirection, the message will be displayed until the other page will be loaded into the browser...
    I already launched a thread from a JSP but it was for a four hour process where the user can close his browser windows.

  • What RAD tool should i use with JSP??

    I would like to know what RAD (opensource) to use to work with JSP and MySQL.
    If anyone could help
    thank you

    If you are using the Sun Java System Enterprise Studio, the Web Application Framework will provide you with all the tools you need to create a JSP/Servlet based web application that scales in performance like no other framework. Coupled with a WYSIWYG HTML editor like Dreamweaver and your RAD app dev is covered.
    For MySQL, there are some really nice GuI clients out there. This is a link to the one I have used:
    http://www.mysql.com/products/
    If you are using the Sun Java Studio, don't forget to add the MySQL jdbc driver so that you can access your DB at development time and use the Sql Model wizards from within the Web Application Framework tools.
    If your app is not concerned with serious scalability, and you are looking to build your app using the latest standards (JSF - Java Server Faces), you can download the Sun Java Studio Creator. It's more of a VB.NET/ASP like development environment with a WYSIWYG HTML form painter. Very slick. You can download here:
    http://developers.sun.com/prodtech/javatools/jscreator/index.jsp
    Here's a primer for Creator:
    http://developers.sun.com/prodtech/javatools/jscreator/reference/techart/primer.html
    The Creator forum is here:
    http://swforum.sun.com/jive/forum.jspa?forumID=123
    To recap, use Web Application Framework if you require the utmost in a mature, stable, and scalable web application. WAF apps can be deployed to any J2EE server.
    If you require a webapp based on the latest standard JSF implementation, and dev productivity is more important than enterprise strength scalability, then Creator is a great choice.
    cheers
    craig

  • Using a package in JSP

    Hi,
    I've been learning java at Uni using the Elements Package. I've started learning JSP on my own and was wondering if i can use the package with JSP. For example if i wanted to use this code
    import element.*;
    import java.awt.Color;
    public class test
    public static void main(String args[])
         DrawingWindow d = new DrawingWindow();
         ConsoleWindow q = new ConsoleWindow();
    is it possible?

    You cannot have a main() method in a JSP. The JSP will be compiled (behind the scenes) by your J2EE container (Tomcat, Weblogic, JBoss, etc.) into a Servlet. As such, you have access in your JSP to the HttpServletRequest and HttpServletResponse, as well as the HttpSession, the Servlet OutputStream, and a few other Servlet variables. You write normal Java code within the JSP (or use a JSTL tag lib) between <% and %> blocks. You can import any package in your JSP that is in the web application's classpath.
    - Saish

Maybe you are looking for