Saturday, 2 January 2016

Java servlet program forward() and include() methods

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class First
 */
//@WebServlet("/First")
public class First extends HttpServlet {
//private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
   PrintWriter out = response.getWriter();
       
   String n=request.getParameter("userName");
   String p=request.getParameter("userPass");
       
  out.println("First Servlet");
   if(p.equals("servlet")){
       RequestDispatcher rd=request.getRequestDispatcher("/servlet2");
       rd.forward(request, response);
   }
   else{
       out.print("Sorry UserName or Password Error!");
       RequestDispatcher rd=request.getRequestDispatcher("/First.html");
       rd.include(request, response);
                   
       }
 
}

}



import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Sec
 */
//@WebServlet("/Sec")
public class Sec extends HttpServlet {
//private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub






   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
       
   String n=request.getParameter("userName");
   out.print("Welcome "+n);
   }


}



Output:-




No comments:

Post a Comment