How can we access database with servlets?
DATABASE ACCESS WITH SERVLETS
Database access with servlets is the same as JDBC. Only the difference is that we have a mysql-connector.jar file in the WEB-INF directory inside our root directory.
Example
//login.html file
<html>
<head>
<Title> login page </Title>
</head>
<body>
<br><br>
<font color=blue size=12> <center> User Authentication page
</center></font>
<hr color=red size=3>
<br><br> <br>
<form action="Login" method="post">
<center>
<table>
<tr> <td> User ID </td> <td> <input type=text name=txtid></td></tr>
<tr> <td> Password </td> <td> <input type=password
name=txtpass></td></tr>
<tr> <td colspan=2 align=center>
<input type=submit value=OK>
<input type=reset></td></tr>
</table>
</form>
</body>
</html>
//Login.java File
import java.io.*;
import java.sql.;
import javax.servlet.*;
import javax.servlet.http.*;
public class Login extends HttpServlet
{
Connection con=null;
public void doPost(HttpServletRequest reg, HttpServletResponse resp)
throws IOException, ServletException
{
Printwriter out=resp.getWriter();
resp.setContentType("text/html");
String url="jdbc:mysql://localhost/Test";
try {
String n=req.getParameter("txtid");
String p=req.getParameter("txtpass");
Class.ForName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection(url, "root", "arjun");
Statement stmt=con.createStatement(); String sql="select * from login
where Name='"+n+"' and Password='"+p+""";
ResultSet rs=stmt.executeQuery(sql);
if(!rs.next())
{
out.println("<html><head></Title> Login error </Title> </head><body>");
out.println("<br><br><br><br><b>Unknown User </b> <br><br> :");
out.println("<h3>Access denied </h3></body></html>");
}
else
{
out.println("<html><head></Title> Login success </Title>
</head><body><center>");
out.println("<br><br><br> Welcome");
out.println(n+"</b><br>");
out.println("<h3>You have been Authenticated </h3> </center>
</body></html>");
}
con.close();
}
catch(SQLException se)
{out.println("Error!!!!"+se); }
catch(ClassNotFoundException cne)
{out.println("Error!!!!"+cne); }
}
}
Comments
Post a Comment