Javascript function not getting called when clicking the Button

I’m writing a Perl script to do a POST request when clicking a button. It’s a monolith code, using html and javascript with Perl. On clicking the button, the ‘onclick’ functionality is not somehow triggering the function ‘PostRequest’. But when I am using a reference link with ‘onclick’ instead, that seems to be working fine.

$html .= CreateJiraLink();

sub Jira {
    my $args = $_;
    # This will be given from JiraInformation
    my $namedID = 'some value;
    my $teamname = 'some value';
    my $jiraname = 'some value';
    my $jiradescription = 'some value';

    my $requestData = {
                    operation => 'create',
                    named_sql_id => $namedID,
                    team_name => $teamname,
                    jira_name => $jiraname,
                    jira_description => $jiradescription
                    };
    my $requestDataJSON = JSON::encode_json($requestData);  # Encode the requestData as JSON
    # print('********* Inside CreateJira *********');
    # print ('$requestDataJSON');
    my $html = Unindent(qq|
    <script>
        function PostRequest() {
            $.ajax({
                type: 'POST',
                url: 'some url',
                data: $requestDataJSON,
                cache: false,
                success: function(response) {
                    console.log('AJAX request successful.');
                    console.log(response);
                    // Handle the response data here
                },
                error: function(xhr, status, error) {
                    console.error('AJAX request error.');
                    console.log(xhr.responseText);
                    console.log(status);
                    console.log(error);
                    // Handle the error here
                }
            });
        }
    </script>
    |);
    $html .= qq{<td> <button id="jirabutton" onclick="return PostRequest()">Create JIRA task</button>};
    return $html;
}

Dynamically Create Span Around Each Word using JavaScript

I am looking to create a function in JavaScript which will create a <span> element around each word of any (realistically most) website. This is part of the content script of a browser extension, so I am not able to make changes to the HTML, as it should work with whatever website the user loads into the browser. The goal is to be able to label each span with an index using an id tag. In other words, I can write code that just goes in and says “I want to change the CSS of word number 54 on the current site”, and it can go in and select the span element with id=54 and run some code to change it (or something along those lines).

Below is the recursive function I currently have. (the yellow highlighting via CSS is just so I can see where the span elements are, and will be removed in the future). I also intend to add functionality where it will make the id differently if the integer id it’s trying to use is already in use on the site. This mostly works, except it causes some undesired visual changes on some sites. On many sites it seems to make all the text slightly “larger” and more spread out, and on some sites it messes with the CSS in an undesirable way. For example, on the results of a DuckDuckGo search with dark mode on, it will remove the dark background and replace it with a white one, but will not change the color of the text, making the text very hard to see.

let initidx = 0;

function run_element(element, parent)
{
    if(element.nodeType == Node.ELEMENT_NODE)
    {
        let childList = [];
        for(let child of element.childNodes) //probably a better way to copy the list of children before it gets modified.
        {
            childList.push(child);
        }
        for(let child of childList)
        {
            run_element(child, element);
        }
    }
    else if(element.nodeType == Node.TEXT_NODE)
    {
        for(let word of element.nodeValue.split(" "))
        {
            if(word != "" && word != "n")
            {
                let span = document.createElement('span');
                span.appendChild(document.createTextNode(word));
                span.id = initidx.toString();
                span.style = "background:yellow;"
                initidx++;
                parent.insertBefore(document.createTextNode('xa0'), element);
                parent.insertBefore(span, element);
            }
        }
        parent.removeChild(element);
    }
}

run_element(document.body, null);

Is there any way I could improve this method of “indexing” the words (where a word is just defined by using split(" ")) in the site? I am not very experienced with web development, and I have never made a browser extension before. Thanks!

CORs error when switching between www and non-www url even though my origins are listed in my Google Cloud Bucket’s CORs origin array

I have an application on Google App Engine with a public storage bucket that has the following CORs settings

[{"maxAgeSeconds": 3600, "method": ["GET", "HEAD"], "origin": ["https://[app-name].appspot.com/", "https://subdomain.domain.com/", "https://www.subdomain.domain.com/"], "responseHeader": ["Content-Type"]}]

Everything works as expected when visiting these URL’s separately, BUT if I visit https://www.subdomain.domain.com/, then I visit my site at https://subdomain.domain.com/ (without clearing cache), I get CORs errors for all previously fetched assets from the bucket…

Access to fetch at 'https://[CDN_URL]/[ASSET_PATH]/image.jpg' from origin 'https://www.subdomain.domain.com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'https://subdomain.domain.com' that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

If I clear my cache and visit https://subdomain.domain.com/, no CORs errors.

In the scenario that’s giving me errors, I’m wondering why it is listing my origin as ‘https://www.subdomain.domain.com’ when I’ve visited at ‘https://subdomain.domain.com’. And also, why is there a CORs error when the bucket has both www and non-www urls in the origin array?

Can I solve this issue within the CORs config for the bucket or is there something else at play here?

FWIW, I’m using a SvelteKit framework for this application.

Thanks!

React-Leaflet v4 with Next.js 13 Invalid hook call

I expirence an issue after updating my Next.js version from 12 to 13 – that also means I updated React from 17 to 18 and react-leaflet from 3 to 4. I have this component:
`

function ChangeView({ center }) {
    const map = useMap();
    map.setView(center);
    return null;
}
const createClusterCustomIcon = function (cluster) {
    return L.divIcon({
    html: `<span>${cluster.getChildCount()}</span>`,
    className: `${styles.markerClusterCustom}`,
    iconSize: L.point(40, 40, true),
  });
};

 const RegularMap = ({ center, organizations, cat, org, orgIcon }) => {
const [organization, setOrganization] = useState();
if(center[0] || center [1] !== null  && center.length > 0 ){
    return (
        <MapContainer center={center} zoom={6} className={styles.mapContainer} scrollWheelZoom={true}
                      style={organizations ? {height: 600, width: "100%"} : {height: 400, width: "100%"}} >
            <ChangeView center={center} />
            <TileLayer
                attribution="© <a href='https://www.mapbox.com/about/maps/'>Mapbox</a> © <a href='http://www.openstreetmap.org/copyright'>OpenStreetMap</a> <strong><a href='https://www.mapbox.com/map-feedback/' target='_blank'>Improve this map</a></strong>"
                url="https://api.mapbox.com/styles/v1/freala/ckqtm5ajl6cxr19n2r67a821q/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoiZnJlYWxhIiwiYSI6ImNrcXRtZHR4djA4Nmkyd3F1ZmM2eHBiYnoifQ.uKDqGDSzf88It8iCuX6fJg"
            />
            {org ? <Marker icon={orgIcon ? icon({
                iconUrl: orgIcon,
                iconSize: [32, 32],
            }) : ICON} position={center}> </Marker> : <Marker icon={ICON} position={center}> </Marker>}
            <MarkerClusterGroup  showCoverageOnHover={false}
                                 spiderfyDistanceMultiplier={2} iconCreateFunction={createClusterCustomIcon}>
            {organizations && organizations.length > 0 ? (
                <>
                    {organizations.map( o => {
                        if(o.latitude && o.longitude){
                            let id = o.id;
                            return(
                                <Marker key={o.id} icon={o.icon ? icon({
                                    iconUrl: o.icon.url,
                                    iconSize: [32, 32],
                                }) : ICON} position={[o.latitude, o.longitude]}
                                       >
                                        <Popup>
                                            <h2 className={styles.popupH2}>{o.name}</h2>
                                            <div style={{width:'100%',display:'flex',justifyContent:'center',margin:'5px 0'}}>
                                                <Link href={{ pathname: o.is_organization ? "/organization" : "/location", query: { id: o.id } }}>
                                                    <a  className="details-org">Szczegóły</a>
                                                </Link>
                                                <style jsx>
                                                    {
                                                        `
                                                          .details-org{
                                                            padding:10px 20px;
                                                            background-color:#517c92;
                                                            color:white !important;
                                                            border-radius:5px;
                                                            text-decoration:none;
                                                          }
                                                          .details-org:hover{
                                                            color:white !important;
                                                          }
                                                        `
                                                    }
                                                </style>
                                            </div>
                                        </Popup>
                                </Marker>
                            )
                        }
                    })}
                </>
            ) : null}
            </MarkerClusterGroup>
        </MapContainer>
    )
} else return null
};

Here are my depencendcies:
"dependencies": { "@changey/react-leaflet-markercluster": "^4.0.0-rc1", "@fortawesome/fontawesome-svg-core": "^1.2.36", "@fortawesome/free-brands-svg-icons": "^5.15.4", "@fortawesome/free-solid-svg-icons": "^5.15.4", "@fortawesome/react-fontawesome": "^0.1.16", "ally.js": "^1.4.1", "bootstrap": "^5.1.3", "easy-peasy": "^5.0.4", "i18next": "^21.5.2", "i18next-browser-languagedetector": "^6.1.2", "i18next-http-backend": "^1.3.1", "leaflet": "^1.9.4", "leaflet-defaulticon-compatibility": "^0.1.1", "leaflet-map-server-component": "^0.2.0", "leaflet.markercluster": "^1.5.3", "moment": "^2.29.4", "next": "^13.4.8", "next-share": "^0.22.1", "nprogress": "^0.2.0", "react": "^18.2.0", "react-audio-player": "^0.17.0", "react-bootstrap": "^2.1.2", "react-calendar": "^3.7.0", "react-confirm-alert": "^2.8.0", "react-datepicker": "^4.15.0", "react-dom": "^18.2.0", "react-hook-form": "^7.29.0", "react-i18next": "^11.14.2", "react-leaflet": "^3.2.5", "react-leaflet-markercluster": "^3.0.0-rc1", "react-player": "^2.9.0", "react-select": "^5.3.2", "react-slick": "^0.29.0", "sass": "^1.43.4", "sharp": "^0.32.1", "slick-carousel": "^1.8.1", "swr": "^2.2.0" }

I tried downgrading the leaflet back to v3 but that just breaks too since it’s not compatible with React v18. I can’t seem to find anyone who has fixed this problem and when I find someone then it’s a different problem that has nothing to do with the version updates and is at least 2 years old. Before the update everything seemed to work just fine.

MongoDB node.js driver not running nor connecting to mongoDB server port 27017

Taking a tutorial on MongoDB so i am trying to work with the mongoDB driver. I use hyper terminal as my command line. I run “mongod” to start the mongoDB server then node app.js to run my app.js. At a point, i don’t i dont get any response, eithger error nor succesfull, the terminal just remains static, then at a point when i run node app.js it logs “server running on port 3000” of which i dont have an app.listen anywhere in my app.js.

Here is my app.js file;

enter image description hereenter image description here

Below is my “mongod” command and logs
enter image description here

Here is when i ran my app.js file with the static response;
enter image description here

I expect to get a response like “connected successfully to server” “inserted 3 documents into the collection”

let me also share the “mongo” terminal

enter image description here

The fruitDB database wasn’t created.

How do i troubleshoot this and achieve my aim here? Thanks

How do I create a console chatbot with automated responses and sessions using Node.Js

How do I create a console chatbot with automated responses and sessions using Node.Js? For example:
Me: Hi
Bot: Good day. Select 1 to start
Me: 1
Bot: Enter Your Name (Step 1)
Me: Accuman
Bot: Enter your gender…

NB: In the event that my response is delayed. The bot should start again from step 1.

I have working simple code with a bunch of flow control statements (if statements)

let stage=0;
let msg="";

//Prompt user to get msg

if(msg==hi && stage==0){
   console.log("Select 1 to start");
   stage=1;
}else if(msg && stage==1){
   Console.log("Enter name:");
}
// And the list goes on
// How do i use session to terminate process if user message is delayed

Reset scale to 1:1 after zoom

I wish to reset the image to its original zoom factor upon a button onclick() event.

It is the code for the onclick() event that I need.

I have the following div in my HTML:

div id="zoom">
    <img src="assets/img/map2.png" width="600" height="auto" alt="zoom">
</div>

And the following javascript allows for zoom-in, zoom-out, and click-and-drag.

<script>
 var scale = 1,
        panning = false,
        pointX = 0,
        pointY = 0,
        start = { x: 0, y: 0 },
        zoom = document.getElementById("zoom");

      function setTransform() {
        zoom.style.transform = "translate(" + pointX + "px, " + pointY + "px) scale(" + scale + ")";
      }

      zoom.onmousedown = function (e) {
        e.preventDefault();
        start = { x: e.clientX - pointX, y: e.clientY - pointY };
        panning = true;
      }

      zoom.onmouseup = function (e) {
        panning = false;
      }

      zoom.onmousemove = function (e) {
        e.preventDefault();
        if (!panning) {
          return;
        }
        pointX = (e.clientX - start.x);
        pointY = (e.clientY - start.y);
        setTransform();
      }

      zoom.onwheel = function (e) {
        e.preventDefault();
        var xs = (e.clientX - pointX) / scale,
          ys = (e.clientY - pointY) / scale,
          delta = (e.wheelDelta ? e.wheelDelta : -e.deltaY);
        (delta > 0) ? (scale *= 1.2) : (scale /= 1.2);
        pointX = e.clientX - xs * scale;
        pointY = e.clientY - ys * scale;

        setTransform();
      }
      </script>

How can I reset the image to its original size, and re-center it, such as when the page loads initially?

Thank you.

How to create a self signed ssl certificate for a server that uses websockets

I can’t find (or don’t understand) how to create an ssl certificate for a server using websockets and how to apply this certificate to Windows so that it recognizes it.

Thank you for your help.

I have already tried with various tutorials but I always come to the same conclusion being that the server starts with the correct configuration of the ssl generate but I have never managed to connect to it with my site.

Parallax on JS & TailwindCSS

<main class="bg-gradient-to-r from-black via-cyan to-black">
        <!--BACKDROP-->
        <section id="Home" class="h-screen">
            <h1 class=" hidden md:flex justify-center items-center z-20 absolute top-24 left-1/2 transform -translate-x-1/2 font-extrabold text-6xl text-center">John Doe</h1>
            <h2 style="top: 170px" class="z-20 absolute left-1/2 transform -translate-x-1/2 font-light text-2xl md:text-5xl text-center ">Lorem Ipsum</h2>
            <img class="absolute h-full w-full object-cover top-0 left-0 z-0" src="images/backdrop1.png" alt="bg">
            <img class="absolute h-full w-full object-cover top-0 left-0 z-10" src="images/sky1.png" alt="fg">
        </section>
window.addEventListener("DOMContentLoaded", (event) => {
    const navigation = document.querySelector("#navigation");
    //   let logo = document.querySelector('.logo');
    //   let Name = document.getElementById('Name');
    //   let mainHeader = document.getElementById('main-header');
    //   let HomeSection = document.querySelector('.Home');
  
    window.addEventListener("scroll", () => {
      let value = window.scrollY;
  
      if (value > 0) {
        navigation.style.backgroundColor = "#000000e9";
      } else {
        navigation.style.backgroundColor = "transparent";
      }
  
      if (value <= HomeSection.offsetHeight) {
        Name.style.marginTop = value * 2.5 + "px";
      }
  
      if (value > HomeSection.offsetHeight) {
        logo.style.fontSize = "1.5em";
      } else {
        logo.style.fontSize = "1em";
      }
    });
  });
  
  window.addEventListener("beforeunload", () => {
    window.scrollTo(0, 0);
  });

I am trying to use the parallax effect only on h1 and h2 class while scrolling, keeping these two classes above the sky1.png image and behind the backdrop1.png.

The server does not support SSL connections node-postgres

I am trying to establish a connection with my local postgres database and use express to do api endpoints. I’m not sure why I am getting this error.

//db.js

const { Pool } = require("pg");
const pg = require("pg");

require("dotenv").config(); //get credentials

pg.defaults.ssl = true;

const connectionString = process.env.NODE_ENV === "production"
  ? process.env.DATABASE_URL
  : `postgresql://${process.env.PG_USER}:${process.env.PG_PASS}@${process.env.PG_HOST}:${process.env.PG_PORT}/${process.env.PG_DATABASE}`;

const conn = new Pool({ 
  connectionString: connectionString,
  ssl: { rejectUnauthorized: false }
});

module.exports = conn;
//index.js

const express = require('express');
const app = express();
const pool = require("./db"); //stores super secret db info
const cors = require("cors");

const PORT = process.env.PORT || 5500;

app.use(cors());
app.use(express.json()); // => req.body
app.use(express.static('public'));

app.get("/apiv1/:tier", async (req, res) => {
    try {
        const { date, tier } = req.params;
        const allData = await pool.query(
            "SELECT * FROM previous WHERE tier=$1 ORDER BY DESC LIMIT 25;", 
            [tier]
            );
        const results = allData.rows;
        console.log(results)
        // const output = { "data": Object.fromEntries(
        //     results.map(
        //         item => [item.pokemon, item]
        //         ))
        //     };
        // res.json(output);
    } catch (error) {
        console.log(error.message);
    };
});

app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}.`);
});

My credentials are valid, and my landing page loads, but when I try to go to localhost:5500/apiv1/anything, I get an error page and the message The server does not support SSL connections in my console, but I have taken the steps to allow for SSL connections.

Extends mongoose schema with methods – typescript compatible way

I found that the way mongoose suggest to add additional methods to a schema – is not compatible with the typeScript:

import * as m from 'mongoose'

const MySchema = new m.Schema({ deletedAt: Date  });

MySchema.methods.myDelete = function() { this.deletedAt = new Date(); }
MySchema.method('myUndelete', function() { this.deletedAt = null; });


const MyModel = m.model('MyCollection', MySchema);

let myInstance = new MyModel();
myInstance.myDelete();
myInstance.myUndelete();

the typescript compiler says

error TS2339: Property ‘myDelete’ does not exist on type ‘Document<unknown, {}, { deletedAt?: Date; }> & Omit<{ deletedAt?: Date; } & { _id: ObjectId; }, never>’.

error TS2339: Property ‘myUndelete’ does not exist on type ‘Document<unknown, {}, { deletedAt?: Date; }> & Omit<{ deletedAt?: Date; } & { _id: ObjectId; }, never>’.

How to achieve adding new methods to the Schema and get recognized by typescript compiler at the same time? Any idea?

How to change value of variable linked to an array element without changing array element [duplicate]

I am making snake game in JavaScript.
What I am doing is finding new head position then using .unshift() to add it to my snake array, and then removing last element by .pop()

Here is my updateSnake() function.

var  snake = [[4,4],[4,3],[4,2],[4,1]]
const updateSnake = function(){
    var head = snake[0]
    switch(direction){
        case 1:    //up
            head[1] -= 1
            break
        case 2:     //left 
            head[0] -= 1
            break
        case 3:     //right
            head[0] += 1
            break
        case 4:      //down
            head[1] += 1
            break
    }
    console.log(snake)     // returns [[4,5],[4,3],[4,2],[4,1]]  but i was expecting [[4,4],[4,3],[4,2],[4,1]]
    //snake.unshift(head)
    //snake.pop()
}

But the problem I am facing:

For example I am in direction 4(down)
So head[1] += 1 is running
But this is changing the snake array’s 0th element(which is head) directly. So it return’s [[4,5],[4,3],[4,2],[4,1]] but I am expecting it to return [[4,4],[4,3],[4,2],[4,1]] so that I can use unshift and pop to update snake array afterwards.

How to display a picture in JavaScript that can be changed

I am making a sort of simple pet hangman game extension that I made from a tutorial. Most of the extension works fine, but my pictures do not display. I have the picture files as assets.
Here is my js code:

const words = [
  'KITTEN',
  'PUPPY',
  'BUNNY',
  'HAMSTER',
  'AXOLOTL',
  'FISH',
  'REPTILE',
  'BIRD'
];

// Define the maximum number of incorrect guesses allowed
const maxWrongGuesses = 5;

let wordToGuess = '';
let guessedLetters = [];
let wrongGuesses = 0;
let imageCount = 1;

// Select random word from the list
function selectRandomWord() {
  return words[Math.floor(Math.random() * words.length)];
}

// Initialize the game
function initializeGame() {
  wordToGuess = selectRandomWord();
  guessedLetters = Array(wordToGuess.length).fill('_');
  wrongGuesses = 0;

  // Update the word display
  updateWordDisplay();

  updateKitGraphic();

  // Remove any previously generated buttons
  const lettersContainer = document.querySelector('.letters');
  while (lettersContainer.firstChild) {
  lettersContainer.removeChild(lettersContainer.firstChild);
  }

 // Generate the letter buttons
  for (let i = 0; i < 26; i++) {
    const letter = String.fromCharCode(65 + i);
    const button = document.createElement('button');
    button.innerText = letter;
    button.addEventListener('click', function () {
      handleGuess(letter);
    });
    lettersContainer.appendChild(button);
  }

  // Clear any previous win/lose message
  const messageContainer = document.querySelector('.message');
  messageContainer.innerText = '';
}

// Update the word display
function updateWordDisplay() {
  const wordContainer = document.querySelector('.word');
  wordContainer.innerText = guessedLetters.join(' ');
}

// Handle a letter guess
function handleGuess(letter) {
  // If the letter has already been guessed, do nothing
  if (guessedLetters.includes(letter)) {
    return;
  }

 // Add the letter to the list of guessed letters
  guessedLetters.forEach((guessedLetter, index) => {
    if (wordToGuess[index] === letter) {
      guessedLetters[index] = letter;
    }
  });

  // If the letter is not in the hidden word, increment the wrong guesses count and update the Kitten Graphic
  if (!wordToGuess.includes(letter)) {
    wrongGuesses++;
    updateKitGraphic();
  }

  // Update the word display
  updateWordDisplay();

  // Check if the game has been won or lost
  checkWinOrLose();
}

function updateKitGraphic() {
  const KitContainer = document.querySelector('.Kit');
  KitContainer.innerHTML = `<img src="images/Kit${imageCount}.png" alt="Kit ${imageCount}">`;
  imageCount++;
}

// Check if the game has been won or lost
function checkWinOrLose() {
  if (guessedLetters.join('') === wordToGuess) {
    const messageContainer = document.querySelector('.message');
    messageContainer.innerText = 'You win!';
    const letterButtons = document.querySelectorAll('.letters button');
    letterButtons.forEach(button => {
      button.disabled = true;
      button.removeEventListener('click', handleGuess);
    });
  } else if (wrongGuesses >= maxWrongGuesses) {
    const messageContainer = document.querySelector('.message');
    messageContainer.innerText = `You lose! The word was "${wordToGuess}".`;
    const KitContainer = document.querySelector('.Kit');
    KitContainer.innerHTML = `<img src="images/gameover.png" alt="gameover">`;
    const letterButtons = document.querySelectorAll('.letters button');
    letterButtons.forEach(button => {
      button.disabled = true;
      button.removeEventListener('click', handleGuess);
    });
  }
}

// Initialize the game when the page loads
window.addEventListener('load', initializeGame);

The pic simply comes up with the little icon displayed when pictures aren’t available and says the name of the picture.

I tried changing how I put the photo up, but it didn’t work. I suppose it is how I opened the files and where I saved them that made this happen. Please try and answer my questions if you can!

Muffin123

How do i solve the error in my Lamda Function the deploy spring boot?

I want to run Spring Boot Controllers on AWS Lamda Function. I have a Handler that looks like this:
package com.amazonaws.serverless.sample.springboot3;

import com.amazonaws.serverless.exceptions.ContainerInitializationException;
import com.amazonaws.serverless.proxy.internal.testutils.Timer;
import com.amazonaws.serverless.proxy.model.AwsProxyRequest;
import com.amazonaws.serverless.proxy.model.AwsProxyResponse;
import com.amazonaws.serverless.proxy.spring.SpringBootLambdaContainerHandler;
import com.amazonaws.serverless.sample.springboot3.filter.CognitoIdentityFilter;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;

import jakarta.servlet.DispatcherType;
import jakarta.servlet.FilterRegistration;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.EnumSet;


public class StreamLambdaHandler implements RequestStreamHandler {
    private static SpringBootLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler;
    static {
        try {
            handler = SpringBootLambdaContainerHandler.getAwsProxyHandler(Application.class);

            // For applications that take longer than 10 seconds to start, use the async builder:
            // handler = new SpringBootProxyHandlerBuilder<AwsProxyRequest>()
            //                    .defaultProxy()
            //                    .asyncInit()
            //                    .springBootApplication(Application.class)
            //                    .buildAndInitialize();

            // we use the onStartup method of the handler to register our custom filter
            handler.onStartup(servletContext -> {
                FilterRegistration.Dynamic registration = servletContext.addFilter("CognitoIdentityFilter", CognitoIdentityFilter.class);
                registration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
            });
        } catch (ContainerInitializationException e) {
            // if we fail here. We re-throw the exception to force another cold start
            e.printStackTrace();
            throw new RuntimeException("Could not initialize Spring Boot application", e);
        }
    }

    public StreamLambdaHandler() {
        // we enable the timer for debugging. This SHOULD NOT be enabled in production.
        Timer.enable();
    }

    @Override
    public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context)
            throws IOException {
        handler.proxyStream(inputStream, outputStream, context);
    }
}

The Gradle build looks like this:

apply plugin: 'java'

repositories {
  mavenLocal()
  mavenCentral()
}

sourceCompatibility = 11
targetCompatibility = 11

dependencies {
  implementation (
          implementation('org.springframework.boot:spring-boot-starter-web:2.7.13') {
            exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
          },
          'com.amazonaws.serverless:aws-serverless-java-container-springboot3:[2.0-SNAPSHOT,)',
  )
}

task buildZip(type: Zip) {
  from compileJava
  from processResources
  into('lib') {
    from(configurations.compileClasspath) {
      exclude 'tomcat-embed-*'
    }
  }
}

build.dependsOn buildZip

I deploy the code to Lamda Function with this Pulumi Code:

import * as aws from "@pulumi/aws"
import * as pulumi from "@pulumi/pulumi";
import  {usersExecutionRole} from "./UsersExecutionRole"

const stack = pulumi.getStack()
const handler= "com.amazonaws.serverless.sample.springboot3.StreamLambdaHandler"


export const usersFunction = new aws.lambda.Function("users-function", {
    code: new pulumi.asset.FileArchive("../build/distributions/pet.zip"),   
    runtime: aws.lambda.Runtime.Java11,
    handler: handler,
    role: usersExecutionRole.arn,
    name: stack + '-' +"petsFunction",
    memorySize: 10240,
    timeout: 900,
    tracingConfig:{mode:"Active"},
    architectures:["arm64"],
    
        }

},

When I invoke the Lamda Function with curl
curl https://512lnld1ve.execute-api.eu-north-1.amazonaws.com/dev/pets
I get follwing message:
{“message”:”Internal Server Error”}%

The ClodWatch display following message:

Error loading class com.amazonaws.serverless.sample.springboot3.StreamLambdaHandler: javax/servlet/ServletException: java.lang.NoClassDefFoundError
java.lang.NoClassDefFoundError: javax/servlet/ServletException
at org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext$Factory.create(AnnotationConfigServletWebServerApplicationContext.java:230)
at org.springframework.boot.DefaultApplicationContextFactory.getFromSpringFactories(DefaultApplicationContextFactory.java:61)
at org.springframework.boot.DefaultApplicationContextFactory.create(DefaultApplicationContextFactory.java:48)
at org.springframework.boot.SpringApplication.createApplicationContext(SpringApplication.java:566)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:304)
at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:164)
at com.amazonaws.serverless.proxy.spring.SpringBootLambdaContainerHandler.initialize(SpringBootLambdaContainerHandler.java:189)
at com.amazonaws.serverless.proxy.InitializationWrapper.start(InitializationWrapper.java:35)
at com.amazonaws.serverless.proxy.spring.SpringBootProxyHandlerBuilder.buildAndInitialize(SpringBootProxyHandlerBuilder.java:79)
at com.amazonaws.serverless.proxy.spring.SpringBootLambdaContainerHandler.getAwsProxyHandler(SpringBootLambdaContainerHandler.java:87)
at com.amazonaws.serverless.sample.springboot3.StreamLambdaHandler.(StreamLambdaHandler.java:26)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Unknown Source)
Caused by: java.lang.ClassNotFoundException: javax.servlet.ServletException. Current classpath: file:/var/task/:file:/var/task/lib/aws-lambda-java-core-1.2.2.jar:file:/var/task/lib/aws-serverless-java-container-core-2.0.0-M1.jar:file:/var/task/lib/aws-serverless-java-container-springboot3-2.0.0-M1.jar:file:/var/task/lib/commons-io-2.12.0.jar:file:/var/task/lib/jackson-annotations-2.15.1.jar:file:/var/task/lib/jackson-core-2.15.1.jar:file:/var/task/lib/jackson-databind-2.15.1.jar:file:/var/task/lib/jackson-datatype-jdk8-2.15.1.jar:file:/var/task/lib/jackson-datatype-jsr310-2.15.1.jar:file:/var/task/lib/jackson-module-afterburner-2.15.1.jar:file:/var/task/lib/jackson-module-parameter-names-2.15.1.jar:file:/var/task/lib/jakarta.annotation-api-1.3.5.jar:file:/var/task/lib/jakarta.servlet-api-6.0.0.jar:file:/var/task/lib/jakarta.ws.rs-api-3.1.0.jar:file:/var/task/lib/jul-to-slf4j-1.7.36.jar:file:/var/task/lib/log4j-api-2.17.2.jar:file:/var/task/lib/log4j-to-slf4j-2.17.2.jar:file:/var/task/lib/logback-classic-1.2.12.jar:file:/var/task/lib/logback-core-1.2.12.jar:file:/var/task/lib/slf4j-api-2.0.7.jar:file:/var/task/lib/snakeyaml-1.30.jar:file:/var/task/lib/spring-aop-5.3.28.jar:file:/var/task/lib/spring-beans-5.3.28.jar:file:/var/task/lib/spring-boot-2.7.13.jar:file:/var/task/lib/spring-boot-autoconfigure-2.7.13.jar:file:/var/task/lib/spring-boot-starter-2.7.13.jar:file:/var/task/lib/spring-boot-starter-json-2.7.13.jar:file:/var/task/lib/spring-boot-starter-logging-2.7.13.jar:file:/var/task/lib/spring-boot-starter-web-2.7.13.jar:file:/var/task/lib/spring-context-5.3.28.jar:file:/var/task/lib/spring-core-5.3.28.jar:file:/var/task/lib/spring-expression-5.3.28.jar:file:/var/task/lib/spring-jcl-5.3.28.jar:file:/var/task/lib/spring-web-5.3.28.jar:file:/var/task/lib/spring-webmvc-5.3.28.jar

How do I fix this error?