There are 2 ways of doing it,
1. Validating at the client side using javascript
2. Validating at the server side.
In the former you have to pass the value to the jsp when the page is loaded. Say if qty A you have 40 pieces, pass 40 and store it in a javascript variable on load of the page and validate on submit if user has entered the right quantity.
The above method will need code change at both client side and server side if new items are added are deleted.
Best thing to do would be to validate at the server side. Call a validation class from your
servlet and based on success or failure return the user to same page/next page. This is extensible also because you can fetch all items from the db and validate the corresponding quantities against the values entered by the user. So in future if new items are added/items deleted you wont have to change the code.