New to Servlet

Hi all,
How to read a file from a Servelt and display the contents of that file?
Thanks
Sreenivas

well, it's not that tricky :
1) read your file. Assuming you now the path to the file you wanna read, just do something like :
File f=new File("yourpath");
BufferedReader in =new BufferedReader(new FileInputStream(f));
StringBuffer data=new StringBuffer();
// do a loop that read your file and accumulate the data in the data variable
// see java.io.BufferedInputStream javadoc
// using a StringBuffer is not mandatory, but it's better when accumulating String chunk that simply doing
// string=string+otherString
content=data.toString();NB: you can also look the IO section in the commons package from the jakarta project, they have a class that do read a file to a String, without the loop mess : http://jakarta.apache.org/commons/io/
2) output it
now you have a String named content that old the content of your file, you can send out as a response.
To achieve this, get the writer from the response objet you'll get as a parameter in the doGet/doPut/service (whatever servlet method you use), and writes your data in it :
response.getWriter().write(content);
3) optimize : the backdraft of this way of doing things is that you load the whole file into memory (and it ma be a big file. A better way of doing things would be to output the data as soon as you have read it from the file, and drop the StringBuffer use.
String line;
PrintWriter out=response.getWriter();
while ((line=in.readline()) !=null) {
      out.write(line);

Similar Messages

  • New to Servlet Technology

    Hi,
    i am new to servlets. Can anyone tell me how can i compile and run a java servlet. ie what do i need i mean application servers and webservers.
    Thanks in advance
    byee

    hi anansmithi,
    Thanks for the reply
    i have installed Tomcat 5.5.4 on my system and its working fine. i have written a small servlet program
    can you tell me how how can i compile and run a servet using tomcat 5.5.4
    thanks in advance
    byeee

  • Help! New to Servlets.

    Hi,
    I am kind of new to servlets.
    I have developed an application in Java using JAI which displays multipage tiff images. But i would like to create a servlet which does the same thing. If anybody has any documents or examples on Servlets which displays images, I would appreciate if they can post it or e-mail me at [email protected]
    Thanks In advance.
    Sam

    first, a servlet ist not able to display an image directly. all a servlet can to (to the client) is to send a html. but as as you sure know it's easy to place an image tag in the html that points to the image. if the image already exists everything is already done. if oyu need to create the imgae severside just build a special command in the url that lets the servlet know it has to send a special image (you pass the needed parameters in the url). then you send the picture information back. make sure that you set the right header information, specialy the right content-type so the browser realizes that it's a picutre you are sending.

  • New to servlet  http status 404 ::((((

    Hello
    I am writeing my first servlet and have problem to run it using Tomcat.
    How???
    In webapps i made new folder in folder i made web-inf folder in that folder i made classes folder and put web.xml.
    In adress bar i put localhost:8080/name_folder_in_webapps/servlet/Name_of_my_clas
    Is it good?
    what i should do if it is not??
    Thank in advance.

    This is what I do:
    In web.xml:
    <servlet>
    <servlet-name>servletname</servlet-name>
    <servlet-class>servletclassname</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>servletname</servlet-name>
    <url-pattern>/servletname</url-pattern>
    </servlet-mapping>
    Then I use a url without "servlet":
    http://localhost:8080/name_folder_in_webapps/servletname

  • ## NEW XSQL Servlet 0.9.9.1 OUT TODAY ##

    The new release of XSQL Pages and the XSQL Servlet is out today here on OTN. For complete information on what's new, and a much-improved "how to install" section, see:
    http://technet.oracle.com/tech/xml/xsql_servlet/htdocs/relnotes.htm
    The brand-new, unified demo, on-line help system is also staged on the live server at:
    http://technet.oracle.com/tech/xml/demo/demo1.htm
    and is included in the release. It's all built using XSQL Pages and XSLT stylesheets.
    Lot's of new features and enhancements based squarely on all of YOUR feedback, here on the OTN XML Forum.
    Keep the questions and suggestions coming.

    Richard,
    I have just applied patch to upgrade from Portal 3.0.9 to 3.0.9.8.1 (Patch applied to loginserver and portal schema) and the External Applications that were previously set up have gone from the portlet.
    Does this relate to your note at the bottom:
    "Minor issues with Bulk action. 1840420 CUSTOM WRITTEN EXTERNAL AUTH MODULE NEED TO BE UPDATED AFTER 3.0.9 UPGRADE SSOXOID.PKB DOESN'T LOAD.
    External authentication modules that were written before 3.0.9 need to be updated after upgrading to 3.0.9. ssoauthx.pks is updated in 3.0.9 and contains additional routines that need to be implemented." ??
    If I go to the "Login Server Administration" portlet and select the link "Administer External Applications" I get a list of 5 External Applications that have previously been set up.
    If I go back to the Home Page and select "customize" on the "External Applications" portlet I get the message "Your Login Server administrator has not registered any external applications".
    Does that mean I should just run 'ssoauthx.pks' & 'ssoxoid.pkb' or do I need to do something else ??
    Thanks
    Simo

  • New to Servlet - Existing html doc

    I created a new servlet and have an existing html doc. How do I connect the doc to the servlet so that it will send request to the servlet.
    In the html file I have the following code.
    <form action = "/servlet/TEDServicesDatabrowserServlet" method = "post" name ="myName">
    I place the follow in the web.xml file
    <servlet>
    <servlet-name>TEDServicesDatabrowserServlet</servlet-name>
    <servlet-class>mil.navy.nrlssc.dmap.TEDServices.TEDSServer.TEDServicesDatabrowserServlet</servlet-class>
    <init-param>
         <param-name>WorkingDirectory</param-name>
    <param-value>C:\tedsservletworkingdirectory</param-value>
    </init-param>
    <init-param>
         <param-name>ScratchDirectory</param-name>
         <param-value>c:\apache\htdocs\mapb</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    </servlet>
    It is not responsing to any request I make. What to do!

    Hello
    A sample web.xml file is attached for your reference.
    <?xml version="1.0" encoding="UTF-8"?>
    <!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 id="WebApp">
         <display-name>Web</display-name>
         <filter>
              <filter-name>RedirectFilter</filter-name>
              <display-name>RedirectFilter</display-name>
              <filter-class>test.RedirectFilter</filter-class>
         </filter>
         <filter-mapping>
              <filter-name>RedirectFilter</filter-name>
              <url-pattern>/ResourceLookupServlet</url-pattern>
         </filter-mapping>
         <filter-mapping>
              <filter-name>RedirectFilter</filter-name>
              <servlet-name>ResourceLookupServlet</servlet-name>
         </filter-mapping>
         <servlet>
              <servlet-name>action</servlet-name>
              <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
              <init-param>
                   <param-name>config</param-name>
                   <param-value>WEB-INF/struts-config.xml</param-value>
              </init-param>
              <init-param>
                   <param-name>debug</param-name>
                   <param-value>2</param-value>
              </init-param>
              <init-param>
                   <param-name>detail</param-name>
                   <param-value>2</param-value>
              </init-param>
              <init-param>
                   <param-name>validate</param-name>
                   <param-value>true</param-value>
              </init-param>
              <load-on-startup>2</load-on-startup>
         </servlet>
         <servlet>
              <servlet-name>ResourceLookupServlet</servlet-name>
              <display-name>ResourceLookupServlet</display-name>
              <servlet-class>test.ResourceLookupServlet</servlet-class>
         </servlet>
         <servlet-mapping>
              <servlet-name>action</servlet-name>
              <url-pattern>*.do</url-pattern>
         </servlet-mapping>
         <servlet-mapping>
              <servlet-name>ResourceLookupServlet</servlet-name>
              <url-pattern>/ResourceLookupServlet</url-pattern>
         </servlet-mapping>
         <welcome-file-list>
              <welcome-file>index.html</welcome-file>
              <welcome-file>index.htm</welcome-file>
              <welcome-file>index.jsp</welcome-file>
              <welcome-file>default.html</welcome-file>
              <welcome-file>default.htm</welcome-file>
              <welcome-file>default.jsp</welcome-file>
         </welcome-file-list>
         <taglib>
              <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
              <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
         </taglib>
         <taglib>
              <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
              <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
         </taglib>
         <taglib>
              <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
              <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
         </taglib>
         <taglib>
              <taglib-uri>/WEB-INF/struts-nested.tld</taglib-uri>
              <taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
         </taglib>
         <taglib>
              <taglib-uri>/WEB-INF/struts-template.tld</taglib-uri>
              <taglib-location>/WEB-INF/struts-template.tld</taglib-location>
         </taglib>
         <taglib>
              <taglib-uri>/WEB-INF/struts-tiles.tld</taglib-uri>
              <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
         </taglib>
    </web-app>
    You are missing the servlet mapping tag. The servlet mapping tag maps the servlet name with a url pattern, so that the web server can understand which servlet to call.
    In your html form specify this url-mapping
    HTH
    VJ

  • Whats new in Servlet 2.4 (j2ee 1.4) ?

    I've downloaded this servlet 2.4 spec pdf (final version). Its a 330 page document. How do I find out whats new (compared to servlet 2.3) ?
    Thanks in advance :)
    -a.

    thud! (that was my hand hitting my forehead :) should have found it myself.
    Thanks I got it now.
    -a.

  • New to servlets - Is this a good design?

    I would like to create a web app whereby a user pastes large amounts of text (thousands of words) into a text field, then to have the text transformed and sent back and displayed to the user. To transform the text, a memory intensive model is required (currently it ranges between 500-1000mb). Therefore with my understanding I will have an html form send the text via post to an httpservlet. The servlet itself will read the data pertaining to the model (via database or file) and construct the model once during the servlet initialization stage. Then the servlet will transform the text and send it as a response to display it on a new html page for every request while the servlet is alive.
    My main concern is the life cycle of a servlet. If the servlet is not handling requests because there are no requests to handle, from my understanding the servlet will terminate. Then later on when a request does come through, a new instance of the servlet will be created. Therefore I am worried that the model to transform the text will need to be reconstructed. I'm worried because this involves large amounts of data and can take thousands of milliseconds to construct.
    My desired solution is to have the model that transforms the text constructed once, somewhere on the server for the servlet to query, preferably inside the servlet itself.
    Hopefully someone can clarify this for me and comment on my broad approach.
    Thanks

    user11105060 wrote:
    I will restate my problem since it's not exactly clear in the previous message.
    I want an HttpServlet to process text sent to it from an html form and then display this on a subsequent form. The issue confronting me is that I have to create a memory intensive object (model) that is fairly time consuming to create, before I can process the text. The fortunate thing is that the object (model) is always the same and never changes, therefore I only ever need to construct it once to process any text.
    I would like to know if it is possible to construct this model once and only once for the HttpServet that will use it to process the text, or do I have no control over this? That is, if the httpservlet is created then destroyed then recreated, will I have to reconstruct the model again? Is it possible to keep this model in memory and pass it to the httpservlet constructor as a parameter?
    If the question is not clear, could someone please say so.
    Thank you.So you need your model object to basically only exist once in the entire application, right?
    Seems like you found a reason to use a singleton.

  • [b]can I use servlets for Chat? new to servlets[/b]

    I want to a chat application for someprof and students
    I am using multicasting technique to send and receive messages
    I used applets and created it but applets don't support java.net's MulticastSocket so I used certificate
    Now I want to use servlets for this in JSP because I called applets from JSP
    Can it be possible? If yes please clearify.

    it is possible
    you could create a jsp page that would update like 10 or 20 or whatever number of ServletContext attributes.
    in the jsp_service or in the doPost or doGet method of a servlet:
    String messageFromUser=request.getParameter("msg");
    int num=15;
    String[] chat=new String[num];
    chat[0]=getServletContext().setAttribute("chatLine" + 0, messageFromUser);
    for(int i=1; i<num; i++) {
        String previousMessage=getServletContext().getAttribute("chatLine" + (i-1));
        chat=getServletContext().setAttribute("chatLine" + i, previousMessage);
    out.println(chat[i]);
    however, there is a pretty decent client/server chat program that can run as an applet here:
    http://planetsourcecode.com/vb/scripts/ShowCode.asp?txtCodeId=4397&lngWId=2

  • New to Servlets

    there is no bin folder in jswdk that i have downloaded. so how do i host my servlet cause i cant trace teh servletrunner as the tutorial suggests !!??
    anyone for help please.
    thanks

    i tried running the Httpservlet from the command line
    and i keep getting exeptions that has sumtin to do
    with main(). but there is no main() in the code. is it
    possible to run the Httpservlet from the command line?
    and how do i actually run the Httpservlet with
    tomcat?
    thanx in advance!!!as far as i know, you cant do that. Correct me if i am wrong. As others guys mentioned before, go to http://www.moreservlets.com There got all the basics you need to get started, esp. the nice instruction about install Tomcat 4 or 5. It looks like a bit overwhelming and confusing when you read those insturctions at the very first time, particuarly when you are really new to this area. But dont worry, they are not rocket science. just make yourself calm down, have a cup of java, read and follow through these instructions carefully, then you would get it down. Feel free to ask any more questions.
    Hope it helps.

  • New to servlets... Where to start?

    I want to start writing simple JSP or Servlet that displays data that I get from a class.
    How do I do it? where do I start to learn these subjects?

    You might want to start with the Java tutorial which is available here under the Docs & Training section.
    Buying a good book on servlets like Java Servlet Programming by Jason Hunter will get you up to speed faster.
    Silvio Bierman

  • New with Servlets - please help

    Hello:
    I am using JDev to work with JSPs/Servlets .Can someone please direct me how to setup JDev to work with JSPs and Servlets.
    Question 1: I downloaded JDev Full Version which said that it included JDK1.5 . But I don't know where it installed it. I just unzip the folder. Do I have to install JDK differently?
    Q2: Using Tomcat Application Server - it asked to locate the folder where JRE is installed . Where can I get that info.
    Q3 : How to setup Servlets so that I can load a servlet file in the browser. I created a "Hello World" app using Servlets but I can't load it .
    I will appreciate you help.
    THanks

    user517625,
    First, for your information, Tomcat is a servlet container, not an application server. Second, Oracle JDeveloper includes an [embedded] application server: OC4J. So you don't really need Tomcat if you only want to create and test some servlets and JSPs. JDeveloper includes extensive "help" information and sample code that shows you how to create servlets and JSPs.
    Good Luck,
    Avi.

  • Get all values from multi select in a servlet

    Hello,
    I have a multi <select> element in a HTML form and I need to retrieve the values of ALL selected options of this <select> element in a servlet.
    HTML code snippet
    <select name="elName" id="elName" multiple="multiple">
    Servlet code snippet
    response.setContentType("text/html");
    PrintWriter out = null;
    out = response.getWriter();
    String output = "";
    String[] str = request.getParameterValues("elName");
    for(String s : str) {
    output += s + ":";
    output = output.substring(0, output.length()-1); // cut off last deliminator
    out.println(output);But even when selecting multiple options, the returned text only ever contains the value of the first selected option in the <select>
    What am I doing wrong? I'm fairly new to servlets
    Edited by: Irish_Fred on Feb 4, 2010 12:43 PM
    Edited by: Irish_Fred on Feb 4, 2010 12:44 PM
    Edited by: Irish_Fred on Feb 4, 2010 2:14 PM
    Edited by: Irish_Fred on Feb 4, 2010 2:26 PM
    Edited by: Irish_Fred on Feb 4, 2010 2:26 PM
    Edited by: Irish_Fred on Feb 4, 2010 2:32 PM

    I am using AJAX.
    I will show you how I'm submitting the <select> values by showing you the flow of code:
    This is the HTML code for the <select> tag and the button that sends the form data:
    <form name="formMain" id="formMain" method="POST">
         <input type="button" id="addOpts" name="addOpts" value="Add Options" style="width:auto; visibility:hidden" onClick="jsObj.addOptions('servletName', document.getElementById('elName'))">
         <br>
         <select name="elName" id="elName" multiple="multiple" size="1" onChange="jsObj.checkSelected()">
              <option value="0"> - - - - - - - - - - - - - - - - </option>
         </select>
    </form>Note that the "visibility:hidden" part of the button style is set to "visible" when at least one option is selected
    Note that "jsObj" relates to a java script object that has been created when the web app starts ( The .js file is included in the .jsp <head> tag )
    The following code is taken from the file: "jsObj.js"
    jsObj = new jsObj();
    function jsObj() {
    //=================================================
         this.addOptions = function(url, elName) {
              var theForm = document.getElementById('formMain');          
              if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
                   xmlhttp=new XMLHttpRequest();
              } else { // code for IE6, IE5
                   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
              url += this.buildQueryString(theForm.name);
              xmlhttp.open("POST",url,true);
              xmlhttp.send(null);
              xmlhttp.onreadystatechange=function() {
                   if(xmlhttp.readyState==4) { // 4 = The request is complete
                        alert(xmlhttp.responseText);
    //=================================================
    this.buildQueryString = function(formName) {
              var theForm = document.forms[formName];
              var qs = '';
              for (var i=0; i<theForm.elements.length; i++) {
                   if (theForm.elements.name!='') {
                        qs+=(qs=='')? '?' : '&';
                        qs+=theForm.elements[i].name+'='+escape(theForm.elements[i].value);
              return qs;
         //=================================================
    }And this is a code snippet from the "servletName" servlet:public synchronized void doGet(HttpServletRequest request,
              HttpServletResponse response) throws ServletException,IOException {
              PrintWriter out = null;
              try {
                   response.setContentType("text/html");
                   out = response.getWriter();
                   String output = "";
                   String[] values = request.getParameterValues("elName");
                   for(String s : values) {
                        output += s + ":";
                   output = output.substring(0, output.length()-1); // cut off last delimitor
                   out.println(output);
                   } catch (Exception e) {
         }So anyway, everthing compiles / works, except for the fact that I'm only getting back the first selected <option> in the 'elName' <select> tag whenever I select multiple options
    Edited by: Irish_Fred on Feb 7, 2010 10:53 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Servlet Response Problem

    Hello all,
    My simple servlet takes in a URL as a parameter and the uses the httpUrlConnection method to retrieve that page. It then just writes the html to the browser in the hope that it would be displayed as if retrieved directly.
    Although the source of a page retrieved in this way is identicle to the expected source, no images appear. I think (guess) this is because the address of a page retrieved in this way will not be the same as if retrieved normally. This, in turn, messes up the relative file paths. e.g www.mypage.com becomes something like http://localhost/httpProxyServer?URL=http%3A%2F%2Fwww.mypage.com (httpProxyServer is the name of the servlet).
    To get to the point, idoes anyone know if there is a way i can set the address of the returned page to be as if retrieved directly? I have looked in to response headers with little luck although i am very new to servlets. Thanks for any tips or advice.
    Christie

    This question can be better answered if you point out the need to examine each response before actually sending it out to the browser. What exactly do you look for in the response ? Do you compress it / transform it / parse it ?
    Having said that, you could use filters to meet any of your above needs.
    1. The first obvious gain is that it is a standard, widely accepted and part of the j2ee specification. As you said, it provides modularity and resuability of code. Somebody who goes through your work would easily pick up the trail, comprehend concisely the effort and the ends you attempt to achieve. You would have implicit server support (more of this later)
    2. You use a servlet that intercepts each request. It then uses a HttpURLConnection to get the response from each resource. As you can see straight away, this essentially makes it two requests per request - the original request goes to your general purpose servlet; then the general purpose Servlet(GPS hereafter) makes the url connection to the resource, its a brand new request. The original request may have lots of params coming in which have to be reconstructed by the GPS and included in the call to the resource which delivers the actual response back to the GPS. Hope you begin to see the pitfalls here (for example imagine the incoming stream is a byte stream resulting from a file upload)
    **in short** the 'simple servlet' is going to get very very complex as your application grows.
    3. All the above rerouting (even if you manage to achieve it successfully) will take its toll on the performance measured in terms of the response time.
    4. In established MVC2 framework like Struts or JSF, the Servlet that intercepts every request is a Controller Servlet (which knows how to handle the request, which validations to perform, which beans to invoke and so on). Your GPS should in addition to examining responses, do all this stuff or else you would end up with multiple Controllers making your app quite unwieldy.
    5. Using filters, you could side step all the above which in itself is a huge advantage (me thinks :)) besides providing a standard way to implement tasks similar to yours. I mentioned implicit server support, right ? Filters are supported by all standard j2ee web severs. You neednt write a single line of code to have your filter modify the response. All you have to write is the actual modification algorithm. However the path you choose, you would have to manually do all the dirty work of transferring the request to the actual resource (using HttpUrlConnection). You should receive each request params and convey that to the resource being accessed and so on. (see #2 above)
    Hope all that helps.
    cheers,
    ram.

  • Setting up a servlet in iis

    Hello all
    I am new to servlets and my particular questions deals with setup. I have xp pro (iis 5.o) and I was wondering can I just install jre and put the servlet class on the server. I guess if someone can give a thought on that then I would be real appreciative

    I think IIS is a webserver only. You need to have some App Server or some servlet engine to be coupled with IIS. Try to get JRun/ Servlet Exec.

Maybe you are looking for