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

Resolve problems with implementing dynamic routes in Next.js

I have been learning about Next.js and I am struggling with understanding how to set up dynamic routing. I have the following setup: https://i.stack.imgur.com/uBPdm.png https://i.stack.imgur.com/YYSxn.png "use client" import React from "reac ...

Issues arising when attempting to replicate a fetch object into an undefined object in React.js

I'm facing an issue where I have defined a 'poke' object and when I try to clone an object into it, I only get a promise fulfilled with the object's link , instead of the actual object. Here's the code snippet: let poke = fetch(url ...

Enhancing interactivity: Implementing a ripple effect for Card clicks in Material UI

I'm curious if there's a method to incorporate a ripple effect into Material UI's Card component when it is clicked. Additionally, I am wondering if it is achievable to have the ripple effect display on top of the content within the Card co ...

Oops! An issue occurred at ./node_modules/web3-eth-contract/node_modules/web3-providers-http/lib/index.js:26:0 where a module cannot be located. The module in question is 'http'

I have been troubleshooting an issue with Next.js The error I am encountering => error - ./node_modules/web3-eth-contract/node_modules/web3-providers-http/lib/index.js:26:0 Module not found: Can't resolve 'http' Import trace for req ...

Is there a way to assign innerHTML values to table cells using PHP?

I'm currently building a website that relies on a database to store information. I have created an array to hold the values retrieved from the database, and now I need to populate a table with these values. Each cell in the table has a numerical ID ra ...

Ways to effectively hide one window or pop-up upon clicking another

I am working on creating an interactive website for my close circle of friends and family. One of the key features is to have a button that displays their biography when clicked. What I'm aiming for is that when a different bio is selected, the previo ...

Guide on downloading a PDF file with NodeJS and then transmitting it to the client

My goal is to download a PDF file using NodeJS and then send its data to the client to be embedded in the page. Below is the code snippet I am using to download the PDF file: exports.sendPdf = function(req, responce) { var donneRecu = req.body; va ...

What is the best way to add multiple lines of text to a webpage using the span element?

Currently, I am developing a game that involves using a map, which consists of multiple lines. My question is whether it is possible to have the span tag cover multiple lines while ensuring that each line ends with a new line character. Below is an exampl ...

Reactive form allows you to easily format dates

Currently, the date displayed is 1/4/2022. We need it to display in the format 01/04/2022. Can we achieve this formatting using reactive forms with the sample Model form provided below? Thank you. How can we format it when starting from transactionStartD ...

Strange behavior observed in the Datepicker, possibly linked to the blur event

I'm facing a challenge with the Datepicker feature. When I blur, the calendar disappears if the Datepicker was active, but the focus remains on the input field. As a result, I am unable to trigger the Datepicker again by clicking on the input field. T ...

What is the best way to eliminate the input range in a React date range picker?

Here is an image illustrating a date range picker: https://i.stack.imgur.com/pwKaI.png I am looking to remove the labels for days before today and starting from today in the date range picker. How can I achieve this? Below is my code snippet: class Better ...

Extracting data from web pages using JavaScript and PHP

Using the following script, I am able to scrape all the items from this specific page: $html = file_get_contents($list_url); $doc = new DOMDocument(); libxml_use_internal_errors(TRUE); if(!empty($html)) { $doc->loadHTML($html); ...

Creating specialized paths for API - URL handlers to manage nested resources

When working with two resources, employees and employee groups, I aim to create a structured URL format as follows: GET /employees List employees. GET /employees/123 Get employee 123. GET /employees/groups List employee groups. GET /employees/groups/123 ...

Effortlessly browse through directory with the seamless integration of AngularJS or

Hey there! I'm working on a really cool feature - creating a list with editable inputs. However, I've encountered a bit of an issue. Is there any way to navigate through this list using arrow keys and focus on the desired input? .content ul { ...

AngularJS: Unable to preserve the data

I'm currently working on an issue with saving updated functions using angularJS. I've managed to edit the data and update it on the database side, but the changes aren't reflecting on the frontend side unless I logout and login again. I need ...

Leveraging an external React library to utilize .ogg files for audio playback specifically in the Safari

Hey there! I'm currently working on incorporating ogg-opus audio playback in a react app on Safari (since it doesn't support .ogg format). My project was initialized using create-react-app. I came across the "ogv.js" library, which supposedly h ...

Having trouble accessing news feed with jQuery due to an unexpected token error when attempting to cross domains

I am attempting to access the Yahoo News feed from a SharePoint site, but it is causing a cross-domain access issue. Despite trying various solutions found on numerous websites and blogs, I still cannot resolve the problem. (I am executing this code in the ...

5 steps to create a versatile function for activating attributes based on their values

Hey everyone! I was working on creating this calculator and I had different options to implement it, but I wanted to do it in a specific way. <form action=""> <label for="num1">Number A</label><br> <input type="number" na ...

Error encountered while executing node server.js for Azure IoT Hub due to incorrect flags provided in the RegExp constructor

Currently, I am attempting to execute 'node server.js' in order to establish a connection between my Raspberry Pi device and Azure through the Azure IoT Hub. However, upon running the command 'node server.js', an error message is displa ...

Encountering an issue while attempting to assess a Meteor package within a local environment

Hello everyone! I'm a beginner in Meteor programming and currently following the online book discovermeteor.com. I recently came across a chapter that covers the creation of Meteor Packages. Excitedly, I proceeded to create my own package using the ...