How to include a servlet in JSP ?

Hi,
Would you please to teach me how I can include a servlet class in JSP ?
Would you please to teach me and give me a simple example ?
My purpose is that I want to use Template model, but I want to show an Image file(that is in the dabase) in JSP.
I use that servlet to read an image in database and show it in the web using JSP.
Please teach me.
Best regards,
Eric

Hiya,
What you're doing is pretty simple and doesn't even require JSP. Just source the SRC tag of <IMAGE> to the servlet, like this:
<IMG SRC="/servlet" WIDTH="x" HEIGHT="y">
And you're done.
Of course, the servlet has to first set the correct response type and return the image for this to work.
Hope this helps,
-ike, .si

Similar Messages

  • How to Include a servlet in a jsp

    Hello,
    My jsp pages are all tied to respective Servlets. So when I have to forward to a jsp, I forward to a servelt which redirects to that jsp.
    Now I have a jsp page which has to include another jsp page.
    So I am trying to include a servlet in my jsp page which inturn redirects itself to the included jsp.
    Have tried doing the following
    <jsp:include page="../../servlet/ServletName" flush="true">
    </jsp:include>
    does not work. It compiles well but no output
    any ideas ????
    ~ Soumya

    It does not seem to work... Let me give you the snippet of code I used.
    calendarEntry.java - the parent jsp
    <tr rowspan="60%">
    <td width="100%">
         <jsp:include page="file://c:/../../servlet/MonthEventList">
         </jsp:include>
    </td>
    </tr>
    MonthEventList.java - the included servlet
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class MonthEventList extends HttpServlet {
         * Attributes
         private static final String CONTENT_TYPE = "text/html";
         private HttpSession session;
         public void init() throws ServletException
         public void doPost(HttpServletRequest request,
    HttpServletResponse response) throws
    ServletException, IOException
              try {     
              HttpSession session = request.getSession(true);
              String url;
         url = "/jsp/site/calendar/monthEventList.jsp";
                        //ReDirect to where the page is going
                        response.sendRedirect(url);
                        return;
              } catch (Exception ex) {
              String url="/jsp/site/calendar/main/servletError.jsp;
         response.sendRedirect(url);
              return;
         public void doGet(HttpServletRequest request,HttpServletResponse
    response) throws ServletException, IOException
              doPost(request, response);
    monthEventList.jsp
    just displays some dummy data
    So if this is the case, do you think the <jsp:include> can work ??
    Thanks in advance
    Soumya

  • How to include external files in JSP

    hi,
    How to include external files like image or javascript in to jsp pages.
    I am using MVC frame work. So i have to use request dispatcher. While calling the pages trough dispatcher the external files are missing from the output. Also am using tomcat as server,web.xml(deployment descriptor ) is also configured.
    regards
    sree

    When you use the request dispatcher, the relative path for all your ressources becomes the relative path of your calling serlvet and not the JSP/servlet that you call. Make sure to use the full relative path such as:
    /PATH_TO_YOUR_DIRECTORY/myRessource.ext
    NOT
    SOME_DIRECTORY/myRessource.ext
    Jeff

  • How to convert this Servlet into JSP

    I am trying to convert this Servlet into JSP page.
    How do I go about doing this?
    Thanks.
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import java.text.*;
    /** Shows all items currently in ShoppingCart. Clients
    * have their own session that keeps track of which
    * ShoppingCart is theirs. If this is their first visit
    * to the order page, a new shopping cart is created.
    * Usually, people come to this page by way of a page
    * showing catalog entries, so this page adds an additional
    * item to the shopping cart. But users can also
    * bookmark this page, access it from their history list,
    * or be sent back to it by clicking on the "Update Order"
    * button after changing the number of items ordered.
    * <P>
    * Taken from Core Servlets and JavaServer Pages 2nd Edition
    * from Prentice Hall and Sun Microsystems Press,
    * http://www.coreservlets.com/.
    * &copy; 2003 Marty Hall; may be freely used or adapted.
    public class OrderPage extends HttpServlet {
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    HttpSession session = request.getSession();
    ShoppingCart cart;
    synchronized(session) {
    cart = (ShoppingCart)session.getAttribute("shoppingCart");
    // New visitors get a fresh shopping cart.
    // Previous visitors keep using their existing cart.
    if (cart == null) {
    cart = new ShoppingCart();
    session.setAttribute("shoppingCart", cart);
    String itemID = request.getParameter("itemID");
    if (itemID != null) {
    String numItemsString =
    request.getParameter("numItems");
    if (numItemsString == null) {
    // If request specified an ID but no number,
    // then customers came here via an "Add Item to Cart"
    // button on a catalog page.
    cart.addItem(itemID);
    } else {
    // If request specified an ID and number, then
    // customers came here via an "Update Order" button
    // after changing the number of items in order.
    // Note that specifying a number of 0 results
    // in item being deleted from cart.
    int numItems;
    try {
    numItems = Integer.parseInt(numItemsString);
    } catch(NumberFormatException nfe) {
    numItems = 1;
    cart.setNumOrdered(itemID, numItems);
    // Whether or not the customer changed the order, show
    // order status.
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Status of Your Order";
    String docType =
    "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
    "Transitional//EN\">\n";
    out.println(docType +
    "<HTML>\n" +
    "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
    "<BODY BGCOLOR=\"#FDF5E6\">\n" +
    "<H1 ALIGN=\"CENTER\">" + title + "</H1>");
    synchronized(session) {
    List itemsOrdered = cart.getItemsOrdered();
    if (itemsOrdered.size() == 0) {
    out.println("<H2><I>No items in your cart...</I></H2>");
    } else {
    // If there is at least one item in cart, show table
    // of items ordered.
    out.println
    ("<TABLE BORDER=1 ALIGN=\"CENTER\">\n" +
    "<TR BGCOLOR=\"#FFAD00\">\n" +
    " <TH>Item ID<TH>Description\n" +
    " <TH>Unit Cost<TH>Number<TH>Total Cost");
    ItemOrder order;
    // Rounds to two decimal places, inserts dollar
    // sign (or other currency symbol), etc., as
    // appropriate in current Locale.
    NumberFormat formatter =
    NumberFormat.getCurrencyInstance();
    // For each entry in shopping cart, make
    // table row showing ID, description, per-item
    // cost, number ordered, and total cost.
    // Put number ordered in textfield that user
    // can change, with "Update Order" button next
    // to it, which resubmits to this same page
    // but specifying a different number of items.
    for(int i=0; i<itemsOrdered.size(); i++) {
    order = (ItemOrder)itemsOrdered.get(i);
    out.println
    ("<TR>\n" +
    " <TD>" + order.getItemID() + "\n" +
    " <TD>" + order.getShortDescription() + "\n" +
    " <TD>" +
    formatter.format(order.getUnitCost()) + "\n" +
    " <TD>" +
    "<FORM>\n" + // Submit to current URL
    "<INPUT TYPE=\"HIDDEN\" NAME=\"itemID\"\n" +
    " VALUE=\"" + order.getItemID() + "\">\n" +
    "<INPUT TYPE=\"TEXT\" NAME=\"numItems\"\n" +
    " SIZE=3 VALUE=\"" +
    order.getNumItems() + "\">\n" +
    "<SMALL>\n" +
    "<INPUT TYPE=\"SUBMIT\"\n "+
    " VALUE=\"Update Order\">\n" +
    "</SMALL>\n" +
    "</FORM>\n" +
    " <TD>" +
    formatter.format(order.getTotalCost()));
    String checkoutURL =
    response.encodeURL("../Checkout.html");
    // "Proceed to Checkout" button below table
    out.println
    ("</TABLE>\n" +
    "<FORM ACTION=\"" + checkoutURL + "\">\n" +
    "<BIG><CENTER>\n" +
    "<INPUT TYPE=\"SUBMIT\"\n" +
    " VALUE=\"Proceed to Checkout\">\n" +
    "</CENTER></BIG></FORM>");
    out.println("</BODY></HTML>");
    }

    Sorry.
    actually this is my coding on the bottom.
    Pleease disregard my previous coding. I got the different one.
    My first approach is using <% %> around the whole doGet method such as:
    <%
    String[] ids = { "hall001", "hall002" };
    setItems(ids);
    setTitle("All-Time Best Computer Books");
    out.println("<HR>\n</BODY></HTML>");
    %>
    I am not sure how to break between code between
    return;
    and
    response.setContentType("text/html");
    Here is my coding:
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException
         String[] ids = { "hall001", "hall002" };
         setItems(ids);
         setTitle("All-Time Best Computer Books");
    if (items == null) {
    response.sendError(response.SC_NOT_FOUND,
    "Missing Items.");
    return;
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String docType =
    "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
    "Transitional//EN\">\n";
    out.println(docType +
    "<HTML>\n" +
    "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
    "<BODY BGCOLOR=\"#FDF5E6\">\n" +
    "<H1 ALIGN=\"CENTER\">" + title + "</H1>");
    CatalogItem item;
    for(int i=0; i<items.length; i++) {
    out.println("<HR>");
    item = items;
    if (item == null) {
    out.println("<FONT COLOR=\"RED\">" +
    "Unknown item ID " + itemIDs[i] +
    "</FONT>");
    } else {
    out.println();
    String formURL =
    "/servlet/coreservlets.OrderPage";
    formURL = response.encodeURL(formURL);
    out.println
    ("<FORM ACTION=\"" + formURL + "\">\n" +
    "<INPUT TYPE=\"HIDDEN\" NAME=\"itemID\" " +
    " VALUE=\"" + item.getItemID() + "\">\n" +
    "<H2>" + item.getShortDescription() +
    " ($" + item.getCost() + ")</H2>\n" +
    item.getLongDescription() + "\n" +
    "<P>\n<CENTER>\n" +
    "<INPUT TYPE=\"SUBMIT\" " +
    "VALUE=\"Add to Shopping Cart\">\n" +
    "</CENTER>\n<P>\n</FORM>");
    out.println("<HR>\n</BODY></HTML>");

  • How to include HTML file in JSP using HTML elements or Javascript?

    Hi,
    I have around 15000 static html files one for each item which we display each upon invoking an item.The HTML file should be part of a JSP file.
    Please note that the name of the HTML file is determined dynamically
    Placing all the HTML files within the web application does not give us good performance so i would like to put all of them in the webserver.
    I am not able to include the file in the JSP using the jsp:include attribute if i place the HTML files in the webserver ,
    in order to do that i think should use either HTML element or javascript to include the HTML in the JSP.is there any alternative to <Jsp:include>
    Does anyone have an idea how to include the HTML file and take advan tage of webserver?
    Any ideas are appreciated

    What you need to do is simply read the HTML file from the disk and dump it out to the outputstream. It really is that simple.
    There's no reason you need to include all 15000 files in the actual WAR, you can place those files any place handy that is easy for the application to see (in another directory, or accessible from a file server if you have multiple front ends).
    Then, just write a utiility function that takes the output stream (i.e. the 'out' JSP variable), and the file name, read the file, and write it to the stream.
    If you start noticing performance issues, then you can try doing some caching, but truth is your OS should be doing that for you.
    But, truth be told that's the only practical way to do it.
    Another solution would be to use JavaScriipt and XMLHttpRequest (i.e "AJAX") to load the file at the client side, and simply replace a tag with the results.
    That's also pretty trivial to write, any web site talking about AJAX should give you hint there.
    Of course, that won't work for folks who have JavaScript turned off, or some other incompatible browser, whereas the server side solution obviously works everywhere.

  • How to include .js file in jsp file?

    hi,
    i have a jsp file with struts tag. right now i have all the javascript code as a separate function inside the jsp file itself. i want the javascript code to be present in a .js file and i want to refer that .js file from the jsp file with struts tags.
    <html:text property="Phone" value="" size="3" maxlength="3"
         onkeyup="return autoTab(this, 3, event);"></html:text>
    the above is the html tag which will call the function "autoTab" of the .js file. please help.
    thanks,
    Jayanth.

    You include javascript into a jsp in exactly the same way you do with html
    <script src="myJavascriptFile.js"/>
    It has nothing to do with the jsp per se, but rather the generated HTML page.

  • Newbie question : How to call a servlet from JSP?

    my web.xml
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <!DOCTYPE web-app
        PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app>
      <display-name>Test</display-name>
      <description>
         Test
      </description>
    <servlet>
            <servlet-name>Test1</servlet-name>
            <servlet-class>Test1</servlet-class>
        </servlet>
        <servlet-mapping>
           <servlet-name>Test1</servlet-name>
           <url-pattern>/test1</url-pattern>
        </servlet-mapping>
         <security-constraint>
          <web-resource-collection>
             <web-resource-name>Protected Group</web-resource-name>
          <!-- Define the context-relative URL(s) to be protected -->
             <url-pattern>/jsp/security/protected/*</url-pattern>
          <!-- If you list http methods, only those methods are protected -->
          <http-method>DELETE</http-method>
             <http-method>GET</http-method>
             <http-method>POST</http-method>
          <http-method>PUT</http-method>
          </web-resource-collection>
          <auth-constraint>
             <!-- Anyone with one of the listed roles may access this group -->
             <role-name>tomcat</role-name>
          <role-name>role1</role-name>
          </auth-constraint>
        </security-constraint>
        <!-- Default login configuration uses BASIC authentication -->
        <login-config>
          <auth-method>BASIC</auth-method>
          <realm-name>Example Basic Authentication Group</realm-name>
        </login-config>
    </web-app>my index.html
    <html>
    <body>
    <a href="/test1">test</a>
    </body>
    </html>I put my Test1.class in ../WEB-INF/classes.
    When I click the link for test1, I got the following message
    HTTP Status 404 - /test1
    type Status report
    message /test1
    description The requested resource (/test1) is not available.
    Apache Tomcat/4.1.18-LE-jdk14please help. thanks

    Hi,
    You have not said if your servlet is in a package in which case which one.
    you need to add the '/servlet/' to the href so it becomes
    '/servlet/test1'.
    Phil

  • How to include a file in jsp!

    I need dynamic inlude a jsp file by use inlude file �B

    Use
    <%@ include file="file.jsp" %>
    which works at translation time so your file can be a jsp file or use
    <jsp:include page="relative url" flush="true" />
    which works at request time so the file can't contain JSP.

  • How to include .css file into jsp file in portal application

    Hi,
    I have included a .css file in a .jsp file using following tag :
    <link rel="<%=componentRequest.getWebResourcePath()%>/css/ts.css">.
    I have kept .css file under /dist/css folder.
    Preview of jsp file is fine but when I upload the jsp file and .css file to server, Look and feel of the screen is changing. When I paste the style code in jsp file, look and feel is fine.
    Can some body suggest me that why the look and feel is changing when I put the style code in css file and include it in jsp.
    Thanks in advance.
    Manish

    Hello
    We're using <link rel="stylesheet" type="text/css" href="http://ourserver/eclib/css/ecstandard.css">
    between <head> and </head>
    It works.
    Hope it helps.
    Regards
    Benoit

  • How to include CSS file in JSP

    Hi Experts,
    CSS file availabe in server. I need user that CSS in one of PDK application.
    Example: "/usr/sap/ED1/JC03/j2ee/cluster/server0/apps/sap.com/irj/servlet_jsp/irj/root/portalapps/style1.css"
    I need to include this in one of JSP file.
    Regards,
    Satya.

    You would have to place the file in the project folder of your PDK application and give a relative or absolute path to it.
    <link rel="stylesheet" type="text/css" href="path_to_your_css_file" />
    Thanks,
    GLM

  • How to Upload in Servlet or JSP with JavaBean?

    Anybody used to be familiar with these techs?I want to implement a function of upload files.Can you help me with some suggestions?

    Hi,
    This might help you
    read the file and upload to database
    Read that file using java.io.
    File f= new File("give the file name");
    FileInputStream fis= new FileInputStream(f);
    byte[] data= null;
    Vector tempVector = new Vector();
    int tempInt=fis.read();
    while(tempInt!=-1){
    tempVector.add(new Byte((byte)tempInt));
    tempInt=fis.read();
    data= new byte[tempVector.size()];
    for(int k=0;k<tempVector.size();k++){
    data[k]=new Byte(tempVector.get(k).toString()).byteValue();
    System.out.println("The byte[] data is : " +data);
    stmt= conn.prepareStatement("insert into <tableName>(blobValue, key) values ( ? , ? ) " );
    stmt.setObject(1,data);
    stmt.setString(2,"filename");
    stmt.executeUpdate();

  • How to include servlet in JSP using Include Directive?

    Hi experts,
    am a beginner to JSP.. I want to know,
    is it possible to include a servlet in jsp using include directive? could any one explain me...

    No it is not possible.
    Include directive is like copying and pasting some text into a JSP file, and then translating/compiling it.
    So the only thing you can include with the <%@ include %> directive is a jsp fragment
    It is a static translation/compile time include and thus will always be the same
    By contrast <jsp:include> is a runtime include, and includes the result of running the imported url.
    That URL has to be a complete/standalone jsp/servlet/whatever. However as it is runtime, it can take parameters where the include directive can not.
    Does that answer your homework question?
    Cheers,
    evnafets

  • Can I include a servlet in a jsp page?

    Is there anyway to include a Servlet in JSP page?

    What exactly do you want to achieve? And are you using 'include' in the generic sense or in the [JEE sense|http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/RequestDispatcher.html#include(javax.servlet.ServletRequest,%20javax.servlet.ServletResponse)]?
    By the way, behind the scenes, a JSP gets compiled into a servlet.
    Edited by: nogoodatcoding on May 18, 2009 9:50 AM

  • How to invoke the servlet

    how to invoke a servlet using jsp
    containing JSF components
    how can we do this using creator ?
    having sucessfully executed the examples
    still dont know how to do it
    and also jsp source is quite different than normal jsp
    it doesnt allow jsp tags such as
    <%= "asdf"%>any help is great to me
    thanks in advance !
    cheers,
    shekar

    and also jsp source is quite different than normal
    jsp
    it doesnt allow jsp tags such as
    <%= "asdf"%>
    This is jsp syntax -- JSC uses jsf...:-(
    Regards,
    - D.t.O

  • How include a Servlet into a JSP page?

    Hi!!
    I need make a combobox with a servlet and place its result into a jsp page.
    The servlet is in a package, but when i do: <jsp:include file="sic.view.servlet.ComboServlet" />
    tell me that "file attribute isn�t a valid attribute name"
    whow can i do to make the combobox whit the servlet and include this into the jsp page??
    Thanks!!
    PD: Sorry my pour English...

    Servlets should be mapped to a URL, then you access the servlet via that URL.
    The servlet mapping is done in the web.xml (in WEB-INF/ directory of your web application)
      <servlet>
        <servlet-name>
          Combo_S
        </servlet-name>
        <servlet-class>
          sic.view.servlet.ComboServlet
        </servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>
          Combo_S
        </servlet-name>
        <url-pattern>
          /combo
        </url-pattern>
      </servlet-mapping>Then you would use:
    <jsp:include file="combo" />
    to include it.
    Make sure the class file gets put in the right package under WEB-INF/classes/

Maybe you are looking for

  • How can I make multi-'pushViewController' for severals for buutons?

    Hey all, I'm pretty new on Obj-C programing, and I'm learning from Stanford's videos courses. Right now, I'm 'playing' with the navigation option. I use this action: [Code] - (IBAction)pushViewController:(id)sender{} [Code] In order to connect, in IB

  • Old Headphones don't fit iphone

    I have a pair of Sennheiser PX 100 headphones which I had been using with my ipod video. But they don't fit the iphone jack. Are there adaptors out there for this sort of problem.

  • Funny issue while making calls in my lumia 900

    So a strange issue popped up after the 7.8 upgrade to my Lumia 900 (I waited till all issues seemed to be resolved before applying it). Anytime I try calling a number that is not in my contacts- I just get a call ended message. The call just doesnot

  • 10.1.0.2.0 to 10.2.0.1.0 upgrade

    Hi, I couldn't find similar post, so decided to write: 1. Is it possible to upgrade Oracle 10.1.0.2.0 to 10.2.0.1.0? 2. If so, can you provide links for downloading appropriate files? 3. If so, are there required any additional, special actions to up

  • ValuePattern.SetValue Throws ElementNotAvailableException (Inner Exception of InvalidOperationException)

    I have a Wpf FrameworkElement derived control that offers a custom AutomationPeer: using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Automation.Peers; using System.Windows.Automation.Provide