Jsp web application text file read and write

Hello,
I am new to the java world and jsps. I am trying to make an application which is going to get the data from a jsp page in the browser and then the entered data should be store in a txt file in the WEB-INF folder.
I am trying to get the results but nothing seems to working. I have created the jsp pages, and using two java classes. I need to clarify one most important thing that should i use a servlet to send the jsp strings to the servlets and then servlet will store them in a file specified by a path? and save the data in the text file. How can i do that? and I do not have the code for servlet but using the normal code with an addition of the file writer codes in the servlet to pass the data to the file in WEB-INF folder.

Please help me I have spent my 2 nights to sort out this problems.

Thanks


JSP {
  Form {
    textfield
    submit button
    action = your servlet
  }
}

servlet {
  read requestAttribute yourTextField
  write to file
}

Thanks for your reply here is the code , I have tried many but nothing works. I am pasting all the codes and may be you can help me in it. I have already created a text file in the WEB-INF folder with the detail.

Thanks

Jsp

<form action=“AddProductServlet” method=“post” >
<table cellspacing=“5” border=“0”>
<tr>
<td align=“right”>Product Code:</td>
<td><input type=“text” name=“code”></td>
</tr>
<tr>
<td align=“right”>Product Description:</td>
<td><input type=“text” name=“description”></td>
</tr>
Java Classes: one for Product and one for Product IO
/*

  • To change this template, choose Tools | Templates
  • and open the template in the editor.
    */

package business;

import java.text.NumberFormat;
import java.io.Serializable;

public class Product implements Serializable
{
private String code;
private String description;
private double price;

public Product()
{
    code = "";
    description = "";
    price = 0;
}

public Product(String code, String description, Double price)
{
this.code = code;
this.description = description;
this.price = price;
}

public void setCode(String code)
{
    this.code = code;
}

public String getCode()
{
    return code;
}

public void setDescription(String description)
{
    this.description = description;
}

public String getDescription()
{
    return description;
}

public void setPrice(double price)
{
    this.price = price;
}

public double getPrice()
{
    return price;
}

public String getPriceNumberFormat()
{
    NumberFormat number = NumberFormat.getNumberInstance();
    number.setMinimumFractionDigits(2);
    if (price == 0)
        return "";
    else
        return number.format(price);
}

public String getPriceCurrencyFormat()
{
    NumberFormat currency = NumberFormat.getCurrencyInstance();
    return currency.format(price);
}

}

ProductIO which read the file and direct to the txt file

package data;

import java.io.;
import java.util.
;

import business.*;

public class ProductIO
{
private static ArrayList<Product> products = null;

public static ArrayList&lt;Product&gt; getProducts(String path)
{
    products = new ArrayList&lt;Product&gt;();
    File file = new File(path);
    try
    {
        BufferedReader in =
            new BufferedReader(
            new FileReader(file));

        String line = in.readLine();
        while (line != null)
        {
            StringTokenizer t = new StringTokenizer(line, "|");
            if (t.countTokens() &gt;= 3)
            {
                String code = t.nextToken();
                String description = t.nextToken();
                String priceAsString = t.nextToken();
                double price = Double.parseDouble(priceAsString);

                Product p = new Product();
                p.setCode(code);
                p.setDescription(description);
                p.setPrice(price);

                products.add(p);
            }
            line = in.readLine();
        }
        in.close();
        return products;
    }
    catch(IOException e)
    {
        e.printStackTrace();
        return null;
    }
}

public static Product getProduct(String productCode, String path)
{
    products = getProducts(path);
    for (Product p : products)
    {
        if (productCode != null &&
            productCode.equalsIgnoreCase(p.getCode()))
        {
            return p;
        }
    }
    return null;
}

public static boolean exists(String productCode, String path)
{
    products = getProducts(path);
    for (Product p : products)
    {
        if (productCode != null &&
            productCode.equalsIgnoreCase(p.getCode()))
        {
            return true;
        }
    }
    return false;
}

private static void saveProducts(ArrayList&lt;Product&gt; products,
        String path)
{
    try
    {
        File file = new File(path);
        PrintWriter out =
            new PrintWriter(
            new FileWriter(file));

        for (Product p : products)
        {
            out.println(p.getCode() + "|"
                    + p.getDescription() + "|"
                    + p.getPrice());
        }

        out.close();
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
}

public static void insert(Product product, String path)
{
    products = getProducts(path);
    products.add(product);
    saveProducts(products, path);
}

public static void update(Product product, String path)
{
    products = getProducts(path);
    for (int i = 0; i &lt; products.size(); i++)
    {
        Product p = products.get(i);
        if (product.getCode() != null &&
            product.getCode().equalsIgnoreCase(p.getCode()))
        {
            products.set(i, product);
        }
    }
    saveProducts(products, path);
}

public static void delete(Product product, String path)
{
    products = getProducts(path);
    for (int i = 0; i &lt; products.size(); i++)
    {
        Product p = products.get(i);
        if (product != null &&
            product.getCode().equalsIgnoreCase(p.getCode()))
        {
            products.remove(i);
        }
    }
    saveProducts(products, path);
}

}

My servlet Code
package AddProduct;

import java.io.;
import javax.servlet.
;
import javax.servlet.http.*;

import business.Product;
import data.ProductIO;

public class AddProductServlet extends HttpServlet
{
/*
* @param request servlet request
* @param response servlet response
*/
protected void doPost(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// get parameters from the request
String code = request.getParameter(“code”);
String description = request.getParameter(“description”);
double price = 0.0;

            // get a relative file name
    ServletContext sc = getServletContext();
    String path = sc.getRealPath("/WEB-INF/products.txt");

    // use regular Java objects to write the data to a file
    Product product = new Product(code, description, price);
    ProductIO.insert(product, path);

    // send response to browser
    response.setContentType("text/html;charset=UTF-8");
    FileOutputStream fos = new FileOutputStream("/WEB-INF/products.txt");
    PrintWriter pw = new PrintWriter(fos);
    pw.println(""+code);
    pw.println(""+description);
    
    pw.close();
    fos.close();

    String url = "/edit_product.jsp";
    RequestDispatcher dispatcher =
            getServletContext().getRequestDispatcher(url);
    dispatcher.forward(request, response);

}

protected void doGet(
    HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException
{
    doPost(request, response);
}

}

Which part isn’t working?

I am trying to store the data from the jsp page, the user should enter the stuff in three ext boxes to update the item inventory, then this items dhould be stored in the txt file. I tried the above code when it comes on the editing page and i put the data in it , It says the path is not valid I changed the txt file path and then it shows the IO excepetion and no data entered in the txt file as well.

and apache tomcat error dispalyed .

You use the ProductIO to insert the data, then a few lines later attempt to simply write the code and description to the same file, which write attempt is failing?

so which part of the code should i remove from the servlet?
all the servlet code is making the problem, when I enter the data in jsp to so jsp should write in the file. when i run the application and enter the data and run it then just the following error HTTP Status 500 displays, the detail is below and also no any data is entering in the text file.

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

java.io.FileNotFoundException: \WEB-INF\products.txt (The system cannot find the path specified)
java.io.FileOutputStream.open(Native Method)
java.io.FileOutputStream.<init>(FileOutputStream.java:179)
java.io.FileOutputStream.<init>(FileOutputStream.java:70)
AddProduct.AddProductServlet.doPost(AddProductServlet.java:37)
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

Given:


java.io.FileNotFoundException: \\WEB-INF\\products.txt (The system cannot find the path specified)
java.io.FileOutputStream.open(Native Method)
java.io.FileOutputStream.<init>(FileOutputStream.java:179)
java.io.FileOutputStream.<init>(FileOutputStream.java:70)
[B][COLOR="Red"]AddProduct.AddProductServlet.doPost(AddProductServlet.java:37)[/COLOR][/B] <-- Your code!
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
Today 06:51

I would guess that the code on line 37 is the culprit.

I changed the above path to
String path = sc.getRealPath(“/WEB-INF/product.txt”);

    // use regular Java objects to write the data to a file
    Product product = new Product(code, description, price);
    ProductIO.insert(product, path);

    // send response to browser
    response.setContentType("text/html;charset=UTF-8");
    FileOutputStream fos = new FileOutputStream("/WEB-INF/products.txt");
    PrintWriter pw = new PrintWriter(fos);
    pw.println(""+code);
    pw.println(""+description);

and now it is showing the error in line 33 which is the insert function, I tried saveProduct but it give error as well.

And what, pray tell, is that error?

Here is that , Do you know any book or resources which have the applications on jsp, servlets tomcat step by step. Just updating the stuff from jsps to text files and delteing afterwards etc.

java.lang.NullPointerException
data.ProductIO.insert(ProductIO.java:113)
AddProduct.AddProductServlet.doPost(AddProductServlet.java:33)
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

You’re getting a null pointer, I’d guess on the products.add line.

Question: why is products null?

Answer: in getProducts, if there’s a problem, you return null.

So it’s safe to say that the path is still a problem, have you printed out the path to ensure that it is properly formed and correct?

As to a book or resource, this is an elementary file operation, which you’re doing well on. You need to work out why your path isn’t proper - there’s no book for that.

As for me, I have to leave for work - best of luck

Thanks for your time to help me sort out the problem, I tried it many time but does not seems to be working. I sont have any idea how to solve this problem. I am looking for some sample application to get an idea that how the jsp communicate to the servlets. If i see the logic in this program is clear , the jsp is posting to the servlet and servlet podts to the file. There is some thing very tiny this is wrong, thats the hardest part to find out for me .