Reading afile using servlet

hi
i have to read a file using servlet.
thanks,
Jasmeen

servletContext doesn't seems to return request dispather successfully. Try following:
RequestDispatcher rd =
request.getRequestDispatcher(url);
if (rd != null)
     rd.forward(request, response);

Similar Messages

  • How to read a file using servlet

    hi ,
    i've to read a file using servlet ,
    should read the file using servlet and display it in JSP,Could anybody get me how can i do it .
    Shiva

    To do that you need to get the response output stream and write yur file contents to that.
    response.setContentType(mimeType); //Set the mime type for the response
    ServletOutputStream sos = resp.getOutputStream();
    sos.write(bytes from your file input stream);
    sos.close();

  • Open Jasper Report in new page using servlet

    Guys,
    Looks very simple but i am having problem making this process work. I am using 11.1.1.4
    This is my use case:
    - From a employee page, user clicks on a menu item to open report for current employee. I need to pass appropriate report parameters to servlet and open report into new page.
    I can successfully call servlet using commandmenuitem and set request parameters and call servlet from backing bean.... but that doesn't open report in a new page.... any way i can do this?
    Another option i tried was that using gomenuitem and setting target=blank but in that case i need to pass the parameter using servlet url which i like to avoid.(in case i need to pass many parameters in future) (also values will be set on page so i need to generate url when then click the menuitem...... so there are some hoops and loops i need to go through) I don't know a way to pass the request parameter using backing bean to servlet... i don't think it is possible.
    Those are the two approaches i tried.
    If you have any better approach...I would appreciate if you can let me know. (i have searched on internet for two days now.... for the solution)
    -R
    Edited by: polo on Dec 13, 2011 7:22 AM

    Hi,
    Hope following will useful
    http://sameh-nassar.blogspot.com/2009/10/using-jasper-reports-with-jdeveloper.html
    http://www.gebs.ro/blog/oracle/jasper-reports-in-adf/

  • How to define target window when redirecting within frames using servlet?

    Howdy:
    Is there a way to define target window when redirecting within frames using servlets?
    How to do it in JSP as well?
    T.I.A.
    Oriental Spirit

    Your servlet (or JSP) can't decide where it is going to be displayed. The browser has already decided that when it makes the request to your servlet.

  • How do i call the method in a class using servlet

    i am doing a project which need to use servlet to call a few methods in a class and display those method on the broswer. i tried to write the servlet myself but there are still some errors .. can anyone help:
    The servlet i wrote :
    package qm.minipas;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class test extends HttpServlet {
    Database database;
    /** Initializes the servlet.
    public void init(ServletConfig config) throws ServletException {
    super.init(config);
    database = FlatfileDatabase.getInstance();
    /** Destroys the servlet.
    public void destroy() {
    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
    * @param request servlet request
    * @param response servlet response
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("this is my class wossname"+FlatfileDatabase.getInstance()); // this is calling the toString() method in the instance of myJavaClass
    out.println("this is my method"+FlatfileDatabase.getAll());
    out.println("</body>");
    out.println("</html>");
    out.close();
    /** Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    processRequest(request, response);
    /** Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    processRequest(request, response);
    /** Returns a short description of the servlet.
    public String getServletInfo() {
    return "Short description";
    my methods which i need to call are shown below:
    public Collection getAll() {
    return Collections.unmodifiableCollection(patientRecords);
    public Collection getInpatients() {
    Collection selection=new ArrayList();
    synchronized(patientRecords) {
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    if(next.isInpatient())
    selection.add(next);
    return Collections.unmodifiableCollection(selection);
    public Collection getByAdmissionDate(Date dateOfAdmission) {
    List selection=new ArrayList();
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    if(dateOfAdmission.equals(next.getDateOfAdmission()))
    selection.add(next);
    return Collections.unmodifiableCollection(selection);
    public Collection getByAdmissionDates(Date from,Date to)
    throws IllegalArgumentException {
    if(to.before(from))
    throw new IllegalArgumentException("End date must not be before start date");
    List selection=new ArrayList();
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    Date nextAD=next.getDateOfAdmission();
    if((nextAD.after(from)||nextAD.equals(from))
    &&(nextAD.before(to)||nextAD.equals(to)))
    selection.add(next);
    return Collections.unmodifiableCollection(selection);
    public Collection getByDischargeDates(Date from,Date to)
    throws IllegalArgumentException {
    if(to.before(from))
    throw new IllegalArgumentException("End date must not be before start date");
    List selection=new ArrayList();
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    Date nextAD=next.getDateOfDischarge();
    if(nextAD==null)
    continue;
    if((nextAD.after(from)||nextAD.equals(from))
    &&(nextAD.before(to)||nextAD.equals(to)))
    selection.add(next);
    return Collections.unmodifiableCollection(selection);
    public Collection getByConsultant(String consultant) {
    List selection=new ArrayList();
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    if(consultant.equalsIgnoreCase(next.getConsultant()))
    selection.add(next);
    return Collections.unmodifiableCollection(selection);
    public Collection getByDischargeDate(Date dateOfDischarge) {
    List selection=new ArrayList();
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    if(dateOfDischarge.equals(next.getDateOfDischarge()))
    selection.add(next);
    return Collections.unmodifiableCollection(selection);
    public Collection getBySurname(String surname) {
    List selection=new ArrayList();
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    if(surname.equalsIgnoreCase(next.getSurname()))
    selection.add(next);
    return Collections.unmodifiableCollection(selection);
    public Collection getByWard(String ward) {
    List selection=new ArrayList();
    for(Iterator i=patientRecords.iterator(); i.hasNext();) {
    PatientRecord next=(PatientRecord) i.next();
    if(ward.equalsIgnoreCase(next.getWard()))
    selection.add(next);
    return Collections.unmodifiableCollection(selection);

    please provide a detail description of your errors.

  • Uploading a file to server using servlet (Without using Jakarta Commons)

    Hi,
    I was trying to upload a file to server using servlet, but i need to do that without the help of anyother API packages like Jakarta Commons Upload. If any class for retrieval is necessary, how can i write my own code to upload from client machine?.
    From
    Velu

    <p>Why put such a restriction on the solution? Whats wrong about using that library?
    The uploading bit is easy - you put a <input type="file"> component on the form, and set it to be method="post" and enctype="multipart/form-data"
    Reading the input stream at the other end - thats harder - which is why they wrote a library for it. </p>
    why i gave the restriction is that, i have a question that <code>'can't we implement the same upload'</code>
    I was with the view that the same can be implemented by our own code right?

  • Cache file(pdf) in user's browser using Servlet -Cookie, or Session

    How can I save a file (pdf) in the cache of a browser (IE 6) in a user's computer? I am using Servlet and Tomcat 4.1.24. PDF file is sitting in server (remote computer) under a URL space.
    The idea is to NOT to download the pdf file on user's computer (from the remote server) if the user has a cached copy of the pdf file and pdf file in the server is the same as the pdf file in the browser. If cached pdf is different from pdf in browser, or, if the user does not have that pdf file in cache, then download pdf file from the server.
    Can I come up with a way to use Cookie class? Cookie class does not have an API which will let me save a file in it. I could have saved the pdf file in the Cookie with 999999999 setMaxAge. Is storing that pdf file in session the only choice? I do not see session serving my purpose - session should not be valid for a longgg duration e.g. week or month.
    Also, how would I create a file whne I am given a URL to that file.
    URL fileInServer = new URL("http://www.myDomain.com/myWebApp/PDF/my.pdf);
    URLConnection conn = fileInServer.openConnection();
    Does getContent() help and what are the steps after that?
    Any help with the source code will be appreciated.
    Thanks,
    Sam
    [email protected]

    I am NOT creating this PDF file on the fly. This pdf file is sitting in the server (remote machine) under URL e.g. http://10.10.10.xxx:8081/myApp/PDF/my.pdf
    I need to check if this pdf file is in the cache in user's computer (differnt machine than the server) and if the cached pdf is the same as the pdf in the server. If that file is not in the cache, or if they are not the same, then, I need to save the pdf file from the server into user's browser cache.
    I am writing all that code in Servlet. I can save the file in session. I do NOT know how else can I cache the file, other than saving it in session. I can not think of any setHeader() which will let me save a file in user's browser cache. Headers like If-Modified-Since are of no help, as it does not let me compare file in browser cache with the file in server.
    Also, how would I create a file, given a URL to that file.
    URL fileInServer = new URL("http://www.myDomain.com/myWebApp/PDF/my.pdf");
    URLConnection conn = fileInServer.openConnection();
    Do I use getContent()? What are the steps after that?
    Thanks,
    Sam
    [email protected]

  • Read file in servlet

    In the servlet file, I create a new object which is class A(which is not subclass of servlet).
    And class A have a method to read a txt file.
    However, no matter I put the file in what directory such as tomcat/webapps/home/WEB-INF/classes, or just in home, when the servlet file and new the object of class A, and then call the read file method. java.lang.NullPointerException occurs.
    How should I do?
    thx~~

    use the absolute path in the constructor
    of the reader you use to read the file.
    then it should work.

  • Accessing postgresql record using servlet

    Hello every body,
    I am trying to access the postgresql database using servlet. But I found the error of ClassNotFound exception: org.postgresql.Driver. One thing more I am using eclipse ide. I have used the postgresql-8.1-404.jdbc3 driver. And I have set it on class path in eclipse.
    package dbservlet.example;
    import java.io.*;
    import java.sql.*;
    import java.text.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class DbServletExample1 extends HttpServlet{
         public String getServletInfo() {
              return "Servlet connects to PostgreSQL database and displays result of a SELECT";
         private Connection dbcon; // Connection for scope of DbServletExample1
         public void init(ServletConfig config) throws ServletException { // "init" sets up a database connection
              String loginUser = "ali";
              String loginPasswd = "ali";
              String loginUrl = "jdbc:postgresql://127.0.0.1:5432/ali"; // Load the PostgreSQL driver
              try{
                   Class.forName("org.postgresql.Driver");
                   dbcon = DriverManager.getConnection(loginUrl, loginUser, loginPasswd);
              catch (ClassNotFoundException ex){
                   System.err.println("ClassNotFoundException: " + ex.getMessage());
                   throw new ServletException("Class not found Error");
              catch (SQLException ex){
                   System.err.println("SQLException: " + ex.getMessage());
         // Use http GET
         public void doGet(HttpServletRequest request, HttpServletResponse response)
                             throws IOException, ServletException {
              response.setContentType("text/html"); // Response mime type
              PrintWriter out = response.getWriter(); // Output stream to STDOUT
         out.println("<HTML><Head><Title>Db Servelt Example</Title></Head>");
         out.println("<Body><H1>Example of Servlet with Postgres SQL</H1>");
         try {                // Declare our statement               
              Statement statement = dbcon.createStatement();
              String query = "SELECT empid, name, dept, "; // Perform the query
              query += " jobtitle ";
              query += "FROM employee ";
              ResultSet rs = statement.executeQuery(query);
              out.println("<table border>");
              while (rs.next()) {      // Iterate through each row of rs
                   String m_id = rs.getString("empid");
                   String m_name = rs.getString("name");
                   String m_dept = rs.getString("dept");
                   String m_jobtitle = rs.getString("jobtitle");
                   out.println("<tr>" +
                                       "<td>" + m_id + "</td>" +
                                       "<td>" + m_name + "</td>" +
                                       "<td>" + m_dept +"</td>" +
                                       "<td>" + m_jobtitle + "</td>" +
                                  "</tr>");
              out.println("</table></body></html>");
              statement.close();
         catch(Exception ex){
              out.println("<HTML>" +
                             "<Head><Title>" +
                             "Bedrock: Error" +
                             "</Title></Head>\n<Body>" +
                             "<P>SQL error in doGet: " +
                             ex.getMessage() + "</P></Body></HTML>");
              return;
         out.close();
    and web.xml file is
    <web-app>
              <database>
                   <driver>
                   <type>org.postgresql.Driver</type>
              <url>jdbc:postgresql://127.0.0.1:5432/ali</url>
              <user>ali</user>
              <password>ali</password>
                   </driver>
              </database>
              <servlet>
              <servlet-name>DbServletExample1</servlet-name>
              <servlet-class>dbservlet.example.DbServletExample1</servlet-class>
              </servlet>
              <servlet-mapping>
              <servlet-name>DbServletExample1</servlet-name>
              <url-pattern>/db11</url-pattern>
              </servlet-mapping>
    </web-app>
    Thanks in advance

    That web.xml doesn't look right to me.
    what's that <database> tag? I would only expect to see a <resource-ref> in the web.xml.
    I would not touch the server.xml. Create a context.xml and put it in your META-INF directory. That should look like this:
    <?xml version="1.0" encoding="UTF-8"?>
    <Context path="/your-path" reloadable="true" crossContext="true">
        <Resource name="jdbc/your-jndi"
                  auth="Container"
                  type="javax.sql.DataSource"
                  username="your-username"
                  password="your-password"
                  driverClassName="your-driver-class"
                  url="your-url"
                  maxActive="10"
                  maxWait="60000"
                  removeAbandoned="true"
                  removeAbandonedTimeout="60000"/>
    </Context>%

  • How to fetch data from DataBase using Servlet ?

    Hi all,
    Till now, i was just sending values from web page and receive the data in excel format using servlets.
    But, now, i want to fetch data from data base. I will be giving inputs in the web page(for the query)....ON click of submit button,
    Servlet should be called.
    Depending on the input, query has to be executed, and response should be sent to the user.
    How to do it?
    Code
    import java.text.*;
    import java.sql.*;
    import java.util.*;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.OutputStream;
    /** Simple servlet that reads three parameters from the html
    form
    public class Fetchdata extends HttpServlet
              String query=new String();
              String uid="ashvini";
              String pwd="******";
              try
                   Connection con=null;
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");     
                   String url = "jdbc:odbc:Testing";     
                   con = DriverManager.getConnection(url, uid, pwd);
                   Statement s = con.createStatement();
                   query = "select * from gowri.msllst1";
                   ResultSet rs = s.executeQuery(query);
              public void doGet(HttpServletRequest request,HttpServletResponse response)
              throws ServletException, IOException
                        response.setContentType("application/vnd.ms-excel");
                        ServletOutputStream out=response.getOutputStream();
                        out.println("<HTML>" +"<BODY BGCOLOR=\"#FDF5E6\">\n" +
                        "<H1 ALIGN=CENTER>" + title + "</H1>\n" +
                        "<table>" +" <th>ITEM Code</th>");
                        while(rs.next())
                        out.println("<tr><td>" rs.getString(1).trim()"</tr></td>");
                        }//end of while
                        out.println("</table></BODY></HTML>");
                   }//end of doGet method
         }catch(Exception e)
                        System.out.println(e);
    It is giving error message as:
    C:\Program Files\Apache Tomcat 4.0\webapps\general\srvlt>javac Fetchdata.java
    Fetchdata.java:17: illegal start of type
    try
    ^
    Fetchdata.java:48: <identifier> expected
    ^
    2 errors
    Is this format is correct? am i placing this doGet method at the right place? is my program's logic is correct?
    Please help me?
    Regards
    AShvini

    There is some mistakes in ur code.....how can try catch exists outside a function???
    make use of try catch isde ur doGet method and put
    Connection con=null;
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String url = "jdbc:odbc:Testing";
    con = DriverManager.getConnection(url, uid, pwd);
    Statement s = con.createStatement();
    query = "select * from gowri.msllst1";
    ResultSet rs = s.executeQuery(query);
    isdie doGet method, for the time being,
    i think u get me..
    regards
    shanu

  • Sort function in web report using servlet

    Dear all
    Please help me this out. I'm doing an online report using servlet. When the report is displayed as a table on the web, is there a way to have a sort function-when you click on the tabs, it will sort the data accordingly.
    If I didn't state my question clearly, please let me know.
    Thank you all for your kind help!
    Grace

    You could probably do that using Javascript, but it's beyond my competence to even suggest how. Alternatively you could make the tabs behave as buttons that send a "sort me" request to the server, which would send out new, resorted, HTML.

  • How can I use Servlets on Sun Java System WebServer 6.1

    Hi
    This is Khurram,
    I have just downloaded, and installed "Sun One Java System Web Server 6.1" on WindowsXP. This is installed and working properly on my system. But I want to use Servlet technology on this server, even I did download it just for working on servlets. Before it, I was using typical JavaWebServer2.0 for this purpose.
    Any ways.
    Can any one tell me, how can I do this on "Java System Web Server 6.1".
    Thanks
    any help will be appriciated
    regards
    Khurram

    Thanks for your such action.
    Actually I have installed it since 2 days, and have read throughly the documentation of WebServer, But Only the Link for this purpose is provided "Programmer's Guide to Web Applications", Now I have just searched for it and found only "Programmer's Guide" .PDF format. I have just read it out now, But here also provided a small refference to see "Programmer's Guide to Web Applications". Now I have just the problem that where to find it.
    Please, tell me if you have some solution to my problem
    or atleast tell me where to find the refference "Programmer's Guide to Web Applications". I tried but only found "Programmer's Guide" for Sun Web Server 6.1.
    Thanks any way to give some time.
    Khurram

  • How to get XML value using servlet?

    how to get values from a XML file using servlet ? Thank you.
    for example: how can I get the location value (aaa) from this XML file?
    abc.xml:
    <business>
    <location>aaa</location>
    </business>

    Try to use XML Parsers to do the job.
    Use DOM or SAX Parsers that are freely available.
    Some of the popular ones are xerces, DOM, SAX.

  • When to use jsp,and when to use servlet?

    I think that jsp and servlet can realize the same functions, because when run a jsp, it is transferred to a servlet program, so when to use jsp and when to use servlet?
    I am now developing the input interface for a website, I just use jsp and javabean to connect to weblogic and database, and I didn't use servlet, Is there any unseemliness?
    Thank you!

    IMHO I use servlets to control the flow between my jsp's based on a number of factors in a webapp. For instance, user authorization. If a user has the authorization to conduct various administrative functions on an application (like change user rights, reset passwords etc) they will have access to specific buttons or links on some screens that others will not. I use servlets to establish what access rights a user has and direct them to the appropriate pages. I also use servlets to test data validity on form input screens. I know that I can also do this with JavaScript but that can be disabled by the client and in order to prevent that I also double check the form input from a servlet. All my jsp's do is display the results of a business process (which is held in a JavaBean or EJB) and the servlets act as the controllers for the application, connecting to multiple databases, verifying application state, flow control etc. I try to keep the jsp as simple as possible as some of them are maintained by html developers who lack the necessary experience to write java code. I hope this helps.

  • Sending thumbnail of images to client on request using servlet/jsp

    hi
    can anybody tell me how can we send thumbnail of more than one image to client using servlet or jsp just the way we thumbnail of images in google

    Then create a servlet which uses Java 2D API to rezise the image and writes it to the outputstream of the response. Call that servlet in the <img> tag along with an unique request parameter identifying the image.

Maybe you are looking for

  • Month, QTD, YTD in prompts - Financial Reporting Studio

    Hi All, We developed a report (source: Essbase) using Financial Reporting Studio. We used a prompt for Period Dimension and used all the months in the choices list. We have a new requirement to pull QTD and YTD of the months to the prompt list. We ha

  • AuthorIT and Structured FrameMaker?

    Just wondering if anyone has experience with bringing AuthorIT structured documentation into FrameMaker. I know it's a long shot, but....

  • HT4113 Can not turn off passcode lock

    I can not turn off passcode lock. I see it and it is grayed out. I can change the password, etc. but I can not turn it off  I plugged the phone into a friends computer a few days ago to charge it. Does that have something to do with it?

  • SAPScript Fonts Problem

    Hi all, User claimed that simplified chinese characters in Customer Statement forms (SAPscript ), are thin in font, and light in color, if compare to some English characters and Numeric characters on the same page, after printed out (hardcopy). Howev

  • Play Flash Movie ONE TIME on Webpage...

    I've been searching for a way to add a 'Cookie' to my Flash Video file so that it will only Play One Time... on my landing page. After the visitor goes to another page and returns to my homepage I do NOT want the Video to Play again. My Video is a Fl