Monday, 24 September 2018

Java Servlets

Assume that a client enter his/her name and password in a form and sends a request to servlet. Servlet 1  will creates the connection  with database and verify the user information from the database. Table (login) show success message on console, if name found otherwise enter the information of client in table (log) with current system date and display sorry message. 


HTML Form:

<!DOCTYPE html>
<html>
    <head>
        <title>HTML Form</title>
    </head>
    <body>
        <form name="form1" method="post" action="Servlet1">
            Username: <input type="text" name="t1" /><BR><BR>
            Password: <input type="password" name="t2" /><BR><BR>
            <input type="submit" name="Login" value="Login">
        </form>
    </body>
</html>

Servlet1:

import java.io.*;
import java.sql.*;
import javax.servlet.http.*;
public class Servlet1 extends HttpServlet {
    public void doPost(HttpServletRequest req, HttpServletResponse res) {
        try {
            PrintWriter pw = res.getWriter();
            res.setContentType("text/html");
            boolean flag = false;
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection cn = DriverManager.getConnection("Jdbc:Odbc:Exam");
            String sql = "select * from login";
            PreparedStatement st = cn.prepareStatement(sql);
            ResultSet rs = st.executeQuery();
            String s1 = req.getParameter("t1");
            String s2 = req.getParameter("t2");
            while (rs.next()) {
                if ((rs.getString(1).equals(s1)) && (rs.getString(2).equals(s2))) {
                    flag = true;
                }
            }
            if (flag) {
                pw.print("Login Succeeded!");
            } else {
                pw.print("Sorry... Login does not Succeeded!");
                String sql1 = "SELECT * FROM log";
                PreparedStatement pStmt = cn.prepareStatement(sql1, ResultSet.TYPE_SCROLL_INSENSITIVE,     ResultSet.CONCUR_UPDATABLE);
                ResultSet rs1 = pStmt.executeQuery();
                rs1.moveToInsertRow();
                rs1.updateString("username", s1);
                long time = System.currentTimeMillis();
                java.sql.Date date = new java.sql.Date(time);
                String s = date.toString();
                rs1.updateString("system_date", s);
                rs1.insertRow();
                cn.close();
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Output:

No comments:

Post a Comment

If you have any doubt please let me know

Methods in JAVA Language

 In general, a way may be thanks to perform some task. Similarly, the tactic in Java may be a collection of instructions that performs a sel...