Java Servlet Programing Laungage

Java Servlet Projects

Servlet Project 3

adplus-dvertising
Java Servlet :Example of RequestDispatcher
Previous Home Next

Example of RequestDispatcher

RequestDispatcher object is used by the servlet to forward the request to another web resource to include the contents of another web resource.

LoginServlet.java

import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginServlet extends HttpServlet
{
 public void doGet(HttpServletRequest request,HttpServletResponse response)
         throws ServletException,IOException
 {
 try
 {
   String user1=request.getParameter("txtName");
   String password1=request.getParameter("txtPassword");
   response.setContentType("text/html");
   PrintWriter out=response.getWriter();
   Class.forName("oracle.jdbc.driver.OracleDriver");
   Connection con=DriverManager.getConnection
	     ("jdbc:oracle:thin:@localhost:1521:xe","system","gaurav");
   PreparedStatement stmt=con.prepareStatement
	     ("select * from infologin where name=? and password=?");
   stmt.setString(1,user1); 
   stmt.setString(2,password1);
   ResultSet rset=stmt.executeQuery();
   if(rset.next())
   out.println("Welcome," +user1);
  else
  {
    out.println("<b>Invalid username and password !</b><br>");
    RequestDispatcher rd=request.getRequestDispatcher("index.html");
    rd.include(request,response);
  }
out.close();con.close();
}
  catch(Exception e)
{
	  System.out.println(e);
}
}
}

index.html

<html>
	<head>
	  <title> third web applicatin</title>
	</head>
	<body>
	  <form method="get" action="loginServlet">
	  Name<input type="text" name="txtName"> <br>
	  Password<input type="password" name="txtPassword">
	  <input type="submit" value="submit">
	  </form>
	</body>
</html>

web.xml

<web-app>
	<servlet>
	  <servlet-name> v1 </servlet-name>
	  <servlet-class> LoginServlet </servlet-class>
	</servlet>
	<servlet-mapping>
	  <servlet-name> v1 </servlet-name>
	  <url-pattern> loginServlet </url-pattern>
	</servlet-mapping>
</web-app>
Previous Home Next