Tuesday, November 27, 2012

SevletConfig Interface using JDBC, NetBeans 6.9 and Oracle 10g


Web Container Creates a object for ServletConfig for Each Servlet and we used this object to get configuration information from web.xml file using getServletConfig().getInitParameter(String name) method.
Due to ServletConfig you can dynamically change data without editing Servlet page using web.xml file.
For Example here we are using Oracle database so we need to specify Oracle Drivers and if Someone want to change Database like Oracle to sql then just need to change Drivers in web.xml file and there is no need to modify Servlet page.

You can also get  initialization parameter value  without initialization parameter name using Enumeration.
 import java.util.Enumeration;  
 import javax.servlet.ServletConfig;  
 ServletConfig config=getServletConfig();  
     Enumeration ee=config.getInitParameterNames();  
     while(ee.hasMoreElements())  
     {  
       String s=(String)ee.nextElement();  
       out.println(config.getInitParameter(s));  
     }  

Step 1:Create Login table in Oracle Database 
Goto Run Sql Command Line and write following commands
a) Connect to HR schema
b) Create Login Table with three columns Id,Username and Password

 CREATE TABLE LOGIN(   
 ID NUMBER,  
 UNAME VARCHAR2(20),  
 UPASS VARCHAR2(20)  
 );  
c) Insert one Row values as Shown in Picture.
d)It is Very Important That You must commit insert because insert is not AutoCommit(DML).
If You'll not commit it.Then username and password not be found and It'll show Invalid User as output.



Step 2: 
File->New Project->Java Web->Web Application
Here we are using Apache Tomcat 6.0 as Server.

Project View on Project Explorer on Completion of This Tutorial


Step 3: Adding Oracle Jar's
To add JAR files, Right click on Libraries Folder and goto Add JAR/Folder


Add ojdbc14.jar and ojdbc14_g.jar, to add these jars goto following location:
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\

Step 4:
index.jsp
In index.jsp page in form tag conServlet is url pattern of conServlet.java page which we are passing in Action property which redirects index.jsp to conServlet.java
 <%@page contentType="text/html" pageEncoding="UTF-8"%>  
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  
   "http://www.w3.org/TR/html4/loose.dtd">  
 <html>  
   <head>  
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
     <title>Login Page</title>  
   </head>  
   <body>  
     <h1>Login</h1>  
     <form action="conServlet">  
      Username:<input type="text" name="t1"><br>  
      Password:<input type="password" name="t2"><br>  
      <input type="submit" value="login" >  
      </form>  
   </body>  
 </html>  

Step 5: Create conservlet.java by right click on Source Packages->New->Servlet
conServlet.java
Here We are using Thin Driver, 1521 is port no. and XE stand for Oracle Express edition
First HR is Username and Second HR is Password of HR Schema. Our Login Table Exists in HR Schema.
 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;  
 import java.sql.*;  
 //import java.util.Enumeration;  
 //import javax.servlet.ServletConfig;  
 public class conServlet extends HttpServlet {   
   protected void doGet(HttpServletRequest req, HttpServletResponse res)  
   throws ServletException, IOException {  
     res.setContentType("text/html");  
     PrintWriter out=res.getWriter();  
     String s1=req.getParameter("t1");  
     String s2=req.getParameter("t2");  
     String dd1=getServletConfig().getInitParameter("d1");  
     String dd2=getServletConfig().getInitParameter("d2");  
     /*ServletConfig config=getServletConfig();  
     Enumeration ee=config.getInitParameterNames();  
     while(ee.hasMoreElements())  
     {  
       String s=(String)ee.nextElement();  
       out.println(config.getInitParameter(s));  
     }*/  
     try{  
       Class.forName(dd1);  
       Connection connection=DriverManager.getConnection(dd2,"hr","hr");  
       Statement st=connection.createStatement();  
       ResultSet rs=st.executeQuery("select * from login where Uname='"+s1+"'and Upass='"+s2+"'");  
       if (rs.next())  
       out.print("Welcome! "+s1);  
       else  
       out.print("invalid user");  
       }  
     catch(Exception e){  
       out.print(e);  
     }  
   }   
 }  


public ServletConfig getServletConfig()
Returns a ServletConfig object, which contains initialization and startup parameters for this servlet.

public String getInitParameter(String name)
Gets the value of the initialization parameter with the given name.
     
getParameter(String name)
Returns the value of a request parameter as a String, or null if the parameter does not exist. Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data.
     
Connection
A connection with a specific database. SQL statements are executed and results are returned within the context of a connection.     

Statement

The object used for executing a static SQL statement and returning the results it produces.

ResultSet

A table of data representing a database result set, which is usually generated by executing a statement that queries the database.
ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.     


Step 6:
Web-Pages->WEB-INF->web.xml

web.xml
 <?xml version="1.0" encoding="UTF-8"?>  
 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
   <servlet>  
     <servlet-name>conServlet</servlet-name>  
     <servlet-class>conServlet</servlet-class>  
     <init-param>  
       <param-name>d1</param-name>  
       <param-value>oracle.jdbc.driver.OracleDriver</param-value>  
     </init-param>  
     <init-param>  
       <param-name>d2</param-name>  
       <param-value>jdbc:oracle:thin:@localhost:1521:XE</param-value>  
     </init-param>  
   </servlet>  
   <servlet-mapping>  
     <servlet-name>conServlet</servlet-name>  
     <url-pattern>/conServlet</url-pattern>  
   </servlet-mapping>  
   <session-config>  
     <session-timeout>  
       30  
     </session-timeout>  
   </session-config>  
   <welcome-file-list>  
     <welcome-file>index.jsp</welcome-file>  
   </welcome-file-list>  
 </web-app>  

Download Code Link 1
Download Code Link 2
Output:
Login Screen
Valid User Screen

No comments:

Popular Posts