Steps for invoking a Java function within a JSP document

In my project, I need to ensure that the username entered by a user is unique and does not match any other usernames already registered. This validation process occurs in newuser.jsp, where a function called searchForUsername in SemanticSearch.java is executed. Additionally, when a new user registers, their email address must also be validated before checking the uniqueness of the username.

Despite my efforts, it seems that my current approach is not working as expected. Can you please help me identify what mistake I might be making?

The constructor in my SemanticSearch.java code is as follows:

public SemanticSearch() {}

The excerpt below executes after the email id validation:

In newuser.jsp, the relevant code snippet for this functionality is:

SemanticSearch myclass=new SemanticSearch();

boolean rets=myclass.searchForUsername(username);

if (rets==false)

{

    alert("Username already exists");

    document.getElementById("username").value="";

    document.getElementById("password").value="";

    document.getElementById("username").focus();

}

This function should be triggered during the click event of the adduser button. However, upon clicking, nothing appears to occur. Any assistance would be greatly appreciated.

Answer №1

It's important to note that Java and JavaScript are two distinct languages that run in different environments. While Java runs on a webserver, JavaScript runs in a web browser.

There are two main approaches to meet this requirement:

  1. Develop a servlet that listens on a specific URL, handles the validation process, and allows your form to submit to it. The servlet can then return to the same page with error messages displayed using JSP/EL. You can refer to a simple example in our servlet wiki page.

  2. Create a servlet that listens on a particular URL, manages the validation process, and enables your JavaScript code to call it using Ajax techniques. This approach involves modifying the HTML DOM dynamically to display error messages. For an example, you can check out the answer to this question.

Answer №2

Make sure your code follows this structure. Any Java code in a JSP file should be wrapped between "<%" and "%>".

<%
SemanticSearch search = new SemanticSearch();

boolean result = search.checkForUsername(username);

if (!result) {
%>
alert("Username already exists");

    document.getElementById("username").value = "";

document.getElementById("password").value = "";

document.getElementById("username").focus();
<%
}
%>

Answer №3

<%
SemanticSearch search=new SemanticSearch();

boolean results=search.searchForUsername(username); // How can the username be obtained and assigned to this variable upon button click?

if (!results)
{
%>

It seems that a Java variable can be assigned to a JavaScript variable

var username = '<%= username%>';

but does it work vice versa?

<%String username = %>document.getElementById("username").value<%:%>

I would favor BalusC's approach (1st one), as using javascript validation in this scenario can be risky since most browsers support disabling of javascript.

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

Execution failure of the passport.authenticate callback

I am currently working on developing a backend using nodejs v8.7.0. For authentication, I am implementing passport and local passport. Previously, everything was running smoothly, but now I am facing an issue. Here is my code: My strategy: var passport = ...

What are some ways to implement Node.js within Netsuite?

Recently, I've been exploring Netsuite and I'm curious to learn about the feasibility of integrating Node.js or npm modules into a SuiteScript or Suitelet. Is it possible? I have a specific aim in mind - to utilize some npm modules within Netsui ...

Enhancing MongoDB within a MEAN (MongoDB, Express,

Looking for assistance in updating my MongoDB database? I have the server-side code ready, but need help implementing it on the client side using Angular. Can anyone provide guidance? module.exports.updateUser = function (req, res) { // Retrieve user wi ...

Discover the method for invoking a Javascript function within a Leaflet popup using HTML

Upon clicking on a marker on the leaflet map, I aim to trigger a popup box that contains five elements: Title Description Image Button (Next Image) Button (Previous Image) To achieve this, I attempted to include a custom popup for each feature ...

Conceal a bootstrapTable column with the power of JavaScript or jQuery

I have incorporated bootStrap Table in order to display information for my users based on the following example. In my table, I am attempting to hide the Edit and Delete options by concealing the operate (Delete User Column) data field. I attempted using ...

Unexpected Behavior in ComponentDidMount

During my exploration of the React documentation, I came across an example of a clock timer implementation. It was interesting to see how the setInterval function is used inside the componentDidMount method to update the state and trigger re-rendering of ...

JavaScript and jQuery are causing my new HTML elements to multiply rapidly - it's mind-boggling!

Greetings! I could use some help with my code. Whenever I use the contmgr_create_media and contmgr_update_order functions together, like when clicking the add image button, new items are created in an exponential pattern (1, 2, 4, 8, 16). However, if I d ...

Struggling with identifying errors in the Javascript code for my assignment

My code is giving me trouble and I could really use some assistance You can find my code in this GitHub folder: link. To see the project in action, visit this page on GitHub Pages: link. The task involves iterating over an array of names and printing eit ...

Tips for Utilizing External Classes in Fitnesse

I currently have two jar files: MyProduct.jar which contains the business logic, and MyProductFixture.jar which serves as the fixture that invokes the business logic. It is important to note that MyProductFixture.jar relies on MyProduct.jar for its functi ...

Displaying numerous database rows through SQL with the aid of PHP and JavaScript (specifically AJAX) on the frontend of a website

I am a beginner in the world of PHP and JavaScript (Ajax) and despite my efforts to find a solution by looking at various posts and websites, I have not been successful. My goal is to display all related database rows on the front end of a website. While ...

Tips for integrating jQuery AJAX with PHP arrays for efficient data handling

Here is my jQuery AJAX request: $.ajax({ type: 'POST', url: 'processor.php', data: 'data1=testdata1&data2=testdata2&data3=testdata3', cache: false, success: function(result) { if(result){ ...

No routes were found that match: ""

app.routes.ts import { ModuleWithProviders } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { PushComponent } from './push/push.component'; const appRoutes: Routes = [ { path: ...

Tips for handling numerous requests using Express.JS

I am currently working on an Angular 6 + Express.JS application and have encountered a problem. When multiple requests are made simultaneously, especially when there are more than 4 requests, all of them sometimes respond with a 404 error or get cancelled. ...

InnerHTML failing to append HTML content

Almost at the finish line with this code! I already have a footer in place, but when the button is clicked, it smoothly slides down along with its contents. Once it's done sliding, I utilize JavaScript to swap out that footer and its contents with a n ...

How can circular dependencies be resolved within Angular dependency injection?

Is there a solution to resolving circular dependency injection errors in Angular 1.x? I'm aware of using the injector to inject a service. However, are there other alternatives to address this issue? Furthermore, is it acceptable to implement this ...

Prioritize establishing the connection before guiding the user to a new destination

I have a brilliant idea for creating something amazing, but I'm uncertain if it's feasible. Here is a basic example of an ajax function that could potentially establish a connection with a server... function getFakePage(userId) { var ajaxObj ...

Three.js Troubleshooting: Texture Loading Issue

Having trouble retrieving a texture saved in a folder? Here's the error message I'm encountering: "GET file:///E:/Html/Expo%20Sites/Good%20Site/tex/dirt.jpg net::ERR_FILE_NOT_FOUND" I've followed the steps to get the texture, store it in ...

Retrieve - obtain the textual content in HTML format as a reply

I encounter an issue with a rate-limit that returns HTML: const Limiter = rateLimit({ windowMs: 5 * 60 * 1000, message: "Too many requests created from this IP, please try again later.", max: 10 }) In addition, I have a fetch request on th ...

Unable to retrieve the video from the specified URI when using the new Intent(MediaStore.ACTION_VIDEO_CAPTURE) in Android versions 12 and 13

My goal is to record a 60-second video using an Intent in Android. I have created a video file and passed its URI within the Intent object. The code below works successfully on Android 9, but it encounters issues on Android 12/13. Here are the Intent obje ...

Leverage the power of Next.js Dynamic routing query object with an SWR fetch request

While working with Next.js dynamic routing, I am facing an issue where my SWR fetch request is being called before the query object is properly set. This occurs specifically when using the routing query object. Let's take the example of a dynamic rou ...