Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1409
  • Last Modified:

RequestDispatcher example issue

Hi,

I am trying and reading as below (http://www.javatpoint.com/requestdispatcher-in-servlet)


Introduction to Servlet
What is Servlet Servlet Terminology Servlet API Servlet Interface GenericServlet HttpServlet Servlet Life Cycle Servlet Example How servlet works? War File welcome-file-list Load on startup
Servlet with IDE
servlet in Eclipse servlet in Myeclipse servlet in Netbeans
ServletRequest
Servlet Collaboration
RequestDispacher sendRedirect
ServletConfig
ServletContext
Attribute in Servlet
Session Tracking
Session Techniques 1) Cookies in Servlet Cookies: Login & Logout 2) Hidden Form Field 3) URL Rewriting 4) HttpSession Session: Login & Logout
Event and Listener
Servlet Filter
What is Filter Authentication Filter FilterConfig Useful examples
Servlet Miscellaneous
ServletInputStream ServletOutputStream Annotation Servlet SingleThreadModel SSI
Development
Registration Example Fetching records Improving Performance Uploading file Downloading file Servlet Sending Email Write data to PDF Login Example Writing Image
Servlet Quiz
Servlet Quiz(Part-1) Servlet Quiz(Part-2) Servlet Quiz(Part-3)
space
next>> <<prev
RequestDispatcher in Servlet

    RequestDispatcher Interface
    Methods of RequestDispatcher interface
        forward method
        include method
    How to get the object of RequestDispatcher
    Example of RequestDispatcher interface

The RequestDispacher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp.This interface can also be used to include the content of antoher resource also. It is one of the way of servlet collaboration.

There are two methods defined in the RequestDispatcher interface.

Methods of RequestDispatcher interface

The RequestDispatcher interface provides two methods. They are:

    public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
    public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP page, or HTML file) in the response.

forward() method of RequestDispatcher interface

As you see in the above figure, response of second servlet is sent to the client. Response of the first servlet is not displayed to the user.

include() method of RequestDispatcher interface
As you can see in the above figure, response of second servlet is included in the response of the first servlet that is being sent to the client.
How to get the object of RequestDispatcher

The getRequestDispatcher() method of ServletRequest interface returns the object of RequestDispatcher. Syntax:
Syntax of getRequestDispatcher method

    public RequestDispatcher getRequestDispatcher(String resource);  

Example of using getRequestDispatcher method

    RequestDispatcher rd=request.getRequestDispatcher("servlet2");  
    //servlet2 is the url-pattern of the second servlet  
     
    rd.forward(request, response);//method may be include or forward  

Example of RequestDispatcher interface

In this example, we are validating the password entered by the user. If password is servlet, it will forward the request to the WelcomeServlet, otherwise will show an error message: sorry username or password error!. In this program, we are cheking for hardcoded information. But you can check it to the database also that we will see in the development chapter. In this example, we have created following files:

    index.html file: for getting input from the user.
    Login.java file: a servlet class for processing the response. If password is servet, it will forward the request to the welcome servlet.
    WelcomeServlet.java file: a servlet class for displaying the welcome message.
    web.xml file: a deployment descriptor file that contains the information about the ser


I did not understand what it mean by

If password is servlet, it will forward the request to the WelcomeServlet, otherwise will show an error message: sorry username or password error!

I downloaded eclipse source code as zip. How to import as web project. When i import as attached (Existing Project into workspace) creating as java project.(can i convert java project to web after creation?). When i run on the project since it is java project i am not seeing --->RunAs-->Run on server option.
when i import as  web war file and when i click--> Browse button that is not showing the downloaded zip. How to solve this issue.

I opened command prompt--cd
C:\Users\Desktop\gpfolder\gpmy\SampleCode\Online\javatpoint\requestdispatcher\requestdispatcher(which has src and WebContent build folders)
then i executed below command
==> jar -cvf requestdispatcher.war *
that generated war

I imported that war. But i see generated web project structure is not correct where src came under WebConent instead of JAvaResource-->src.
How to fix this and import properly.


>>> out.print("Sorry UserName or Password Error!");

does aboe line prints in the page or on the console. I thought console similar to System.out.println in java.

I even searched for .classpath file by click Control Shift R then opened classpath file and change the servlet.jar reference wrongly location from D drive to my local Servlet.jar location(C:\softwares\apache-tomcat-6.0.37-windows-x64\apache-tomcat-6.0.37\lib) even that also did not fix the issue.
please advise
Any links resources ideas highly appreciated. Thanks in advance
Import0.jpg
Import.jpg
Import2.jpg
Import3.jpg
Import4.jpg
0
gudii9
Asked:
gudii9
  • 10
  • 2
2 Solutions
 
gudii9Author Commented:
i exported Existing Project and selcted zip file and got java project.

Now i right clicked and went to project facets and selected 'Dynamic Project 3.0 and then java 1.6' and run as  Tomcat 7

when i run on tomcat 7 i see html page(http://localhost:8080/requestdispatcher/) but when i gave username gp and password servlet getting below error

HTTP Status 500 - Simple : Unsupported major.minor version 51.0 (unable to load class Simple)

--------------------------------------------------------------------------------

type Exception report

message Simple : Unsupported major.minor version 51.0 (unable to load class Simple)

description The server encountered an internal error that prevented it from fulfilling this request.

exception

java.lang.UnsupportedClassVersionError: Simple : Unsupported major.minor version 51.0 (unable to load class Simple)
      org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2899)
      org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1173)
      org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1681)
      org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
      org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:491)
      org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
      org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
      org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
      org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
      org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
      org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
      java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
      java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
      java.lang.Thread.run(Thread.java:662)


note The full stack trace of the root cause is available in the Apache Tomcat/7.0.42 logs.
0
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
Looks like a version problem between the compiled classes and the JRE used to run them. Try doing a "Project" -> "Clean..." on your project.
0
 
gudii9Author Commented:
when i run as tomcat 6 giving error
The server does not support version 3.0 of the J2EE Web module specification.
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
gudii9Author Commented:
when i try to change 2.5 dynamic project not taking. please advise
0
 
chaitu chaituCommented:
change the web.xml schema definition as 2.5 version.
0
 
gudii9Author Commented:
when i try to change 2.5 dynamic project not allowing. says cannot change dyncamic project version to 2.5. please advise
0
 
gudii9Author Commented:
Is this example running when imported as java project from downloaded zip and converting to dynamic webproject and run on tomcat 7 server.

i still get error


HTTP Status 500 - Simple : Unsupported major.minor version 51.0 (unable to load class Simple)

type Exception report

message Simple : Unsupported major.minor version 51.0 (unable to load class Simple)

description The server encountered an internal error that prevented it from fulfilling this request.

exception

java.lang.UnsupportedClassVersionError: Simple : Unsupported major.minor version 51.0 (unable to load class Simple)
      org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2899)
      org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1173)
      org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1681)
      org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
      org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:491)
      org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
      org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
      org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
      org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
      org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
      org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
      java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
      java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
      java.lang.Thread.run(Thread.java:662)

note The full stack trace of the root cause is available in the Apache Tomcat/7.0.42 logs.

please advise
0
 
gudii9Author Commented:
web.xml looks as below
<?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>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>Simple</servlet-name>
    <servlet-class>Simple</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>WelcomeServlet</servlet-name>
    <servlet-class>WelcomeServlet</servlet-class>
  </servlet>


  <servlet-mapping>
    <servlet-name>Simple</servlet-name>
    <url-pattern>/go</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>WelcomeServlet</servlet-name>
    <url-pattern>/welcome</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>login.html</welcome-file>
  </welcome-file-list>
</web-app>
0
 
gudii9Author Commented:
i change the ajva back to 1.6 as attached i am getting different  error now(https://www.java.net/node/664117) please advise

type Exception report

message Error instantiating servlet class Simple

description The server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: Error instantiating servlet class Simple
      org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
      org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
      org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
      org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
      org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
      org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
      org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
      java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
      java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
      java.lang.Thread.run(Thread.java:662)

root cause

java.lang.ClassNotFoundException: Simple
      org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
      org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
      org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
      org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
      org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
      org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
      org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
      org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
      org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
      java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
      java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
      java.lang.Thread.run(Thread.java:662)

note The full stack trace of the root cause is available in the Apache Tomcat/7.0.42 logs.
java6.jpg
0
 
gudii9Author Commented:
I do see simple.java servlet in under default package as below
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;
import javax.servlet.http.*;


public class Simple extends HttpServlet {

      public void doGet(HttpServletRequest request, HttpServletResponse response)
                  throws ServletException, IOException {

            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            
            String p=request.getParameter("userPass");
            if(p.equals("servlet")){
                  RequestDispatcher rd=request.getRequestDispatcher("welcome");
                  rd.forward(request, response);
                  
            }
            else{
                  out.print("Sorry username or password error!");
                  RequestDispatcher rd=request.getRequestDispatcher("login.html");
                  rd.include(request, response);
            }
            
      }

}

Do i need to put it in any package?


WelcomeServlet.java looks like
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 WelcomeServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

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

}

Open in new window


login.html as below

<form action="go" method="get">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>

</form>

Open in new window


lastly web.xml as below

<?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>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>Simple</servlet-name>
    <servlet-class>Simple</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>WelcomeServlet</servlet-name>
    <servlet-class>WelcomeServlet</servlet-class>
  </servlet>


  <servlet-mapping>
    <servlet-name>Simple</servlet-name>
    <url-pattern>/go</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>WelcomeServlet</servlet-name>
    <url-pattern>/welcome</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>login.html</welcome-file>
  </welcome-file-list>
</web-app>

Open in new window

0
 
gudii9Author Commented:
I do not see any .class files under

web-inf/classes


How to compile and generate the class files in the eclipse itself so that my code get to see generated .class file of the servlet?
please advise
0
 
gudii9Author Commented:
I created separate dynamic web project from scratch. Then i copied individually src and webcontent. Then run on server. then it all worked fine
0
 
chaitu chaituCommented:
happy to see that you solved the probelm
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 10
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now