Itnitialization files with servlets

I just started reading Core Servlets and JSP. I must have missed something. The author explains the use of init files, but what is the purpose of giving values to variables in a seperate file? In the example in the book he sets a string and an integer in an init file. I can understand that you might want that if you have several servlets that use those variables as if they were global variables. I guess in that case I would understand, but can someone tell me why they are used instead of just declairing the variables inside the sevlet itself?
Thanks,
Keith

If yu declare a variable and initiliaze it with a value (hard coding) in the servlet, would you be abe to change its value without re-copmpiling the servet ?
It all about genericity and maintainability.
All such enivronmental information that can potentially change(for example development time versus deployment time) is better put into some kind of properties/configuration/init file.

Similar Messages

  • Opening files with servlet

    Okay... I'm new to using servlets. Not so much to jsp, just to using servlets. I have one process on our site that is using servlets and I'm trying to mimic how that is using em but am having no luck.
    I am trying to open files with a servlet. I have the class built and compiled, but mainly pulled it from Java World. I evenually will need to pass the servlet the filename and path I want open but in this example it has the file set. My problem is I want to send users to a jsp file where I check user authentication and call the servlet to open the doc, but I don't know how to call the servelet or what to send it. If someone could maybe walk me through this.
    Here's my servlet:
    package cmxx.fileServe;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class fileServe extends HttpServlet {
    final static String CONTENT_TYPE_DOC = "application/msword";
    final static String CONTENT_TYPE_HTML = "text/html";
    final static String document = "/docs/form_41.doc";
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    doGet(request, response);
    public void doGet (HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    PrintWriter out;
    out = response.getWriter();
    HttpSession websession = request.getSession(true);
    response.reset();
    response.setDateHeader ("Expires", 0);
    response.setDateHeader("max-age", 0);
    try {
         response.setContentType(CONTENT_TYPE_DOC);
    FileInputStream fileInputStream = new FileInputStream(document);
    ServletOutputStream servletOutputStream = response.getOutputStream();
    int bytesRead = 0;
    byte byteArray[] = new byte[4096];
    while((bytesRead = fileInputStream.read(byteArray)) != -1) {
         servletOutputStream.write(byteArray, 0, bytesRead);
    servletOutputStream.flush();
    servletOutputStream.close();
    fileInputStream.close();
    } catch(Exception ex) {
         throw new ServletException(ex.getMessage());
    } /* end doget */
    } /* end class */

    I'm trying a new servlet. But am getting a few compile errors. Can someone help?
    Here are my Errors:
    43 cannot resolve symbol
    symbol : class URL
    location: class cmis.fileServe.fileServe2
    URL url = new URL(fileURL);
    ^
    43 cannot resolve symbol
    symbol : class URL
    location: class cmis.fileServe.fileServe2
    URL url = new URL(fileURL);
    ^
    57 cannot resolve symbol
    symbol : class MalformedURLException
    location: class cmis.fileServe.fileServe2
    } catch(final MalformedURLException e) { 
    ^
    Code:
    package cmis.fileServe;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class fileServe2 extends HttpServlet {
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    ServletOutputStream out = res.getOutputStream();
    // Set the output data's mime type
    res.setContentType( "application/pdf" ); // MIME type for pdf doc
    // create an input stream from fileURL
    String fileURL = "http://www.adobe.com/aboutadobe/careeropp/pdfs/adobeapp.pdf";
    // Content-disposition header - don't open in browser and
    // set the "Save As..." filename.
    // *There is reportedly a bug in IE4.0 which  ignores this...
    res.setHeader("Content-disposition", "attachment; filename=Example.pdf" );
    // PROXY_HOST and PROXY_PORT should be your proxy host and port
    // that will let you go through the firewall without authentication.
    // Otherwise set the system properties and use URLConnection.getInputStream().
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
    URL url = new URL(fileURL);
    // Use Buffered Stream for reading/writing.
    bis = new BufferedInputStream(url.openStream());
    bos = new BufferedOutputStream(out);
    byte[] buff = new byte[2048];
    int bytesRead;
    // Simple read/write loop.
    while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
    bos.write(buff, 0, bytesRead);
    } catch(final MalformedURLException e) {
    System.out.println ( "MalformedURLException." );
    throw e;
    } catch(final IOException e) {
    System.out.println ( "IOException." );
    throw e;
    } finally {
    if (bis != null)
    bis.close();
    if (bos != null)
    bos.close();
    } /* end class */

  • Save byte array (image) to file with servlet

    Good day.
    I should must to save a png image to file.
    I have a byte array of the image.
    This work is in a servlet.
    How can I do it?
    Best regards.
    Stefano Errani

    Good day.
    I have a byte[] and then I have used
    FileOutputStream fos = new FileOutputStream(getServletContext().getRealPath("/public_html/mcfoto/foto1.png"));
    fos.write(bt, 0, bt.length); // byte[] bt
    fos.close();
    This on my web server that has public_html as root web directory.
    The server is in multi domain.
    In this mode I have an error.
    Then I have tryied to use
    FileOutputStream fos = new FileOutputStream("http://www.stefanoerrani.it/mcfoto/foto1.png");
    and
    FileOutputStream fos = new FileOutputStream(getServletContext().getRealPath("http://www.stefanoerrani.it/mcfoto/foto1.png"));
    In both ways I have obtained an error.
    At last I have tryied in my localhost (local machine) using
    FileOutputStream fos = new FileOutputStream(getServletContext().getRealPath("/mcfoto/foto1.png"));
    All run correclty.
    The Application Server is Tomcat with Apache HTTP Server.
    The first server (of www.stefanoerrani.it) has Linux as OS.
    My local server has Windows as OS.
    I should want, if it's possible, an help.
    Best regards.
    Stefano Errani

  • Generating JNLP file with servlet?

    Hi all,
    I want to pass in paramters from a hyperlink into a webstart application. Now I know this can be done with webstart 1.5, but using this is not an option for us. What I would like to do is to create a servlet that generates a JNLP file from any parameters passed into it on the hyperlink.
    Has anybody done this? Is this possible? would there be any problems with this?
    thanks,
    J

    That's running fine with us. That has been the way for us to transmit authentication information to pass inside the JNLP world.
    Be very careful with your output, there's no validation at the client and errors created by wrong JNLPs can be really unpredictable. Do use the DTD to at build time to check the output!
    The JNLP file will be downloaded every-time if you output correct headers...
    paul

  • Compiling file with servlet.jar

    Hi,
    I can compile my file under the arm/pdm package fine by using this command:
    javac -classpath .;.. pdm\FileName.java
    but now i wrote a servlet which imports the javax.servlet directory.
    So in order for the class to compile i have to give it the path of the servlet.jar file which is in this directory: c:/jdk1.3.1_07/lib/servlet.jar
    The problem am having is that i can't give both the classpaths at one time in order to compile my servlet which also uses classes in the pdm directory and also from a different directory under arm.
    Please help
    Thanks

    Perhaps
    javac -classpath .;..;c:\jdk1.3.1_07\lib\servlet.jar pdm\FileName.java

  • Help needed. Problem with servlet.

    Hello ppl. Ok. I've never really needed to implement servlets in my projects before but I experimented by writing a simple helloworld servlet. It compiled successfully and I tested it in the examples servlet dir and it worked. To test it in the ROOT dir, I placed the servlet in the ROOT/WEB-INF/classes folder and edited the web.xml file with:
    <servlet>
              <servlet-name>HelloWorldExample</servlet-name>
              <servlet-class>HelloWorldExample</servlet-class>
         </servlet>
         <servlet-mapping>
              <servlet-name>HelloWorldExample</servlet-name>
              <url-pattern>servlet/*</url-pattern>
         </servlet-mapping>
    When I try and execute the servlet by using this URL: localhost:8080/servlet/helloworld I get an internal server error and the server crashes. I removed the entry from the web.xml file and Tomcat started up again. What went wrong? Can someone enlighten me in how to get my test servlet working becuase i may use them in the future. Thanks.

    Nope, Still didnt work. As soon as I put in:
    <servlet>
         <servlet-name>HelloWorldExample</servlet-name>
         <servlet-class>HelloWorldExample</servlet-class>
         </servlet>
         <servlet-mapping>
         <servlet-name>HelloWorldExample</servlet-name>
         <url-pattern>servlet/HelloWorldExample</url-pattern>
         </servlet-mapping>
    Tomcat went offline!
    I have another entry which is:
    <servlet>
              <servlet-name>org.apache.jsp.index_jsp</servlet-name>
              <servlet-class>org.apache.jsp.index_jsp</servlet-clas
    >
         </servlet>
         <servlet-mapping>
              <servlet-name>org.apache.jsp.index_jsp</servlet-name>
              <url-pattern>/index.jsp</url-pattern>
         </servlet-mapping>
    Do you think they may be conflicting? Thanks.Tomcat going offline is quite weird. However,
    <url-pattern>/index.jsp</url-pattern>
    this is perfectly valid. Lemme ask you this: did u come up with this stuff on your own or was it generated for you by the container? It looks like it was generated upon compilation of the jsp. If that is the case it should cause any conflicts. However now if you want to invoke the servlet/jsp you must use a URL like:
    http://localhost:<PORT_NO>/index.jsp
    Cheers

  • Problem:Accessing the file system with servlets ???

    Hi...
    I have a strange problem with my servlets that run on Win2000 with Apache and 2 Tomcat instances.
    I cannot open files through servlets whereas exactly the same code lines work in local standalone java programm.
    It seems to be somehting like a rights problem...but I dont know what to do.
    thanks for any help
    here are my configuration files for Apache and Tomcat:
    Apache: *******************************************************
    ### Section 1: Global Environment
    ServerRoot "D:/Webserver_and_Applications/Apache2"
    PidFile logs/httpd.pid
    Timeout 300
    KeepAlive On
    MaxKeepAliveRequests 100
    KeepAliveTimeout 15
    <IfModule mpm_winnt.c>
    ThreadsPerChild 250
    MaxRequestsPerChild 0
    </IfModule>
    Listen 80
    LoadModule jk_module modules/mod_jk.dll
    JkWorkersFile conf/workers.properties
    JkLogFile logs/mod_jk.log
    JkLogLevel info
    LoadModule access_module modules/mod_access.so
    LoadModule actions_module modules/mod_actions.so
    LoadModule alias_module modules/mod_alias.so
    LoadModule asis_module modules/mod_asis.so
    LoadModule auth_module modules/mod_auth.so
    LoadModule autoindex_module modules/mod_autoindex.so
    LoadModule cgi_module modules/mod_cgi.so
    LoadModule dir_module modules/mod_dir.so
    LoadModule env_module modules/mod_env.so
    LoadModule imap_module modules/mod_imap.so
    LoadModule include_module modules/mod_include.so
    LoadModule isapi_module modules/mod_isapi.so
    LoadModule log_config_module modules/mod_log_config.so
    LoadModule mime_module modules/mod_mime.so
    LoadModule negotiation_module modules/mod_negotiation.so
    LoadModule setenvif_module modules/mod_setenvif.so
    LoadModule userdir_module modules/mod_userdir.so
    ### Section 2: 'Main' server configuration
    ServerAdmin [email protected]
    ServerName www.testnet.com:80
    UseCanonicalName Off
    DocumentRoot "D:/Webserver_and_Applications/root"
    JkMount /*.jsp loadbalancer
    JkMount /servlet/* loadbalancer
    <Directory />
    Options FollowSymLinks
    AllowOverride None
    </Directory>
    <Directory "D:/Webserver_and_Applications/root">
    Order allow,deny
    Allow from all
    </Directory>
    UserDir "My Documents/My Website"
    DirectoryIndex index.html index.html.var
    AccessFileName .htaccess
    <Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    </Files>
    TypesConfig conf/mime.types
    DefaultType text/plain
    <IfModule mod_mime_magic.c>
    MIMEMagicFile conf/magic
    </IfModule>
    HostnameLookups Off
    ErrorLog logs/error.log
    LogLevel warn
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common
    LogFormat "%{Referer}i -> %U" referer
    LogFormat "%{User-agent}i" agent
    CustomLog logs/access.log common
    ServerTokens Full
    ServerSignature On
    Alias /icons/ "D:/Webserver_and_Applications/Apache2/icons/"
    <Directory "D:/Webserver_and_Applications/Apache2/icons">
    Options Indexes MultiViews
    AllowOverride None
    Order allow,deny
    Allow from all
    </Directory>
    Alias /manual "D:/Webserver_and_Applications/Apache2/manual"
    <Directory "D:/Webserver_and_Applications/Apache2/manual">
    Options Indexes FollowSymLinks MultiViews IncludesNoExec
    AddOutputFilter Includes html
    AllowOverride None
    Order allow,deny
    Allow from all
    </Directory>
    ScriptAlias /cgi-bin/ "d:/webserver_and_applications/root/cgi-bin/"
    <Directory "D:/Webserver_and_Applications/root/cgi-bin/">
    AllowOverride None
    Options Indexes FollowSymLinks MultiViews
    Order allow,deny
    Allow from all
    </Directory>
    IndexOptions FancyIndexing VersionSort
    AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip
    AddIconByType (TXT,/icons/text.gif) text/*
    AddIconByType (IMG,/icons/image2.gif) image/*
    AddIconByType (SND,/icons/sound2.gif) audio/*
    AddIconByType (VID,/icons/movie.gif) video/*
    AddIcon /icons/binary.gif .bin .exe
    AddIcon /icons/binhex.gif .hqx
    AddIcon /icons/tar.gif .tar
    AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv
    AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip
    AddIcon /icons/a.gif .ps .ai .eps
    AddIcon /icons/layout.gif .html .shtml .htm .pdf
    AddIcon /icons/text.gif .txt
    AddIcon /icons/c.gif .c
    AddIcon /icons/p.gif .pl .py
    AddIcon /icons/f.gif .for
    AddIcon /icons/dvi.gif .dvi
    AddIcon /icons/uuencoded.gif .uu
    AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl
    AddIcon /icons/tex.gif .tex
    AddIcon /icons/bomb.gif core
    AddIcon /icons/back.gif ..
    AddIcon /icons/hand.right.gif README
    AddIcon /icons/folder.gif ^^DIRECTORY^^
    AddIcon /icons/blank.gif ^^BLANKICON^^
    DefaultIcon /icons/unknown.gif
    IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t
    AddEncoding x-compress Z
    AddEncoding x-gzip gz tgz
    AddLanguage da .dk
    AddLanguage nl .nl
    AddLanguage en .en
    AddLanguage et .et
    AddLanguage fr .fr
    AddLanguage de .de
    AddLanguage he .he
    AddLanguage el .el
    AddLanguage it .it
    AddLanguage ja .ja
    AddLanguage pl .po
    AddLanguage ko .ko
    AddLanguage pt .pt
    AddLanguage nn .nn
    AddLanguage no .no
    AddLanguage pt-br .pt-br
    AddLanguage ltz .ltz
    AddLanguage ca .ca
    AddLanguage es .es
    AddLanguage sv .se
    AddLanguage cz .cz
    AddLanguage ru .ru
    AddLanguage tw .tw
    AddLanguage zh-tw .tw
    AddLanguage hr .hr
    LanguagePriority en da nl et fr de el it ja ko no pl pt pt-br ltz ca es sv tw
    ForceLanguagePriority Prefer Fallback
    AddDefaultCharset ISO-8859-1
    AddCharset ISO-8859-1 .iso8859-1 .latin1
    AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen
    AddCharset ISO-8859-3 .iso8859-3 .latin3
    AddCharset ISO-8859-4 .iso8859-4 .latin4
    AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru
    AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb
    AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk
    AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb
    AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk
    AddCharset ISO-2022-JP .iso2022-jp .jis
    AddCharset ISO-2022-KR .iso2022-kr .kis
    AddCharset ISO-2022-CN .iso2022-cn .cis
    AddCharset Big5 .Big5 .big5
    AddCharset WINDOWS-1251 .cp-1251 .win-1251
    AddCharset CP866 .cp866
    AddCharset KOI8-r .koi8-r .koi8-ru
    AddCharset KOI8-ru .koi8-uk .ua
    AddCharset ISO-10646-UCS-2 .ucs2
    AddCharset ISO-10646-UCS-4 .ucs4
    AddCharset UTF-8 .utf8
    AddCharset GB2312 .gb2312 .gb
    AddCharset utf-7 .utf7
    AddCharset utf-8 .utf8
    AddCharset big5 .big5 .b5
    AddCharset EUC-TW .euc-tw
    AddCharset EUC-JP .euc-jp
    AddCharset EUC-KR .euc-kr
    AddCharset shift_jis .sjis
    AddType application/x-tar .tgz
    AddType image/x-icon .ico
    AddHandler type-map var
    BrowserMatch "Mozilla/2" nokeepalive
    BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0
    BrowserMatch "RealPlayer 4\.0" force-response-1.0
    BrowserMatch "Java/1\.0" force-response-1.0
    BrowserMatch "JDK/1\.0" force-response-1.0
    BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully
    BrowserMatch "^WebDrive" redirect-carefully
    BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully
    <IfModule mod_ssl.c>
    Include conf/ssl.conf
    </IfModule>
    ScriptAlias /php/ "d:/webserver_and_applications/php/"
    AddType application/x-httpd-php .php
    Action application/x-httpd-php "/php/php.exe"
    Tomcat:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    <Server port="11005" shutdown="SHUTDOWN" debug="0">
    <!-- Define the Tomcat Stand-Alone Service -->
    <Service name="Tomcat-Standalone">
    <!-- Define an AJP 1.3 Connector on port 11009 -->
    <Connector className="org.apache.ajp.tomcat4.Ajp13Connector"
    port="11009" minProcessors="5" maxProcessors="75"
    acceptCount="10" debug="0"/>
    <!-- Define the top level container in our container hierarchy -->
    <Engine jvmRoute="tomcat1" name="Standalone" defaultHost="localhost" debug="0">
    <!-- Global logger unless overridden at lower levels -->
    <Logger className="org.apache.catalina.logger.FileLogger"
    prefix="catalina_log." suffix=".txt"
    timestamp="true"/>
    <!-- Because this Realm is here, an instance will be shared globally -->
    <Realm className="org.apache.catalina.realm.MemoryRealm" />
    <!-- Define the default virtual host -->
    <Host name="localhost" debug="0" appBase="webapps" unpackWARs="true">
    <Valve className="org.apache.catalina.valves.AccessLogValve"
    directory="logs" prefix="localhost_access_log." suffix=".txt"
    pattern="common"/>
    <Logger className="org.apache.catalina.logger.FileLogger"
    directory="logs" prefix="localhost_log." suffix=".txt"
         timestamp="true"/>
    <!-- Tomcat Root Context -->
    <Context path="" docBase="d:/webserver_and_applications/root" debug="0"/>
    <!-- Tomcat Manager Context -->
    <Context path="/manager" docBase="manager"
    debug="0" privileged="true"/>
    <Context path="/examples" docBase="examples" debug="0"
    reloadable="true" crossContext="true">
    <Logger className="org.apache.catalina.logger.FileLogger"
    prefix="localhost_examples_log." suffix=".txt"
         timestamp="true"/>
    <Ejb name="ejb/EmplRecord" type="Entity"
    home="com.wombat.empl.EmployeeRecordHome"
    remote="com.wombat.empl.EmployeeRecord"/>
    <Environment name="maxExemptions" type="java.lang.Integer"
    value="15"/>
    <Parameter name="context.param.name" value="context.param.value"
    override="false"/>
    <Resource name="jdbc/EmployeeAppDb" auth="SERVLET"
    type="javax.sql.DataSource"/>
    <ResourceParams name="jdbc/EmployeeAppDb">
    <parameter><name>user</name><value>sa</value></parameter>
    <parameter><name>password</name><value></value></parameter>
    <parameter><name>driverClassName</name>
    <value>org.hsql.jdbcDriver</value></parameter>
    <parameter><name>driverName</name>
    <value>jdbc:HypersonicSQL:database</value></parameter>
    </ResourceParams>
    <Resource name="mail/Session" auth="Container"
    type="javax.mail.Session"/>
    <ResourceParams name="mail/Session">
    <parameter>
    <name>mail.smtp.host</name>
    <value>localhost</value>
    </parameter>
    </ResourceParams>
    </Context>
    </Host>
    </Engine>
    </Service>
    <!-- Define an Apache-Connector Service -->
    <Service name="Tomcat-Apache">
    <Engine className="org.apache.catalina.connector.warp.WarpEngine"
    name="Apache" debug="0">
    <Logger className="org.apache.catalina.logger.FileLogger"
    prefix="apache_log." suffix=".txt"
    timestamp="true"/>
    </Engine>
    </Service>
    </Server>
    *** and here is my workers.properties : *******************************
    # workers.properties
    # In Unix, we use forward slashes:
    ps=/
    # list the workers by name
    worker.list=tomcat1, tomcat2, loadbalancer
    # First tomcat server
    worker.tomcat1.port=11009
    worker.tomcat1.host=localhost
    worker.tomcat1.type=ajp13
    # Specify the size of the open connection cache.
    #worker.tomcat1.cachesize
    # Specifies the load balance factor when used with
    # a load balancing worker.
    # Note:
    # ----> lbfactor must be > 0
    # ----> Low lbfactor means less work done by the worker.
    worker.tomcat1.lbfactor=100
    # Second tomcat server
    worker.tomcat2.port=12009
    worker.tomcat2.host=localhost
    worker.tomcat2.type=ajp13
    # Specify the size of the open connection cache.
    #worker.tomcat2.cachesize
    # Specifies the load balance factor when used with
    # a load balancing worker.
    # Note:
    # ----> lbfactor must be > 0
    # ----> Low lbfactor means less work done by the worker.
    worker.tomcat2.lbfactor=100
    # Load Balancer worker
    # The loadbalancer (type lb) worker performs weighted round-robin
    # load balancing with sticky sessions.
    # Note:
    # ----> If a worker dies, the load balancer will check its state
    # once in a while. Until then all work is redirected to peer
    # worker.
    worker.loadbalancer.type=lb
    worker.loadbalancer.balanced_workers=tomcat1, tomcat2
    # END workers.properties
    thanks again

    Hi joshman,
    no I didn't get error messages as the relevant lines for reading/writing where between try statements, but you were where right it was/is just a simple path problem.
    I expected the refering directory without using a path to be the directory where the servlet is in, but it is not !!??
    Do you know if I set this in the setclasspath.bat of tomcat ?
    *** set JAVA_ENDORSED_DIRS=%BASEDIR%\bin;%BASEDIR%\common\lib ***
    thanks again
    Huma

  • File Download with Servlet

    In my application i have to download a file with the help of servlet.
    Everything works fine except the case where i want to open the dialog box or just let that file open in the browser.
    For e.g. when i am trying to download an excel file and i want to have a dialog box open for save, it doesnt does that but automatically open the file in browser.
    But for the above case if i dont set the "ContentType" as "application/vnd.ms-excel" then it works fine like it will open a dialog box if in the header the value of "Content-Disposition" has "attachment;" and will open it if it has "inline;"
    Could you guide me to some good study material on what can be issues or the fundamentals of setting the "fileName with extension", what if i dont set "ContentType" and what is the difference between "Attachment" and "Inline"
    Thanks

    actually youre using the trick most ppl use.. force the content type to be something else than the ms-excel..
    the content type is ment to be a guide to the browser on how to interprete the content..
    if it doesnt it will prompt you to download i.e. show the file save dialog..

  • How to open a ".doc" file with ms word directly with this servlet?

    Here is a servlet for opening a word or a excel or a powerpoint or a pdf file,but I don't want the "file download" dialog appear,eg:when i using this servlet to open a word file,i want open the ".doc" file with ms word directly,not in IE or save.
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    public class OpenWord extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request,response);
    public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException {
    String strFileName = req.getParameter("filename");
    int len = 0;
    String strFileType1 = "application/msword";
    String strFileType2 = "application/vnd.ms-excel";
    String strFileType3 = "application/vnd.ms-powerpoint";
    String strFileType4 = "application/pdf";
    String strFileType = "";
    if(strFileName != null) {
         len = strFileName.length();
         if(strFileName.substring(len-3,len).equalsIgnoreCase("doc")) {
              strFileType = strFileType1;
         } else if(strFileName.substring(len-3,len).equalsIgnoreCase("xls")) {
              strFileType = strFileType2;
         } else if(strFileName.substring(len-3,len).equalsIgnoreCase("ppt")) {
              strFileType = strFileType3;
         } else if(strFileName.substring(len-3,len).equalsIgnoreCase("pdf")) {
              strFileType = strFileType4;
         } else {
              strFileType = strFileType1;
    if(strFileName != null) {
         ServletOutputStream out = res.getOutputStream();
         res.setContentType(strFileType); // MIME type for word doc
    //if uncomment below sentence,the "file download" dialog will appear twice.
         //res.setHeader("Content-disposition","attachment;filename="+strFileName);
         BufferedInputStream bis = null;
         BufferedOutputStream bos = null;
         String path = "d:\\"; //put a word or a excel file here,eg a.doc
         try {
         File f = new File(path.concat(strFileName));
         FileInputStream fis = new FileInputStream(f);
         bis = new BufferedInputStream(fis);
         bos = new BufferedOutputStream(out);
         byte[] buff = new byte[2048];
         int bytesRead;
         while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
         bos.write(buff, 0, bytesRead);
         } catch(NullPointerException e) {
         System.out.println ( "NullPointerException." );
         throw e;
         } catch(FileNotFoundException e) {
         System.out.println ( "FileNotFoundException." );
         throw e;
         } catch(final IOException e) {
         System.out.println ( "IOException." );
         throw e;
         } finally {
         if (bis != null)
         bis.close();
         if (bos != null)
         bos.close();

    Hello!
    Does some one of you had open a MS word file (.doc) in Java search for a token like [aToken] replace it with another text and then feed it to a stream of save it?
    I want to build a servlet to open a well formatted and rich on media (images) ms word document search for tokens and replace them with information form a web form.
    Any Ideas?
    Thank you in advanced.

  • Downloading PDF file with a servlet

    I'm working on a web application that dynamicaly creates a PDF file and then writes each character to the ServletOutputStream. Ideally, the browser is supposed to recognize the "application/pdf" MIME type and force the file to be downloaded (or opened from current location if the user should choose). When I test it on my local system, the file downloads but it uses the servlet as the file name. On my webserver I get the following problems.
    1) On all the browsers I've tested (except Internet Explorer), the output is being printed in ASCII to the display which keeps the file from downloading. Internet Explorer is the only browser that will actually download the file.
    2) When it does attempt to download the file, it is creating a file with the servlet as the name as opposed to the filename that I am assigning during creation.
    I've been reading all the related posts that I could find in these Forums but haven't been able to find a solution. If anybody has any ideas, I would greatly appreciate your knowledge. Please note that I have set up MIME-mapping for the PDF extension in the WEB.XML file on my web server.
    Here is some servlet code that handles the PDF creation and download:
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    InputStream in = null;
    ServletOutputStream out = null;
    String dir = "/www/mydirectory/";
    try {
    // Create the PDF file and retrieve the filename
    String filename = PDFCreator.main();
    //Flush the response stream and then reset it for writing a PDF to the display
    response.reset();
    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment; filename="+filename);
    out = response.getOutputStream();
    in = new BufferedInputStream( new FileInputStream(dir+filename));
    int ch;
    while ( (ch = in.read()) != -1 ) {
    out.print( (char)ch );
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    if( in != null ) {
    in.close();
    if( out != null ) {
    out.flush();
    out.close();

    Your code looks correct.
    Apparently other people too have been having problems with pdf's. These links may help you solve the problem.
    http://forum.java.sun.com/thread.jsp?forum=54&thread=100793
    http://forum.java.sun.com/thread.jsp?forum=33&thread=250668
    http://forum.java.sun.com/thread.jsp?forum=33&thread=63282
    Redirecting may not be a good idea due to url hacking. Streaming the output would be the best way to go.

  • Displaying *.pdf file on browser with servlet

    hi all
    this RAMESH,struggling to display a pdf file on browser from a remote mechine
    earlier i tried with servlet
    response.setContentenType("application/pdf")
    out.println();
    by this i am getting only some data as below
    endobj
    4 0 obj
    <<
    /ProcSet [ /PDF /Text /ImageB ]
    /Font << /Fo0 21 0 R /Fo12 24 0 R /Fo13 27 0 R /Fo16 30 0 R /Fo18 33 0 R /Fo19 36 0 R >>
    >>
    endobj
    For this purpose i have gone thru www.lowagie.com
    and gone thru all examples but i am not getting how to display on browser or at least awt frame
    please requesting all for suggest me some way
    tanks all
    -Ramesh

    are you trying to
    a) create a PDF dynamically
    b) send an existing PDF

  • Opening a file with its filename from a servlet- avoid buffer to cach files

    Hi,
    I am building an URL with the following code and calling that particular file from this servlet using request dispatcher. When I am geting alcCode from getParameter method then it is not caching the pages
    but when I am geting the same through a session value it starts caching the page after cirtain number of requests and shows up the previously requested file.
    I guess it is because it always names the file with the package name.
    for example if my package is sree then the file opened is named as
    sree[1].pdf. Please help me solve this problem
    alcCode = req.getParameter("alcList");
    HttpSession userSession= req.getSession(false);//if request is from //submit action from a FORM
    String alcCode;
    alcCode = req.getParameter("alcList");
    System.out.println("request.getparameter alcCode "+alcCode);
    if (alcCode==null){
    alcCode= (String) userSession.getValue("alcCode");
    //else get the alc code from the session that has been stored
    Calendar todaysDate=Calendar.getInstance();
    int selectMonth=todaysDate.get(Calendar.MONTH);
    int selectYear=todaysDate.get(Calendar.YEAR);
    if(selectMonth <10)
    //selectMonth = InvoiceDate.substring(1,i-8);
    urlPdf="/reports/RPTS"+selectYear+"0"+selectMonth+"/PDF-FORMAT/E"+selectYear+"0"+selectMonth+"_"+alcCode+".PDF";
    }else{
    urlPdf="/reports/RPTS"+selectYear+selectMonth+"/PDF-FORMAT/E"+selectYear+selectMonth+"_"+alcCode+".PDF";
    res.setContentType("application/pdf");
    res.reset();
    res.resetBuffer();
    res.setHeader("Content-disposition","attachment; filename" +urlPdf );
    System.out.println(urlPdf);
    try{
    ServletContext sc = getServletContext();
    RequestDispatcher rd = sc.getRequestDispatcher(urlPdf);
    rd.forward(req, res);
    Thanks in advance.
    -Sreekanth Varidhireddy                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    I had a similar problem when I used the attachment argument to the Content-Disposition header.
    try replacing this:
    res.setHeader("Content-disposition","attachment; filename" +urlPdf );
    with this:
    res.setHeader("Content-Disposition","inline; filename=" +urlPdf );
    /Niklas

  • Display text file in servlet with preserved formatting(newlines, etc)

    how do i display a text file in servlet, but all the blanks and newlines are preserved.
    this is what i did:
    RandomAccessFile text = new RandomAccessFile("D:/FYP/tempMessage.txt","r");
    long length = text.length();
    byte[] bytes = new byte[(int)length];
    //Read in the bytes
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length
    && (numRead=deCiphered.read(bytes, offset, bytes.length-offset)) >= 0) {
    offset += numRead;
    // Close the input stream and return bytes
    text.close();
    String plainText=new String(bytes);
    //display in servlet
    pw.println("<center>Plain text: " + plainText + "</center>");
    the problem here is the newlines are seem to be omitted when they're displayed in a web browser, rendering the displayed text in a mess.
    any help are greatly appreciated. thanks in advance :)

    display text in between <pre></pre> tags.
    or display it inside a text area,dont worry abt the text area border, u can change that using style sheets.

  • Generaating new doc file with jsp servlet.

    Hi friends,
    I developed an application with JSP
    In that i need a data to be fetched nd write in .doc file.
    I mean I want to create new word file nd get my data in that
    like reports generation.
    How can i make this.
    help me pls

    .doc file: I don't think there is any reporting tool that creates .doc. You can create .rtf files with Oracle Reports and many other tools.

  • Upload multiple files WITH correct pairs of form fields into Database

    In my form page, I would like to allow 3 files upload and 3 corresponding text fields, so that the filename and text description can be saved in database table in correct pair. Like this:
    INSERT INTO table1 (filename,desc) VALUES('photo1.jpg','happy day');
    INSERT INTO table1 (filename,desc) VALUES('photo2.jpg','fire camp');
    INSERT INTO table1 (filename,desc) VALUES('photo3.jpg','christmas night');
    However, using the commons fileupload, http://commons.apache.org/fileupload/, I don't know how to reconstruct my codes so that I can acheieve this result.
    if(item.isFormField()){
    }else{
    }I seems to be restricted from this structure.
    The jsp form page
    <input type="text" name="description1" value="" />
    <input type="file" name="sourcefile" value="" />
    <input type="text" name="description2" value="" />
    <input type="file" name="sourcefile" value="" />The Servlet file
    package Upload;
    import sql.*;
    import user.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.Map;
    import java.util.HashMap;
    import java.util.Date;
    import java.util.List;
    import java.util.Iterator;
    import java.io.File;
    import java.io.PrintWriter;
    import java.io.IOException;
    import java.text.SimpleDateFormat;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.*;
    public class UploadFile extends HttpServlet {
    private String fs;
    private String category = null;
    private String realpath = null;
    public String imagepath = null;
    public PrintWriter out;
    private Map<String, String> formfield = new HashMap<String, String>();
      //Initialize global variables
      public void init(ServletConfig config, ServletContext context) throws ServletException {
        super.init(config);
      //Process the HTTP Post request
      public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        Thumbnail thumb = new Thumbnail();
        fs = System.getProperty("file.separator");
        this.SetImagePath();
         boolean isMultipart = ServletFileUpload.isMultipartContent(request);
         if(!isMultipart){
          out.print("not multiple part.");
         }else{
             FileItemFactory factory = new DiskFileItemFactory();
             ServletFileUpload upload = new ServletFileUpload(factory);
             List items = null;
             try{
                items = upload.parseRequest(request);
             } catch (FileUploadException e) {
                e.printStackTrace();
             Iterator itr = items.iterator();
             while (itr.hasNext()) {
               FileItem item = (FileItem) itr.next();
               if(item.isFormField()){
                  String formvalue = new String(item.getString().getBytes("ISO-8859-1"), "utf-8");
                  formfield.put(item.getFieldName(),formvalue);
                  out.println("Normal Form Field, ParaName:" + item.getFieldName() + ", ParaValue: " + formvalue + "<br/>");
               }else{
                 String itemName = item.getName();
                 String filename = GetTodayDate() + "-" + itemName;
                 try{
                   new File(this.imagepath + formfield.get("category")).mkdirs();
                   new File(this.imagepath + formfield.get("category")+fs+"thumbnails").mkdirs();
                   //Save the file to the destination path
                   File savedFile = new File(this.imagepath + formfield.get("category") + fs + filename);
                   item.write(savedFile);
                   thumb.Process(this.imagepath + formfield.get("category") +fs+ filename,this.imagepath + formfield.get("category") +fs+ "thumbnails" +fs+ filename, 25, 100);
                   DBConnection db = new DBConnection();
                   String sql = "SELECT id from category where name = '"+formfield.get("category")+"'";
                   db.SelectQuery(sql);
                    while(db.rs.next()){
                      int cat_id = db.rs.getInt("id");
                      sql = "INSERT INTO file (cat_id,filename,description) VALUES ("+cat_id+",'"+filename+"','"+formfield.get("description")+"')";
                      out.println(sql);
                      db.RunQuery(sql);
                 } catch (Exception e){
                    e.printStackTrace();
            HttpSession session = request.getSession();
            UserData k = (UserData)session.getAttribute("userdata");
            k.setMessage("File Upload successfully");
            response.sendRedirect("./Upload.jsp");
      //Get today date, it is a test, actually the current date can be retrieved from SQL
      public String GetTodayDate(){
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String today = format.format(new Date());
        return today;
      //Set the current RealPath which the file calls for this file
      public void SetRealPath(){
        this.realpath = getServletConfig().getServletContext().getRealPath("/");
      public void SetImagePath(){
        this.SetRealPath();
        this.imagepath = this.realpath + "images" +fs;
    }Can anyone give me some code suggestion? Thx.

    When one hits the submit button - I then get a 404 page error.What is the apaches(?) error log saying? Mostly you get very useful information when looking into the error log!
    In any case you may look at how you are Uploading Multiple Files with mod_plsql.

Maybe you are looking for

  • PDF document inline view  Issue with Chrome

    I am facing an issue with the below procedure which should fetch and display PDF document in the browser. It displays properly on IE 9. But no luck in Chrome. Shows junk. What am I missing? Meanwhile report BLOB column link inline download is working

  • Video not included in web gallery

    I imported a collection of photos and videos. The videos appear in the library, but not in the web module. Is there a way to include these videos in the exported web gallery? If Lightroom does not support this directly, are there any web tutorials th

  • CRASH WHEN WAKING FROM HIBERNATION / DEEP SLEEP

    Hi All, 2011 Macbook Pro 15", OS 10.6.8, 750GB Western Digital Black 7200rpm, 16GB RAM I have searched and found several different discussions regarding this issue. When the battery gets low the OS forces a system hibernation / deep sleep. Once you c

  • MINUTES:SECONDS to decimal time, (MINUTES.SECONDS)

    I want to be able to convert "colon time" (28:45) minutes:seconds to "decimal time" (28.75). I have resorted to a work-around: put minutes in one column, seconds in a second column, convert the minutes to seconds, add the two seconds columns, divide

  • Converting from Excel to Adobe PDF

    I have Adobe Acrobat 7.0 Professional and Windows XP. The excel worksheet is on a landscape page and reduced to say 65%. It has wording on the left side that stretches through five cells. Some of the wording gets cut off. Maybe the last letter gets c