Write a servlet code to display Name,ISBN number,price data
of book stored in Database.
Index.html
<html>
<head>
<title>HTML FORM TO GET INPUT DATA
USED TO SEARCH IN DATABASE</title>
<meta
http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<meta
name="viewport" content="width=device-width">
</head>
<body>
<form
action="search">
Enter Book Name:
<input type="text" name="bname"/><br/>
<input
type="submit" value="search"/>
</form>
</body>
</html>
Search.java(servlet program)
import java.io.*;
import java.sql.*;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Search extends HttpServlet {
@Override
protected void
doGet(HttpServletRequest request, HttpServletResponse response)
throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out =
response.getWriter();
String
name=request.getParameter("bname").toUpperCase();
out.println("Entered Name : " + name);
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/Library"
,"root","root");
PreparedStatement ps=con.prepareStatement("select * from liba where
book_name=?");
ps.setString(1,name);
out.print("<center><h1>Result:</h1></center>");
ResultSet
rs=ps.executeQuery();
/* Printing
column names */
ResultSetMetaData rsmd=rs.getMetaData();
if (!rs.isBeforeFirst()) {
out.println("Given Book Name is not available");
} else {
out.print("<table width=25% border=1>");
while(rs.next())
{
out.print("<tr>");
out.print("<td>"+rsmd.getColumnName(1)+"</td>");
out.print("<td>"+rs.getString(1)+"</td></tr>");
out.print("<tr><td>"+rsmd.getColumnName(2)+"</td>");
out.print("<td>"+rs.getString(2)+"</td></tr>");
out.print("<tr><td>"+rsmd.getColumnName(3)+"</td>");
out.print("<td>"+rs.getString(3)+"</td></tr>");
}
out.print("</table>");
}
}catch (Exception
e2)
{
//out.println(e.message() + " Cause = " + e.getcause());
e2.printStackTrace();
}
finally{out.close(); }
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1"
xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>Search</servlet-name>
<servlet-class>Search</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Search</servlet-name>
<url-pattern>/search</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
OUTPUT:
No comments:
Post a Comment