Solved

RequestDispatcher example issue

Posted on 2014-03-26
13
1,161 Views
Last Modified: 2014-04-24
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
Comment
Question by:gudii9
  • 10
  • 2
13 Comments
 
LVL 7

Author Comment

by:gudii9
ID: 39957933
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
 
LVL 35

Assisted Solution

by:mccarl
mccarl earned 200 total points
ID: 39957941
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
 
LVL 7

Author Comment

by:gudii9
ID: 39957988
when i run as tomcat 6 giving error
The server does not support version 3.0 of the J2EE Web module specification.
0
 
LVL 7

Author Comment

by:gudii9
ID: 39958010
when i try to change 2.5 dynamic project not taking. please advise
0
 
LVL 20

Accepted Solution

by:
chaitu chaitu earned 300 total points
ID: 39958064
change the web.xml schema definition as 2.5 version.
0
 
LVL 7

Author Comment

by:gudii9
ID: 39959601
when i try to change 2.5 dynamic project not allowing. says cannot change dyncamic project version to 2.5. please advise
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 7

Author Comment

by:gudii9
ID: 39959653
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
 
LVL 7

Author Comment

by:gudii9
ID: 39959655
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
 
LVL 7

Author Comment

by:gudii9
ID: 39959763
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
 
LVL 7

Author Comment

by:gudii9
ID: 39959814
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
 
LVL 7

Author Comment

by:gudii9
ID: 39959836
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
 
LVL 7

Author Comment

by:gudii9
ID: 39960685
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
 
LVL 20

Expert Comment

by:chaitu chaitu
ID: 39960796
happy to see that you solved the probelm
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now