write a program in servlet to take username & password from html file & print the appropriate message to user
Hi Friend,
Try the following code:
1)login.html:
<html> <head> </head> <body> <form name="form" method="post" action="http://localhost:8080/examples/login"> <br><br> <table align="center"><tr><td><h2>Login Authentication</h2></td></tr></table> <table width="300px" align="center" style="border:1px solid #000000;background-color:#efefef;"> <tr><td colspan=2></td></tr> <tr><td colspan=2> </td></tr> <tr> <td><b>Login Name</b></td> <td><input type="text" name="username" value=""></td> </tr> <tr> <td><b>Password</b></td> <td><input type="password" name="password" value=""></td> </tr> <tr> <td></td> <td><input type="submit" name="Submit" value="Submit"></td> </tr> <tr> <td></td> </tr> </table> </table> </form> </body> </html>
2)login.java:
import java.io.*; import java.io.PrintWriter; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class login extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String userid = request.getParameter("username"); String password = request.getParameter("password"); try { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root"); String query = "SELECT * FROM user_details WHERE username = '"+userid+"' and password = '"+password+"'"; Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); String username=""; String pwd=""; while(rs.next()){ username=rs.getString("username"); pwd=rs.getString("password") ; } if((username.equals(userid))&&(pwd.equals(password))){ out.println("<html>"); out.println("<head><title>Login Success</title></head>"); out.println("<body>"); out.println("<p>Login Success! Welcome " + userid); out.println("</body></html>"); } else{ out.println("<html>"); out.println("<head><title>No Such User</title></head>"); out.println("<body>"); out.println("<p>Login Failed! "); out.println("<p>No such user exists "); out.println("</body></html>"); out.println("<a href=\"login.html\">Click here to login</a>"); out.close(); conn.close(); } } catch (Exception e) { System.out.println("Error" + e.getMessage()); } out.close(); } }
Thanks
Ads