<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>New User Sign Up</title>
<!-- Bootstrap CSS CDN -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="loginNewUserSignUp.css" />
</head>
<body>
<div class="signup-container">
<div class="signup-header">NEW USER SIGN UP DETAILS</div>
<form id="signupForm" novalidate>
<div class="form-row d-flex align-items-center mb-2">
<label for="userName" class="label-field col-4">Enter User Name</label>
<input type="text" id="userName" name="userName" autocomplete="off" class="input-field col-7" />
<span class="asterisk">*</span>
</div>
<div class="form-row d-flex align-items-center mb-2">
<label for="userId" class="label-field col-4">Enter User ID</label>
<input type="text" id="userId" name="userId" autocomplete="off" class="input-field col-7" />
<span class="asterisk">*</span>
</div>
<div class="form-row d-flex align-items-center mb-2">
<label for="password" class="label-field col-4">Enter User Password</label>
<input type="password" id="password" name="password" autocomplete="off" class="input-field col-7" />
<span class="asterisk">*</span><br>
</div>
<span class="password-msg">(Atleast one Capital Letter, One Number and One Special Character should be in Password)</span>
<div class="form-row d-flex align-items-center mb-2">
<label for="confirmPassword" class="label-field col-4">Confirm User Password</label>
<input type="password" id="confirmPassword" name="confirmPassword" autocomplete="off" class="input-field col-7" />
<span class="asterisk">*</span>
</div>
<div class="form-row d-flex align-items-center mb-2">
<label for="email" class="label-field col-4">Enter User Email ID</label>
<input type="email" id="email" name="email" autocomplete="off" class="input-field col-7" />
<span class="asterisk">*</span>
</div>
<div class="form-row d-flex align-items-center mb-2">
<label for="mobile" class="label-field col-4">Enter User Mobile No.</label>
<input type="text" id="mobile" name="mobile" autocomplete="off" maxlength="10" class="input-field col-7" />
<span class="asterisk">*</span>
</div>
<div class="form-row d-flex align-items-center mb-2">
<label for="address" class="label-field col-4">Enter User Address</label>
<textarea id="address" name="address" class="input-field col-7" rows="4" wrap="soft"></textarea>
<span class="asterisk">*</span>
</div>
<div class="button-row d-flex justify-content-center mt-3">
<button type="submit" class="submit-btn">SUBMIT</button>
<button type="reset" id="resetBtn" class="reset-btn">RESET</button>
<button type="button" id="closeBtn" class="close-btn">CLOSE</button>
</div>
</form>
</div>
<script src="loginNewUserSignUp.js"></script>
</body>
</html>
My js file code is —
//
// Disable right-click on the page
document.addEventListener('contextmenu', event => event.preventDefault());
// Disable tab key and enable enter key to move focus
document.addEventListener('keydown', function(event) {
if (event.key === 'Tab') {
event.preventDefault();
}
if (event.key === 'Enter') {
const formElements = Array.from(document.querySelectorAll('#signupForm input, #signupForm textarea'));
const index = formElements.indexOf(document.activeElement);
if (index > -1 && index < formElements.length - 1) {
formElements[index + 1].focus();
event.preventDefault();
}
}
});
const form = document.getElementById('signupForm');
function showError(input, message) {
alert(message);
input.focus();
}
function validateNotBlank(input, fieldName) {
if (!input.value.trim()) {
showError(input, `The field cannot be Blank: ${fieldName}`);
return false;
}
return true;
}
function validatePassword(input) {
const value = input.value;
const hasCapital = /[A-Z]/.test(value);
const hasNumber = /[0-9]/.test(value);
const hasSpecial = /[!@#$%^&*(),.?":{}|<>]/.test(value);
if (!hasCapital || !hasNumber || !hasSpecial) {
showError(input, "Password must contain at least one Capital Letter, One Number and One Special Character.");
return false;
}
return true;
}
function validateConfirmPassword(passwordInput, confirmInput) {
if (passwordInput.value !== confirmInput.value) {
alert("The Password and Confirm Password are not same.");
confirmInput.focus();
return false;
}
return true;
}
function validateEmail(input) {
const emailRegex = /^[^s@]+@[^s@]+.[^s@]+$/;
if (!emailRegex.test(input.value.trim())) {
showError(input, "Enter valid Email ID");
return false;
}
return true;
}
function validateMobile(input) {
const mobileRegex = /^[0-9]{10}$/;
if (!mobileRegex.test(input.value.trim())) {
showError(input, "Enter a valid Mobile Number");
return false;
}
return true;
}
function validateAddress(input) {
const words = input.value.trim().split(/s+/).filter(word => word.length > 0);
if (words.length === 0 || words.length > 4500) {
showError(input, "Please enter proper Address not more than 4500 words.");
return false;
}
return true;
}
form.addEventListener('submit', function(event) {
event.preventDefault();
alert("Entering Data");
const userName = document.getElementById('userName');
const userId = document.getElementById('userId');
const password = document.getElementById('password');
const confirmPassword = document.getElementById('confirmPassword');
const email = document.getElementById('email');
const mobile = document.getElementById('mobile');
const address = document.getElementById('address');
if (!validateNotBlank(userName, 'User Name')) return;
if (!validateNotBlank(userId, 'User ID')) return;
if (!validateNotBlank(password, 'Password')) return;
if (!validatePassword(password)) return;
if (!validateNotBlank(confirmPassword, 'Confirm Password')) return;
if (!validateConfirmPassword(password, confirmPassword)) return;
if (!validateNotBlank(email, 'Email')) return;
if (!validateEmail(email)) return;
if (!validateNotBlank(mobile, 'Mobile')) return;
if (!validateMobile(mobile)) return;
if (!validateNotBlank(address, 'Address')) return;
if (!validateAddress(address)) return;
alert("Entering Transfer");
const servletUrl = 'http://localhost:8081/MyTransactionDetails/Servlets/loginNewUserData';
// Send data to servlet
fetch(servletUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
userName: userName.value,
userId: userId.value,
password: password.value,
confirmPassword:confirmPassword.value,
email: email.value,
mobile: mobile.value,
address: address.value
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert('Data entered successfully');
// Clear form
form.reset();
// Focus on userName
userName.focus();
} else {
alert('Error: ' + data.message);
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred during sign up.');
});
});
My servlet code is as shown below
package Servlets;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
import java.sql.ResultSet;
import java.sql.SQLException;
import jakarta.servlet.*;
@WebServlet("/loginNewUserData")
public class loginNewUserData extends HttpServlet {
private static final long serialVersionUID = 1L;
// Database connection details
private static final String DB_URL = "jdbc:mysql://localhost:3306/mytransactiondetails";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "Devi@27032009";
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// CORS headers
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
response.setContentType("application/json");
PrintWriter out = response.getWriter();
StringBuilder sb = new StringBuilder();
String line;
try (BufferedReader reader = request.getReader()) {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
}
String requestBody = sb.toString();
JSONObject jsonRequest = new JSONObject(requestBody);
String userName = jsonRequest.getString("userName");
String userId = jsonRequest.getString("userId");
String password = jsonRequest.getString("password");
String confirmpwd=jsonRequest.getString("confirmPassword");
String email = jsonRequest.getString("email");
String mobile = jsonRequest.getString("mobile");
String address = jsonRequest.getString("address");
JSONObject jsonResponse = new JSONObject();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn =null;
conn=DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
String newUserIDNo = null,sqlSearchID;
sqlSearchID="select count(qr_New_User_ID) as totalID from qr_new_user_details";
PreparedStatement pstmt= conn.prepareStatement(sqlSearchID);
ResultSet rs=pstmt.executeQuery();
while (rs.next())
{
newUserIDNo=rs.getString("totalID");
newUserIDNo=newUserIDNo+1;
}
Date CurDate=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("dd/mm/yyyy");
String getCurDate=sdf.format(CurDate);
String sql = "INSERT INTO qr_new_user_details (qr_New_User_ID, qr_New_User_Name, qr_New_UID, qr_New_UPWD, qr_New_UCPWD, qr_New_User_Email,qr_New_User_Mobile,"
+ "qr_New_User_Address,qr_New_User_Status,qr_New_User_Create_Date) VALUES (?, ?, ?, ?, ?, ?,?,?,?,?)";
java.sql.PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, newUserIDNo);
stmt.setString(2, userName);
stmt.setString(3, userId);
stmt.setString(4, password);
stmt.setString(5, confirmpwd);
stmt.setString(6, email);
stmt.setString(7, mobile);
stmt.setString(8, address);
stmt.setString(9, "Active");
stmt.setString(10, getCurDate);
int rowsAffected = stmt.executeUpdate();
if (rowsAffected > 0) {
jsonResponse.put("success", true);
jsonResponse.put("message", "Data entered successfully");
} else {
jsonResponse.put("success", false);
jsonResponse.put("message", "Failed to insert data");
}
stmt.close();
conn.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
jsonResponse.put("success", false);
jsonResponse.put("message", "Database error: " + e.getMessage());
}
out.print(jsonResponse.toString());
out.flush();
}
protected void doOptions(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Handle CORS preflight
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
response.setStatus(HttpServletResponse.SC_OK);
}
}
<———————————————————->
The above is the code which I wrote for new user details to be entered in the jsp file and validated in js file. After validation the data should be transferred fron js file to the servlet. I am using eclipse ide for the coding. The issue is that the data is not transferred from js file to the servlet.