Tomcat 6 – Calling a  Java Servlet from a JSP Page

Below is a very simple JSP Page that calls a Java Servlet. The question is given Tomcat security constraints, is it possible to call a servlet from a JSP and get the correct output without getting an error message? If so, how would you code the web.xml file?
c:\apache-tomcat-6.0.18
Under conf
catalina
localhost
HelloWorldExample.xml is directly under localhost
The application would have this directory structure:
webapps
HelloWorldExample
hello.jsp is directly under HelloWorldExample
Under HelloWorldExample
src
WEB-INF
classes
Under classes
jservlets
HelloWorld.java is in src folder
HelloWorld.class is in jservlets folder
HelloWorldExample.xml
<Context path="/HelloWorldExample" docBase="HelloWorldExample" debug="0"
      reloadable="true" crossContext="true">    
</Context>**************************
hello.jsp
<HTML>
<HEAD>
<TITLE>Hello</TITLE>
</HEAD>
<BODY>
<FONT SIZE="4">
<P>
Please enter your name:
<FORM 
   METHOD="Post"
   ACTION="servlet/jservlets.HelloWorld">
<TABLE BORDER="3" CELLPADDING="1" WIDTH="100%" ALIGN="CENTER">
<TR>
    <TD><B>Name:</B></TD>
    <TD><INPUT TYPE="text" NAME="Name" VALUE="" SIZE="65"> </TD>      
</TR>
</TABLE>
<P>
<INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>
</FONT>
</BODY>
</HTML>******************
HelloWorld.java
package jservlets;
import java.io.*;
import java.util.Date;
import java.util.*;
import java.text.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet
   PrintWriter out;
   PrintWriter err; 
   String strName;
public void displayMessage(HttpServletRequest request, HttpServletResponse response)
      throws Exception
         try
            if (!strName.equals("") && strName != null)
               out.println("Hello " + strName + "" + "<P>");
                out.println("Hello World" + "<P>");
            else
                out.println("Hello World" + "<P>");
        catch (Exception e)
            out.println("Exception: Could not display message." + "<P>");
            err.println (e.getMessage () ) ;
            out.println("<P>");
public void doPost(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException
      try
           response.setContentType("text/html"); 
           out = response.getWriter();
           err = response.getWriter();
           strName = request.getParameter("Name").trim();
           out.println("<html><head><title>");        
          out.println("</title></head><body>");
           out.println("<FORM");
           out.println("METHOD=POST");
           out.println("ACTION=http://localhost:8080/HelloWorldExample/hello.jsp>");
         out.println("<TABLE ALIGN='RIGHT'>");
         out.println("<TR>");
         out.println("<TD>");          
           out.println("<INPUT TYPE=\"SUBMIT\" VALUE=\"Hello World Page\";>");
           out.println("</INPUT>");
          out.println("</TD>");
         out.println("</TR>");
         out.println("</TABLE>");
         out.println("</FORM>");
         out.println("<BR CLEAR='all'>");
           out.println("<P>");        
           displayMessage(request, response);
           out.close();
         out.println("</body></html>");               
       catch(Throwable e)
          e.printStackTrace();
      public void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException
         doPost(request, response);
web.xml
<servlet>
      <servlet-name>HelloWorld</servlet-name>
      <servlet-class>jservlets.HelloWorld</servlet-class>
</servlet>  
<servlet-mapping>
        <servlet-name>HelloWorld</servlet-name>
        <url-pattern>/servlet/HelloWorld</url-pattern>
</servlet-mapping>      ******************************
HelloWorld.java can be compiled by using javac.
Once compiled, HelloWorld.class would be moved to the jservlets folder.
FYI, coding the above url-pattern results in:
HTTP Status 404
The requested resource (/HelloWorldExample/servlet/jservlets.HelloWorld) is not available
The following url-pattern in the web.xml file permits the servlet to be executed but results in a null pointer exception:
<servlet-mapping>
        <servlet-name>HelloWorld</servlet-name>
        <url-pattern>/ </url-pattern>
</servlet-mapping>      **************************************************
Robin

This problem was resolved.
In hello.jsp
ACTION="servlet/jservlets.HelloWorld">
was replaced with
ACTION="servlet/HelloWorld">
Robin

Similar Messages

  • How do I call a 10g report from a jsp page securly?

    How can I call a report from a jsp page securly? We are migrating from 10g forms to J2EE, and we want to keep using our reports. In forms we were able to do this using a cookie. How can I pass a users credentials to reports without the user having to connect to the database? Single Sign-on isn't an option either.
    Thanks,
    Jim

    Hi Jim,
    If you want to pass the user credentials to the report dynamically, then SSO (Single Sign-On) is the only option I can think of.
    If the user credentials can be hard-coded, then the following 2 solutions are possible:
    1. Use cgicmd.dat file, and write the user credentials in the file.
    2. In your report JSP itself, you could write the following:
    <rw:report id="report" parameters="userid=scott/tiger@mydb">
    Navneet.

  • Calling a servlet from a JSP page using the J2EE reference implementation

    I have a JSP with an include tag as follows: <jsp:include page="servlet/ConnectionServlet" flush="true" />
    When I use JRUN it works fine. I created an ear file and ported
    the application to the J2EE reference implementation. When running the app under the J2EE reference implementation the ConnectionServlet is never called. I figured it must a deployment issue. I tried adding the ConnectionServlet.class file to the WEB-INF\classes file as servlet\ConnectionServlet.class but the JSP still can't find the servlet. Any ideas where I've gone wrong? TIA, Joe

    I have a JSP with an include tag as follows:
    <jsp:include page="servlet/ConnectionServlet"
    flush="true" />Basically, WEB-INF/classes gets added to the classpath, so the directory structure under this folder should be identical to your package structure. If the ConnectionServlet.class is not actually in a package, then it should be directly in WEB-INF/classes (ie if "servlet" isn't actually the name of your package, don't use a WEB-INF/classes/servlet/" directory).
    Then try taking out the "servlet" from your include tag, so you just have page="/ConnectionServlet" (not sure about the leading slash - try experimenting!)
    if this doesn't work, try adding this to your WEB-INF/web.xml file:
    <web-app><!-- the web-app tags may already be there - don't add more -->
    <servlet>
    <servlet-name>ConnectionServlet</servlet-name>
    <servlet-class>your.full.package.here.ConnectionServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>ConnectionServlet</servlet-name>
    <url-pattern>/ConnectionServlet</url-pattern>
    </servlet-mapping>
    </web-app>
    Good Luck!

  • Opening a Java Window from a jsp page on the client side

    Hi all,
    Thanks in advance to all who could help me for this problem.
    I've written some jsp pages. In one of them, I open a new Java Window,
    which is a simple Java Frame. If I test this directly on the Tomcat
    server, everything works well.
    But when I call the jsp page through a web browser of a distant client
    (normal use), and when I want to see the java window, no window pops
    up. It appears that the Java Window pops up on the server, and not on
    the client side, which is what I wanted.
    Could someone tell me how to make the Java frames appear on the client
    side ? (Is it linked to the code or to the configuration of Tomcat ?)
    Thanks in advance,
    Alexis.

    JSP always run on the server. On the client you only see the results.
    But you can use applets on the client side: http://java.sun.com/docs/books/tutorial/uiswing/components/applet.html

  • How to call an exe program from the JSP page?

    How to call and display the interface from a exe (residing on C: drive) on my JSP page. Our customers supplied us with an exe file and they want this to be incorporated on the JSP page that has other components also, like forms, etc. The interface of the program has to be displayed in specific co-ordinates on the JSP page. Any help is highly appreciated. Thanks in advance.

    Can't be done with JSP.
    JSP runs java on the SERVER only.
    All that gets to client is an HTML page. So all that
    you can do at the client is what an HTML page can do.
    Obviously that doesn't include running a file on the
    client machine.
    Take a look into Applets, or maybe ActiveX controls.Thanks for the reply.
    Any idea on how to use the ActiveX controls in this regard?

  • How to call a class method from a jsp page?

    Hi all,
    i would like to create a basic jsp page in jdev 1013 that contains a button and a text field. When clicking the button, i would like to call a method that returns a string into the text field.
    The class could be something like this:
    public class Class1 {
    public String getResult() {
    return "Hello World";
    How do i go about this?
    Thanks

    Here is a sample:
    HTML><HEAD><TITLE>Test JDBC for Oracle Support</TITLE></HEAD><BODY>
    <%@ page import="java.sql.*, oracle.jdbc.*, oracle.jdbc.pool.OracleDataSource" %>
    <% if (request.getParameter("user")==null) { %>
    <FORM method="post" action="testjdbc.jsp">
    <H1>Enter connection Parameters</H1>
    <H5>Please enter host name:</H5><INPUT TYPE="text" name="hostname" value="localhost" />
    <H5>Please enter port number:</H5><INPUT TYPE="text" name="port" value="1521" />
    <H5>Service nanme:</H5><INPUT TYPE="text" name="service" value="XE" />
    <H5>Please enter username: </H5><INPUT TYPE="text" name="user" />
    <H5>Please enter password</H5><INPUT TYPE="password" name="password" />
    <INPUT TYPE="submit" />
    </FORM>
    <% } else { %>
    <%
    String hostName = request.getParameter("hostname");
    String portNumber = request.getParameter("port");
    String service = request.getParameter("service");
    String user = request.getParameter("user");
    String password = request.getParameter("password");
    String url = "jdbc:oracle:thin:" + user + "/" + password + "@//" + hostName + ":" + portNumber + "/" + service;
    try {
    OracleDataSource ods = new OracleDataSource();
    ods.setURL(url);
    Connection conn = ods.getConnection();
    // Create Oracle DatabaseMetaData object
    DatabaseMetaData meta = conn.getMetaData();
    // gets driver information
    out.println("<TABLE>");
    out.println("<TR><TD>");
    out.println("<B>JDBC Driver version</B>");
    out.println("</TD>");
    out.println("<TD>");
    out.println(meta.getDriverVersion());
    out.println("</TD>");
    out.println("</TR>");
    out.println("<TR><TD>");
    out.println("<B>JDBC Driver Name</B>");
    out.println("</TD>");
    out.println("<TD>");
    out.println(meta.getDriverName());
    out.println("</TD>");
    out.println("</TR>");
    out.println("<TR><TD>");
    out.println("<B>JDBC URL</B>");
    out.println("</TD>");
    out.println("<TD>");
    out.println(meta.getURL());
    out.println("</TD>");
    out.println("<TABLE>");
    conn.close();
    } catch (Exception e) {e.printStackTrace(); }
    %>
    <%-- end else if --%>
    <% } %>
    </BODY>
    </HTML>

  • Error getting values by getParameterValues() in a servlet from a jsp page

    Hi, i cant recive in my servlet the values that a user write in some input text in the next page:
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!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=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
         <form action="/ProyectoWeb/ServletPruebas" method="post">
              <table>
              <%
                   for(int i = 0; i<10; i++){
    %>
                   <tr>
                        <td>
                             <input type="hidden" name="ps_oculto" value="<%=i%>">
                             <input type="text" name="ps_valor">
                        </td>
                   </tr>
    <%
              %>
              </table>
              <input type="submit" value="VALOR">
         </form>
    </body>
    </html>and this is the post method of my servlet:
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              PrintWriter pw = response.getWriter();
              String[] pocultos= request.getParameterValues("ps_oculto");
              String[] valores= request.getParameterValues("ps_oculto");
              for(String oculto: pocultos){
                   pw.println("ps_ocultos: " + oculto);
              for(String valor: valores){
                   pw.println("ps_valores: " + valor);
              pw.flush();
              pw.close();
         }When i open the jsp page in my web server and do the sumit of its form i get the folow response of my servlet:
    ps_ocultos: 0
    ps_ocultos: 1
    ps_ocultos: 2
    ps_ocultos: 3
    ps_ocultos: 4
    ps_ocultos: 5
    ps_ocultos: 6
    ps_ocultos: 7
    ps_ocultos: 8
    ps_ocultos: 9
    valores: 0
    valores: 1
    valores: 2
    valores: 3
    valores: 4
    valores: 5
    valores: 6
    valores: 7
    valores: 8
    valores: 9
    I can´t get the values that i put in the input text when i open the jsp in my web server, (before press the submit button i write text in the input text), i only get indexes 0,1,2,3 ... What is wrong?
    Thanks in advance

    My error its on the post method. I am getting the worg parameter for the values of my input text. I have change in the doPost the line
    String[] valores= request.getParameterValues("ps_oculto");for this
    String[] valores= request.getParameterValues("ps_valores");the code run perfect. Sometimes happens ...

  • Calling my Java class from JSP page

    Hello, I am trying to call my Java class from my JSP page passing parameters to it and getting back a collection of result sets. Can someone tell me what I might be doing wrong:
    JSP code to call Java class:
    <%
    String strEssUser = "test";
    String strProcessingMonth = "JUL";
    String strProcessingYear = "2002";
    strQueryList=new ListReturn(strEssUser.toString(), strProcessingMonth.toString(), strProcessingYear.toString());
    %>
    I get this error when I try to run this JSP page using tomcat:
    C:\Program Files\Apache Tomcat 4.0\work\Standalone\localhost\em\jsp\Test_0005fSummarySBU_0005fscreen$jsp.java:77: Class org.apache.jsp.ListReturn not found.
    strQueryList=new ListReturn(strEssUser.toString(), strProcessingMonth.toString(), strProcessingYear.toString());
    I'm not sure if this problem is the way I am calling the Java class, or if I have a problem in the Java code itself. Can anyone help?

    Ok, I get a very strange error now:
    org.apache.jasper.JasperException: Unable to compile class for JSPerror: An error has occurred in the compiler; please file a bug report (http://java.sun.com/cgi-bin/bugreport.cgi).
    What is this??? Anyone?

  • Do not know how to call Servlet from a JSP???

    How do I call a Servlet from a JSP page?
    I have an JSP page that does a few things but when there is an error I need the JSP page to call a Servlet but do not know how to do it.
    I want to call a ServletFaillogin from a JSP page how can I do it?
    <html><head>
    <title> Login Page </title>
    </head>
    <body>
    <%@ page import= "portal.* " %>
    <jsp:useBean class="portal.PortalSystem" id="bean" scope="session" />
    <% try
      String servername = request.getParameter("servername");
      String username = request.getParameter("username");
      String password = request.getParameter("password");
      bean.Connect(servername, username, password);
    catch(Exception e)
       //******Here I need help *********
       action="http://localhost:8080/test/servlet/ServletFaillogin";
    %>
    <h1> You have successfully logged in. </h1>
    </body></html>

    I have changed the code but get error, why??
    I think it could be due to the way classes are located,
    All my HTML and JSP pages are at:
    C:\tomcat\jakarta-tomcat-3.3.1\webapps\myJSPs\jsp\portal-project
    The class ServletFaillogin is located here:
    C:\tomcat\jakarta-tomcat-3.3.1\webapps\myJSPs\WEB-INF\classes\portal
    What am I doing wrong, please help???
    <html><head> <title> FTP Login </title> </head>
    <body>
    <%@ page import= "portal.* " %>
    <jsp:useBean class="portal.PortalSystem" id="bean" scope="session" />
    <%      try
               String servername = request.getParameter("servername");
               String username   = request.getParameter("username");   
               String password   = request.getParameter("password");
               bean.Connect(servername, username, password);
            catch(Exception e)
               response.sendRedirect("http://localhost:8080/myJSPs/servlet/ServletFaillogin");
    %>
    <h1> You have successfully logged in. </h1>
    </body></html>

  • Problems calling Java Servlets from HTML pages Online

    Hello
    I have created a Web site using Java Servlets, and have acquired some servlet enabled web-space however i am having some difficulty in calling the actual servlets from the HTML pages i was using the line of code as follows
    http://localhost:8080/servlet/....
    followed by the name eg.
    http://localhost:8080/servlet/Login
    however this doesn't seem to be working i have also tried using the exact address of the servlet but this didn't work either
    i.e ..servlet/Login.java
    I was wondering would anyone have any idea as in how the servlets should be called
    Thanks very much

    Once you write the Servlet code, you have to compile and put the classes in the server classpath. To refer these servlets from your pages, you have to configure them in the server configuration(typical a xml file). There you define how you are going to refer to the servlet(/servlet/Logon) and the correponding class.
    -Mak

  • Calling a servlet (in Tomcat) from a JSP Page (in Apache)

    I have a web form in my JSP Page, which upon submits, will send the params to a servlet. The servlet will then process the request and send the results back to the calling JSP Page.
    with that above senario, is there any way for me to reference a servlet (resides in Tomcat) from a JSP Page (resides in Apache HTTP Server)?
    Thanks!

    Apache HTTP server isn't a servlet/JSP engine.
    Your JSP runs on Tomcat, right where the servlet does. Apache just forwards the request.
    %

  • Accessing a java class method from the jsp page.

    Hi im a beginner with jsp and im trying to find a way to access a method of my java class file in jsp page. After searching through the forums i tried to use the usebean tag. Im using apache to host the jsp file.Below is an excerpt of my code and the error message i got. What am i doing wrong? anyone know?
    <%@ page language="java" %>
    <jsp:useBean id="movies" class="movie.Movie" />
    <jsp:setProperty name="movies" property="*"/>
    <%
    movies.getStart("file:///C:/Video/Applications2/sun.mpg");
    response.setContentType("text/xml");
    %>
    exception
    org.apache.jasper.JasperException: Exception in JSP: /View.jsp:7
    4: <jsp:setProperty name="movies" property="*"/>
    5: <%
    6:
    7: movies.getStart("file:///C:/Video/Applications2/sun.mpg");
    8: response.setContentType("text/xml");
    9: %>
    Stacktrace:
         org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:504)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:375)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    root cause
    javax.servlet.ServletException: javax/media/ControllerListener

    Hi thanks for responding. Ok i did look through and it was opening some gui. I still need the program to do server side processes so cant use an applet.but i dont need the gui so i revised it and removed the gui. also im using a servlet to call the class now yet i still have the same error. Any ideas?
    Below is the vid2jpg code minus the gui.
    import java.io.*;
    import java.awt.*;
    import javax.media.*;
    import javax.media.control.*;
    import javax.media.format.*;
    import javax.media.protocol.*;
    import java.awt.image.*;
    import javax.imageio.*;
    public class vid2jpg implements ControllerListener
         Processor p;
         Object waitObj = new Object();
         boolean stateOK = true;
         DataSourceHandler handler;
    int imgWidth;int imgHeight;
         Image outputImage;
         String sep = System.getProperty("file.separator");
         int[] outvid;
         int startFr = 1;int endFr = 1000;int countFr = 0;
         boolean sunjava=true;
         * Static main method
         public static void main(String[] args)
              if(args.length == 0)
                   System.out.println("No media address.");
                   new vid2jpg("file:///C:/Video/applications2/sun.mpg");     // or alternative "vfw://0" if webcam
              else
                   String path = args[0].trim();
                   System.out.println(path);
                   new vid2jpg(path);
         * Constructor
         public vid2jpg(String path)
              MediaLocator ml;String args = path;
              if((ml = new MediaLocator(args)) == null)
                   System.out.println("Cannot build media locator from: " + args);
              if(!open(ml))
                   System.out.println("Failed to open media source");
         * Given a MediaLocator, create a processor and start
         private boolean open(MediaLocator ml)
              System.out.println("Create processor for: " + ml);
              try
                   p = Manager.createProcessor(ml);
              catch (Exception e)
                   System.out.println("Failed to create a processor from the given media source: " + e);
                   return false;
              p.addControllerListener(this);
              // Put the Processor into configured state.
              p.configure();
              if(!waitForState(p.Configured))
                   System.out.println("Failed to configure the processor.");
                   return false;
              // Get the raw output from the Processor.
              p.setContentDescriptor(new ContentDescriptor(ContentDescriptor.RAW));
              TrackControl tc[] = p.getTrackControls();
              if(tc == null)
                   System.out.println("Failed to obtain track controls from the processor.");
                   return false;
              TrackControl videoTrack = null;
              for(int i = 0; i < tc.length; i++)
                   if(tc.getFormat() instanceof VideoFormat)
                        tc[i].setFormat(new RGBFormat(null, -1, Format.byteArray, -1.0F, 24, 3, 2, 1));
                        videoTrack = tc[i];
                   else
                   tc[i].setEnabled(false);
              if(videoTrack == null)
                   System.out.println("The input media does not contain a video track.");
                   return false;
              System.out.println("Video format: " + videoTrack.getFormat());
              p.realize();
              if(!waitForState(p.Realized))
                   System.out.println("Failed to realize the processor.");
                   return false;
              // Get the output DataSource from the processor and set it to the DataSourceHandler.
              DataSource ods = p.getDataOutput();
              handler = new DataSourceHandler();
              try
                   handler.setSource(ods);     // also determines image size
              catch(IncompatibleSourceException e)
                   System.out.println("Cannot handle the output DataSource from the processor: " + ods);
                   return false;
         //     setLayout(new FlowLayout(FlowLayout.LEFT));
    //          currPanel = new imgPanel(new Dimension(imgWidth,imgHeight));
         //     add(currPanel);
         //     pack();
              //setLocation(100,100);
         //     setVisible(true);
              handler.start();
              // Prefetch the processor.
              p.prefetch();
              if(!waitForState(p.Prefetched))
                   System.out.println("Failed to prefetch the processor.");
                   return false;
              // Start the processor
              //p.setStopTime(new Time(20.00));
              p.start();
              return true;
         * Sets image size
         private void imageProfile(VideoFormat vidFormat)
              System.out.println("Push Format "+vidFormat);
              Dimension d = (vidFormat).getSize();
              System.out.println("Video frame size: "+ d.width+"x"+d.height);
              imgWidth=d.width;
              imgHeight=d.height;
         * Called on each new frame buffer
         int nextframetime = 0;
    private void useFrameData(Buffer inBuffer)
    try
    if(inBuffer.getData()!=null) // vfw://0 can deliver nulls
    if(sunjava) // and with import javax.imageio.*;
    int frametimesecs = (int)(inBuffer.getTimeStamp()/1000000000);
    if(frametimesecs%10 == 0 && frametimesecs==nextframetime)
    nextframetime+=10;
    BufferedImage bi = new BufferedImage(outputImage.getWidth(null), outputImage.getHeight(null), BufferedImage.TYPE_INT_RGB);
    Graphics g = bi.getGraphics();
    ImageIO.write(bi, "png", new File("images"+sep+"image_"+(inBuffer.getTimeStamp()/1000000000)+".png"));
    catch(Exception e){}
         * Tidy on finish
         public void tidyClose()
              handler.close();
              p.close();
         * Block until the processor has transitioned to the given state
         private boolean waitForState(int state)
              synchronized(waitObj)
                   try
                        while(p.getState() < state && stateOK)
                        waitObj.wait();
                   catch (Exception e)
              return stateOK;
         * Controller Listener.
         public void controllerUpdate(ControllerEvent evt)
              if(evt instanceof ConfigureCompleteEvent ||     evt instanceof RealizeCompleteEvent || evt instanceof PrefetchCompleteEvent)
                   synchronized(waitObj)
                        stateOK = true;
                        waitObj.notifyAll();
              else
              if(evt instanceof ResourceUnavailableEvent)
                   synchronized(waitObj)
                        stateOK = false;
                        waitObj.notifyAll();
              else
              if(evt instanceof EndOfMediaEvent || evt instanceof StopAtTimeEvent)
                   tidyClose();
         * Inner classes
         * A DataSourceHandler class to read from a DataSource and displays
         * information of each frame of data received.
         class DataSourceHandler implements BufferTransferHandler
              DataSource source;
              PullBufferStream pullStrms[] = null;
              PushBufferStream pushStrms[] = null;
              Buffer readBuffer;
              * Sets the media source this MediaHandler should use to obtain content.
              private void setSource(DataSource source) throws IncompatibleSourceException
                   // Different types of DataSources need to handled differently.
                   if(source instanceof PushBufferDataSource)
                        pushStrms = ((PushBufferDataSource) source).getStreams();
                        // Set the transfer handler to receive pushed data from the push DataSource.
                        pushStrms[0].setTransferHandler(this);
                        // Set image size
                        imageProfile((VideoFormat)pushStrms[0].getFormat());
                   else
                   if(source instanceof PullBufferDataSource)
                        System.out.println("PullBufferDataSource!");
                        // This handler only handles push buffer datasource.
                        throw new IncompatibleSourceException();
                   this.source = source;
                   readBuffer = new Buffer();
              * This will get called when there's data pushed from the PushBufferDataSource.
              public void transferData(PushBufferStream stream)
                   try
                        stream.read(readBuffer);
                   catch(Exception e)
                        System.out.println(e);
                        return;
                   // Just in case contents of data object changed by some other thread
                   Buffer inBuffer = (Buffer)(readBuffer.clone());
                   // Check for end of stream
                   if(readBuffer.isEOM())
                        System.out.println("End of stream");
                        return;
                   // Do useful stuff or wait
                   useFrameData(inBuffer);
              public void start()
                   try{source.start();}catch(Exception e){System.out.println(e);}
              public void stop()
                   try{source.stop();}catch(Exception e){System.out.println(e);}
              public void close(){stop();}
              public Object[] getControls()
                   return new Object[0];
              public Object getControl(String name)
                   return null;
    below is the servlet code.
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class ShowMovie extends HttpServlet {
    String rootURL="http://127.0.0.1:8080/Video/";
    public void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
         //String movie=request.getParameter("movie");
         String movie ="son";
         getStart(movie);
              response.sendRedirect(rootURL+"View.jsp");
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
         public void getStart(String url){
              new vid2jpg(url);
    this is the error from the server. Im using tomkat 5
    exception
    javax.servlet.ServletException: Servlet execution threw an exception
    root cause
    java.lang.NoClassDefFoundError: javax/media/ControllerListener
         java.lang.ClassLoader.defineClass1(Native Method)
         java.lang.ClassLoader.defineClass(Unknown Source)
         java.security.SecureClassLoader.defineClass(Unknown Source)
         org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:1812)
         org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:866)
         org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1319)
         org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1198)
         java.lang.ClassLoader.loadClassInternal(Unknown Source)
         ShowMovie.getStart(ShowMovie.java:31)
         ShowMovie.processRequest(ShowMovie.java:14)
         ShowMovie.doGet(ShowMovie.java:22)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    note The full stack trace of the root cause is available in the Apache Tomcat/5.5.17 logs.

  • How do I Display a string from a servlet into a JSP Page???? NEED HELP!!!!

    Hi guys,
    How do I Display a string from a servlet into a JSP Page...
    Ive tried so many bloody things!.....
    Simply.
    I get text from JSP. The servlet does what ever it does to the string.
    Now. Ive create sessions and bean things,.... how the hell do I display it in a text box... I can display on the screen.. but not in the text box.!!!
    please help!!!

    hmmm, I dont really like using JSP programming, u should be using JAVA..
    the way to do it is:
    Call and cast to the bean like this:
    <%@ page import="beans.*" %>
    <% //cast to bean get request create object
    userNameBean u= (userNameBean) request.getSession().getAttribute("userNameBean");
    then... all you do is call it like this:
    <input type="text" name="firstName" value="<%= u != null? u.getFirstName(): "" %>">
    this is the real programmers way,,,
    chet.~

  • Calling 3 different servlets from a single servlet

    hi all,
    i am in lot of soup...i am new to servlets,etc....so help me pls.
    i need to call 3 different servlets from one servlet. all 3 servlets that i want to call perform different functions and execute queries on the database.
    what i am trying to do is:
    there is an html page that call a servlet called authenticate.java.(whose code is at the bottom of this page).
    the servlet authenticate.java should authenticate a user according to the password and username supplied in the html page.
    MAINLY:-
    i need to display 3 buttons to the authenticted user. those 3 buttons each should call 3 different servlets, which do different things.
    now in authenticte.java i set certain information in the session using session.putValue();
    further, whatever servlet is called, i need to use that information i set into the session...using session.getValue().
    PLS TELL ME HOW TO DO THAT...ALSO C IF THE BELOW CODE IS OK.
    ALSO TELL ME HOW TO END A SESSION. ALSO DO SERVLETS SUPPORT SESSIONS?
    I AM USING jdk1.3 and jsdk2.0.
    * Authenticate.java
    // this places all user variables in session
    //to access use session.getAttribute
    //dispatcher stuff
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.http.HttpSession;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import java.sql.*;
    import java.io.*;
    import java.util.*;
    * @author Gudiya
    * @version
    public class Authenticate extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    HttpSession session = request.getSession(true);
    Connection con=null;
    String sessionid;
    String deptcode;
    String desig;
    String add1;
    String add2;
    String contname;
    PrintWriter out = response.getWriter();
    try
    {System.out.println(1);
    response.setContentType("text/html");
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con=DriverManager.getConnection("jdbc:odbc:SACFA","","");
    System.out.println("connection established");
    catch(ClassNotFoundException e){
    System.out.println("database driver not found");
    System.out.println(e.toString());
    catch(Exception e){System.out.println(e.toString());
    String username=request.getParameter("username");
    String password=request.getParameter("password");
    try{
    System.out.println(2);
    PreparedStatement stmt=con.prepareStatement("SELECT * FROM AUTHENTICATION,mb_add where AUTHENTICATION.NAME=? AND AUTHENTICATION.PASSWORD=? AND mb_add.DEPT_NAME=?");
    stmt.setString(1,username);
    stmt.setString(2,password);
    stmt.setString(3,username);
    ResultSet rs=stmt.executeQuery();
    System.out.println(3);
    boolean rowfound=false;
    rowfound=rs.next();
    if (rowfound==true)
    sessionid=session.getId();
    System.out.println(sessionid);
    System.out.println(4);
    session.putValue("user",username);
    rs.beforeFirst();
    while (rs.next())
    System.out.println(5);
    deptcode=rs.getString("DEPT_CODE");
    desig=rs.getString("DESIGNATION");
    add1=rs.getString("ADDRESS1");
    add2=rs.getString("ADDRESS2");
    contname=rs.getString("NAME");
    session.putValue("dept_code",deptcode);
    session.putValue("designation",desig);
    session.putValue("address1",add1);
    session.putValue("address2",add2);
    session.putValue("cont_name",contname);
    System.out.println(6);
    }          out.println("<html>");
              out.println("<head>");
              out.println("<title>Successful Login Screen</title>");
              out.println("</head>");
              out.println("<body bgcolor='ORANGE'>");
    out.println("WELCOME SACFA MEMBERS FROM "+ username);
    //print decorative html statements here
              out.println(" SELECT ANY ONE ACTION:-");
    //out.println("<form Action="+"\"servlet/noc\""+" method =post>");//call for your noc servlet
    //print decorative html statements here
    out.println("<INPUT TYPE=submit VALUE='GENERATE NOC' NAME='NOC'>");
    out.println("</form>");
    //print decorative html statements here
    //out.println("<form Action="+"\"servlet/comments\""+" method =post>");//call for your comment servlet
    out.println("<INPUT TYPE=submit VALUE='ENTER/ MODIFY COMMENTS' NAME='COMMENTS' >");
    out.println("</form>");
    //print decorative html statements here
    // out.println("<form Action="+"\"servlet/bye\""+" method = post>");
    out.println("<INPUT TYPE=submit VALUE=EXIT NAME=EXIT >"); //place javascript fucction for exiting window
    out.println("</form>");
              out.println("</body>");
              out.println("</html>");
    con.close();
    } catch( SQLException e){ }
    out.close();}
    THANK YOU,
    REGARDS,
    ASHNA

    Hi Ashna,
    You have use three different forms for three buttons. But I think all are commented one.It will also work if you uncomment it.
    Else you can use only one Form without giving action in form tag. Use normal buttons instead of submit type buttons & call different JavaScript functions on onClick event for each button.
    Try this out.
    Ajay

  • Pass the data back from the jsp page to the java code

    Hi,
    I have written an iView that receives an event using EPCF and extracts data from the client data bag.
    I need this iView to pass the data back from the jsp page to the java code.
    I am trying to do this using a hidden input field, but I cannot get the code to work.
    Here is the code on the jsp page.
    <%@ taglib uri="tagLib" prefix="hbj" %>
    <hbj:content id="myContext" >
      <hbj:page title="PageTitle">
       <hbj:form id="myFormId">
    <hbj:inputField id="myInputField" type="string" maxlength="100" value="" jsObjectNeeded="true">
    <% myInputField.setVisible(false);%>
    </hbj:inputField>      
       </hbj:form>
      </hbj:page>
    </hbj:content>
    <script language=JavaScript>
    EPCM.subscribeEvent("urn:com.peter", "namedata", window, "eventReceiver");
    function eventReceiver(eventObj) {
         var url = eventObj.dataObject;
         var funcName = htmlb_formid+"_getHtmlbElementId";
         func = window[funcName];
         var ipField = eval(func("myInputField"));
         ipField.setValue(url);
         var form = document.all(htmlb_formid);
         form.submit();
    </script> 
    Here is my java code
    package com.sap.training.portal;
    import com.sapportals.htmlb.InputField;
    import com.sapportals.htmlb.page.DynPage;
    import com.sapportals.htmlb.page.PageException;
    import com.sapportals.portal.htmlb.page.JSPDynPage;
    import com.sapportals.portal.htmlb.page.PageProcessorComponent;
    public class ListSalesOrder extends PageProcessorComponent {
      public DynPage getPage(){
        return new ListSalesOrderDynPage();
      public static class ListSalesOrderDynPage extends JSPDynPage{
         private String merong;
        public void doInitialization(){
        public void doProcessAfterInput() throws PageException {
              InputField reportfld = (InputField) getComponentByName("myInputField");
              if (reportfld != null)      merong = reportfld.getValueAsDataType().toString();
        public void doProcessBeforeOutput() throws PageException {
              if ( merong != null ) setJspName("merong.jsp");
              else setJspName("ListSalesOrder.jsp");
    Here is DD
    <?xml version="1.0" encoding="utf-8"?>
    <application>
      <application-config>
        <property name="SharingReference" value="com.sap.portal.htmlb"/>
        <property name="PrivateSharingReference" value="com.sap.portal.htmlb"/>
      </application-config>
      <components>
        <component name="SearchSalesOrder">
          <component-config>
            <property name="ComponentType" value="jspnative"/>
            <property name="JSP" value="/pagelet/SearchSalesOrder.jsp"/>
          </component-config>
          <component-profile>
            <property name="tagLib" value="/SERVICE/htmlb/taglib/htmlb.tld"/>
          </component-profile>
        </component>
        <component name="ListSalesOrder">
          <component-config>
            <property name="ClassName" value="com.sap.training.portal.ListSalesOrder"/>
          </component-config>
          <component-profile>
            <property name="tagLib" value="/SERVICE/htmlb/taglib/htmlb.tld"/>
          </component-profile>
        </component>
      </components>
      <services/>
    </application>
    After receive event, then call java script function "eventReceiver" and call "form.submit()".
    But .. PAI Logic in Java code doesn't called ...
    Where is my problme ?
    Help me ...
    Regards, Arnold.

    Hi Arnold,
    you should not do a form.submit yourself. Instead you can put a component called ExternalSubmit to your page:
    ExternalSubmit exSubmit = new ExternalSubmit("EX_SUBMIT"));
    exSubmit.setServerEventName("MyEvent");
    This results in a java script funtion on the page which is called "_htmlb_external_submit_". If you call this function the the form gets submitted and your event handler is called.
    regards,
    Martin

Maybe you are looking for