Sending a jsp page for review at specified intervals

Using the setTimeout method, I attempted to achieve this. I passed a variable containing time as an argument, but the setTimeout method is only taking the initialized value of that variable and not the updated value fetched from the database.

Below is the code snippet:

  <html>  
        <head>  
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
            <title>Givetest</title>  

             <script type = "text/javascript">  
             function submitForm() {  
                 document.forms[0].submit();  
             }  
             </script>  

             <script language="JavaScript" src="http://scripts.hashemian.com/js/countdown.js"></script>  
        </head>  
        <%  
            String ts=request.getParameter("testname");  
            session.setAttribute("tname", ts);  
            Connection con=null;  
            Statement s1=null;  
            Statement s=null;  
            ResultSet r1=null;  
            ResultSet r=null;  
            int t=120000;  
            String time=null;  
            try  
            {  
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  
                con=DriverManager.getConnection("jdbc:odbc:online_testing");  
                s=con.createStatement();   
                s1=con.createStatement();          
                r=s.executeQuery("select * from "+ts+"");     
                r1=s1.executeQuery("select duration from tests where testname="+ts+"");    
                if(r1.next())  
                {  
                    time=r1.getString("duration");  
                    t=Integer.parseInt(time)*60000;  
logger.info(time);           
                } 
else {
   logger.info("No row found in db for test " + ts);
          System.out.println("No row found in db for test " + ts);
           out.println("<br>!! <b>No row found in db </b>for test " + ts + "<br><br><br>");         
}      
      r1.close();  
      }  
            catch(Exception e1)  
            {  
                response.setContentType("text/html");  
                out.println(e1.toString());  
            }  
        %>  
        <body onload="setTimeout('submitForm()',<%=t%>)">      

        <div class="header"></div>  
            <div class="view" style="color: #050505">  
                <form action="Givetest" method="post">   
                    <h1 align="center" style="color: #050505"><%=ts%></h1>  

                    <%  
                        int i=1;  
                        while(r.next()){  
                        String a = r.getString("question");  
                        String b = r.getString("option1");  
                        String c = r.getString("option2");  
                        String d = r.getString("option3");                                              
                        String e = r.getString("option4");                                                              
                    %>  
                    Question <%=i%>:- <label> <%=a%></label><br>  
                    <input type="radio" name="r<%=i%>" value="<%=b%>" checked><label><%=b%gt;</label><br>  
                    <input type="radio" name="r<%=i%>" value="<%=c%>"><label><%=c%gt;</label><br>  
                    <input type="radio" name="r<%=i%>" value="<%=d%>"><label><%=d%gt;</label><br>  
                    <input type="radio" name="r<%=i%>" value="<%=e%>"><label><%=e%gt;</label><br>  
    <br>  
                    <input type="hidden" name="h" value="<%=ts%>">  

                    <%  
                        i++;  
                        }  
                        r.close();  
                        s.close();  
                        con.close();  
                    %>  
                    <input type="submit" class="button">  
                </form>  
                </div>  
            <div class="copyright" align="center"> © YOUR NAME</div>  
        </body>  
    </html>

Answer №1

There is an error in the where clause that needs to be corrected as follows:

r1=s1.executeQuery("select duration from tests where testname="+ts+"");  

Additionally, this code should be run in servlets before being sent to jsp.

Answer №2

 <body onload="setTimeout('submitForm()',<%=t%>)">  

Is the value only given once? Does it really get the value from the database?

 int t=120000;

If so, are you sure no errors are being thrown?

By the way, writing a web app all in JSP is not the best approach. It's better to use servlets and POJOs/helper .java files for database operations. Make sure to clean Tomcat/app server's temp folders every time you restart to ensure the latest JSP is used.

In JSP, include a text like 'Version 001' and manually increase it to make sure the correct code version is running.


Use loggers or System.out.println if you don't have a logger.


    r1=s1.executeQuery("select duration from tests where testname="+ts+"");    
       //if should be enough as you will only have 0 or 1 row per test? 
       if(r1.next())  
        {  
            time=r1.getString("duration");  
            t=Integer.parseInt(time)*60000;           
        }  else{
           logger.warn("No row found in db for test " + ts);
           //okay for debug
           out.println("<br>!! <b>No row found in db </b>for test " + ts + "<br><br><br>");  
        }
        r1.close();  
    }  
    catch(Exception e1)  
    {  
        response.setContentType("text/html");  
        out.println("<br><br> <b> ERROR</b>" + e1.toString());  
    }  

SQL
testname="+ts+""

Using this directly in SQL statements is very risky and vulnerable to SQL injection attacks. Use prepared statements instead. Refer to OWASP https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Oops! The Route post function is missing some necessary callback functions, resulting in an undefined object error

I need to verify if a user has admin privileges. Every time I try calling the verifyAdminUser function from my router, I encounter the following error: Error: Route.post() requires callback functions but got a [object Undefined] at Route.(anonymous func ...

Experience some issues with the NextJS beta app router where the GET request fails when using fetch, but surprisingly works

Having an issue with a GET request while using NextJS with the APP dir... The function to getProjects from /project route.ts is not triggering properly. console.log("in GET /projects") is never triggered, resulting in an unexpected end of JSON ...

When using GTM dataLayer .push, a fresh object is generated rather than simply appending it to the current dataLayer

I am in the process of setting up a dataLayer for my website, but I have encountered an issue. My understanding is that Google Tag Manager dataLayer functions in a way where you have one central dataLayer object containing all the data variables. Each tim ...

Harnessing the Power of JSON Data Extraction with JavaScript

I stored the data in JSON format using the setItem method: localStorage.setItem('orderproduct', JSON.stringify([{imageSource: productImg, productTitle: title, productQuantity: qty, productPrice: finalprice}])); When I inspect it, this is how it ...

Having difficulties redirecting with the button's onclick function

I'm struggling to redirect users to another page using a button (assuming the hostname is localhost:8000) $('#getFruit').attr('onclick', window.location.host + '/getFruit/banana') <script src="https://cdnjs.cloudfl ...

The SQLite table successfully stores the initial record, but encounters issues when attempting to store subsequent

I recently set up a database and placed it in the asset folder. The table named orders consists of three columns: id, orderItems, and orderDate. I encountered an issue where converting the arraylist to a string for orderItems worked well for the first reco ...

Is there a way for me to discover the top trending photos on Instagram today?

Finding information on the Instagram API can be quite challenging due to poor documentation. Is there a method available to discover the most liked Instagram photos by location, such as identifying the top picture liked by Danish users today? Any insight ...

Confirmation checkbox that retains original value if canceled

Imagine a scenario where there is a checkbox value. When the checkbox value changes, the user is asked, "Do you want to SHOW this item on the website?" or "Do you want to HIDE this item on the website?" Everything seems to be working fine, except for one ...

What's the best way to integrate Bootstrap into my HTML document?

Hey there, I'm new to the coding world and just started learning. I could use some assistance with including Bootstrap v5.1 in my HTML code. The online course I'm taking is using an older version of Bootstrap, so I'm having trouble finding t ...

Issue with rendering HTML tags when replacing strings within Ionic 2 and Angular 2

I am currently working with an array of content in my JSON that includes URLs as plain text. My goal is to detect these text URLs and convert them into actual clickable links. However, I'm facing an issue where even though the URL is properly replaced ...

Good day extract a collection of articles

I am trying to parse out the date and full URL from articles. const cheerio = require('cheerio'); const request = require('request'); const resolveRelative = require('resolve-relative-url'); request('https://www.m ...

Is there a discrepancy in speed between Node.js http.get and Google Chrome's $.get function?

Recently, while experimenting with node.js, I decided to test out the following code snippet: var http = require("http"); function get() { var headers = { 'Accept-Encoding': 'gzip' }; var startedAt = new Date().get ...

Displaying Data in React Table from JavaScript Object

I'm working on a React component that will display a table of data from a JavaScript object called pixarMovies. The initial state is set with this object. My goal is to sort the movies chronologically by date and render them in a table format (refer t ...

To restore the position of the chosen object in Three.js after clicking reset

I am facing an issue with resetting the position of my latest Object in three.js. Initially, my code consists of the following: function onDocumentMouseDown( event ) { event.preventDefault(); var vector = new THREE.Vector3( mouse ...

Enhancing Animation Speed with jQuery

I've provided the code snippet at this link: http://jsfiddle.net/LnWRL/4/: Here is the HTML: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script> <div id="wrap_demo"> <div id="demo"></di ...

What is the best way to extract a specific object from an array containing multiple objects?

Upon entry, there is an array with various objects. A function is needed to convert this incoming array of objects into a single object. The goal is to bring it to the desired form using the function provided. var array = [ { k1:v1 }, { k2:v2 }, ...

Error encountered: Unable to connect to locking port - WebDriver version 2.22

I encountered an issue where my webdriver (2.22) could not bind to locking port 7054 within the specified 45000ms timeframe. Software Versions: Operating System: WinXP Firefox: 12 Webdriver: 2.22.0 Java: 1.6 Sit ...

most efficient method for organizing a collection of text phrases

Is there an optimal method for storing and accessing a lengthy string where each entry serves as an index for another array? Currently, my approach is: String indices = "1,4,6,19,22,54,....." This string contains hundreds of thousands of entries. I am c ...

Conceal the scroll bar while still allowing for scrolling functionality

In this code snippet, I am trying to maintain the scroll position of two blocks by syncing them together. Specifically, I want to hide the scrollbar of the left block while scrolling the right one. If anyone has any suggestions or solutions for achieving ...

FullCalendar, showcasing real-time event creation as you select dates

I am currently utilizing fullcalendar 4 on my website and I am attempting to incorporate an indicator for when a user selects a date on the calendar. While the background color changes, it's not very visible. My aim is to replicate the functionality ...