Home > database >  How to call servlet after running JavaScript verification code?
How to call servlet after running JavaScript verification code?

Time:11-05

I am trying to run a character length check first and if user pass that than want to call the servlet which will return that user logged in.

<html>
<head><title>Login</title></head>
<link rel="stylesheet" href="css/style.css">
<body>
    <div >
        <div > <a href="/"><img  src="images/logo.png" alt="Hostel logo"></a>
            <H1>Welcome to Arihant's hostel</H1>
        </div>
        <navbar >
            <a href="Home.jsp">Home</a>
            <a  href="Login.jsp">Login</a>
            <a href="Room details.jsp">Room Details</a>
            <a href="Contact Us.jsp">Contact Us</a>
        </navbar>
    </div>
    <div >
        <navbar >
            <a href="Home.jsp">Home</a>
            <a  href="Login.jsp">Login</a>
            <a href="Room details.jsp">Room Details</a>
            <a href="Contact Us.jsp">Contact Us</a>
        </navbar>
        <div >
        
            <form  method=post action=LoginServlet> 
                <div>Room No: <input type="text" name="Roomno" id="Rno"><br></div><br>
                <div>Password : <input type="password" name="password" id="pass"></div><br>
                <input id="formSubmit" type="submit" value="SUBMIT">  
                </form> 
        </div>
    </div>
    <div >
        &#169; Arihant graphics
    </div>
   <script>
        const formSubmit = document.getElementById("formSubmit");
        formSubmit.addEventListener("click", (e) => {
            const Rno = document.getElementById("Rno").value;
            const Password = document.getElementById("pass").value;
            if (Rno == null || Rno == "" || Password.length < 7) {
                alert("Please enter a Room No or your password is incorrect");
                setTimeout(function () {
                    window.location.reload();
                }, 5000);
            }
            
            e.preventDefault();
        })
    </script>
     
</body>
</html>

After running the above jsp code it is checking the password length and Rno check correctly but not running the servlet after that given below.

I want to do this in doPost if possible.

and adding "else document.location.href = 'LoginServlet';" in javascript part return a error Status 405 -Method not allowed

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public LoginServlet() {
        super();
        }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
            PrintWriter out = response.getWriter();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","root");
            int roomNo = Integer.parseInt(request.getParameter("Roomno"));
            String password = request.getParameter("password");
            PreparedStatement ps = con.prepareStatement("select * from login where roomNo=? and password=?");
            ps.setInt(1, roomNo);
            ps.setString(2, password);
            ResultSet rs =  ps.executeQuery();
            
            if(rs.next()) {
              int userRoom = rs.getInt(1);
              String userName = rs.getString(3);
                out.println("RoomNo:" userRoom " is allocated to "  userName);
                con.close();
            }
            else
                out.println("Failed to log in");
            
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

CodePudding user response:

In the JSP page you are using HTML <form> which has an action attribute to bind the URL value to the servlet. The servlet expose itself with <servlet-mapping> configuration that is created via web.xml or with annotarions if you use at least servlet 3.0 specification in your application.

To communicate with a servlet you should make a HTTP request from your browser. There's a lot of ways to send a HTTP request from the page but you are using HTML <form> tag and when you press a submit button the request is going to the URL which contains in the action attribute of the <form> tag with the HTTP method used in the method attribute.

If you bind specific event handlers on the form's submit button then in the code you should allow the function to proceed with the event queue. But your handler is written such as it does not perform the event but also reloads the page. This way a new HTTP request is made from the browser and it uses HTTP GET method which is not implemented by the servlet. The error 405 is sent to the browser because no doGet() method in the servlet.

The solution to the problem is to remove the code that reloads a page and use preventDefault() only if the password is incorrect.

  • Related