Creating a text file in JSP..

I just started learning JSP and I still have lots to learn. Anyway, I just need some help. Here is my problem:

How can I create a text file when a button is clicked? Is there something like an event-handler in JSP? Also, how can I access what is inside the <td> and the </td> and put it inside the file?

[328 byte] By [Jeriela] at [2007-11-26 18:33:03]
# 1
Will someone please help me? Please.. I beg you..
Jeriela at 2007-7-9 6:07:08 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2
Run some server code... create a WriterMeTitus
Me_Titusa at 2007-7-9 6:07:08 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 3

Your question is a little bit unclear.

You can take the content of the <td> and submit it using Javascript

If you want to generate a file on the server then simple use a Writer as stated above.

If you want to generate the file as a response you can do it in the JSP. You can generate text files as well as HTML.

beradriana at 2007-7-9 6:07:08 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 4

Ok, let me explain further. There is this drop-down box containing different genre of music and a combo box which contains different title of songs. Every time I select a different genre, the options in the combo box must also change. Also, there is this button which transfers the selected songs in the combo box to a table. That means then that I can transfer different songs from different genre into the table. Also, there is another button which transfers what is in the table back into their respective combo boxes.

I was able to do all of that using Javascript. Now, I want to add another button which saves the contents of the table into a text file using JSP. So, how will do that?

Jeriela at 2007-7-9 6:07:08 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 5

It's a bad idea to implement this entire functionality in just a JSP file, as it leads to really complicated code.

First break your application into different layers conceptually. Then it becomes easier to implement each layer, also it cleanly separates out the code.

- Front end layer will be JSP, mostly used to display data and submit form data

- Controller layer, you can create a Servlet to do some routing between JSPs. It basically decides which JSP to show - but for now since you are learning JSPs you can leave this out.

- Middle layer, use JavaBeans to store data and also to communicate from Middle layer to your JSP.

- Database layer contains all the code that interacts with the database.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

How are you getting the values for the dropdown and combo box? I'm guessing you are getting those values from the database?

Assuming that you are getting them from the database, first get the primary key of the song,

Upon knowing the primary key of the song you'll be able to retrieve all the other fields corresponding to that song.

You can then populate a JavaBean with all the details of the song.

Then call a Servlet, which calls another class which saves the song to a text file using Java I/O API

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

appy77a at 2007-7-9 6:07:09 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 6

Ok.. That sounds so complicated. *sob*

I don't get the values for the drop-down and combo box from a database. I don't have any idea of them. I just have this array of song titles for every genre of music in my Javascript.

I have thought of something. What if I create a hidden combo box containing the data in the table? I mean, as I dynamically create a table why don't I create this hidden combo box? Then I'll submit this all-selected hidden combo box to a JSP file. Is this possible?

Jeriela at 2007-7-9 6:07:09 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 7

[nobr]It sounds complicated because you are new to the concepts, just like you spent time learning Javascript similarly one would have to spend time in understanding the basic concepts before approaching to implement a fairly *complex* solution.

I'll show a small example of how this could be written with

JSPs, JSTL 1.1, Java Servlets, Java File Input/Output and web.xml

Although it is strongly discouraged, one could write this entire code in just one JSP, but like I mentioned earlier the code will be very complicated in just one JSP - it would be the equivalent of having the kitchen, bedroom, bathroom all in just one room - very messy.

The part where you mentioned - if the user selects a genre, then the song titles get populated, you can implement that with Javascript alone.

What I'm illustrating is how you can take the value selected in the combo box , and submit the form. When the form gets submitted the value of the selected genre is written to a file.

You will find this code complicated because like I mentioned earlier you are new to the concepts. But it is the right way to implement a solution.

I encourage you to try out this code and understand what it does (if you have the time ).

index.jsp - simplified - shows the combox in a form with just Genres

The Genres are read from a JavaBean

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>

<head><title></title></head>

<body>

<%-- See the syntax details for jsp:useBean here : http://java.sun.com/products/jsp/syntax/2.0/syntaxref20.html --%>

<jsp:useBean id="createGenreBean" class="test41.factory.CreateGenreBean"/>

<%-- The jsp:useBean allows one to create an instance of the bean inside the JSP, and access the bean's properties --%>

<%--

In the following code , the c:forEach is a JSTL 1.1 tag. In order to use it one must declare the above taglib

and install and configure JSTL1.1

here's the full JSTL 1.1 API :

http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html

The forEach loop is iterating over the list of GenreBeans obtained from the createGenreBean JavaBean

--%>

<form action="/ProcessThisFormServlet" method="post">

<select multiple="multiple" size="10" name="genreId">

<c:forEach var="currentLoopItem" items="${createGenreBean.genreBeanList}">

<option value="${currentLoopItem.genreId}">${currentLoopItem.genreName}</option>

</c:forEach>

</select>

<br/><br/>

<input type="submit" name="submit" value="submit"/>

</form>

</body>

</html>

--

showResults.jsp - shows the results of writing the combo box input selected by the user and writing the selection to a text file.

- the user selects the genreId -

--

<%@ page import="test41.constant.Constant"%>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<head><title>Was the File written successfully?</title></head>

<body>

Was the file written successfully: ${param.isFileWrittenSuccessfully}

<br/><br/>

What was written to the file: ${param.genreId}

<br/><br/>

Where was the file written? <%=Constant.filePath%><%=Constant.nameOfOutputFile%>

</body>

</html>

GenreBean.java is a JavaBean that represents one Genre

--

package test41.databeans;

import java.io.Serializable;

/**

* This is a JavaBean and conforms to the JavaBean notation and standard.

* Read JavaBeans tutorial for more details on JavaBeans.

*/

public class GenreBean implements Serializable {

private int genreId;

private String genreName;

public GenreBean() {

}

public int getGenreId() {

return genreId;

}

public void setGenreId(int genreId) {

this.genreId = genreId;

}

public String getGenreName() {

return genreName;

}

public void setGenreName(String genreName) {

this.genreName = genreName;

}

}

Constant - defines all the Strings used in the app in just one place

--

package test41.constant;

public class Constant {

public static final String filePath = "C://";

public static final String nameOfOutputFile = "OutputText.txt";

}

CreateGenreBean , creates a list of GenreBeans

It is defined as a JavaBean also, so that it can be accessed

inside a JSP file.

package test41.factory;

import test41.databeans.GenreBean;

import java.io.Serializable;

import java.util.ArrayList;

/**

* This is also a JavaBean, it creates an arraylist of GenreBeans and returns the results to the calling program.

* We use the results of this CreateGenreBean inside the JSP file.

*/

public class CreateGenreBean implements Serializable {

ArrayList<GenreBean> genreBeanList;

public CreateGenreBean() {

}

/**

* Gets all GenreBeans

* @return List of Genre Beans

*/

public ArrayList<GenreBean> getGenreBeanList() {

this.genreBeanList = new ArrayList<GenreBean>();

/* Either create the ArrayList of GenreBeans by hard-coding (for testing), from the database or a text file*/

GenreBean genreBean = new GenreBean();

genreBean.setGenreId(1);

genreBean.setGenreName("Jazz");

genreBeanList.add(genreBean);

genreBean = new GenreBean();

genreBean.setGenreId(2);

genreBean.setGenreName("Electronic music");

genreBeanList.add(genreBean);

genreBean = new GenreBean();

genreBean.setGenreId(3);

genreBean.setGenreName("Hip-Hop/Rap");

genreBeanList.add(genreBean);

/* Continue adding more GenreBeans ... */

/*Instead of hardcoding them here, it is a good practice to read them from a text file using Java File I/O API, even better

read them from the database using JDBC.*/

return this.genreBeanList;

}

public void setGenreBeanList(ArrayList<GenreBean> genreBeanList) {

this.genreBeanList = genreBeanList;

}

}

-

DiskWriter writes to a file , it is called from the Servlet

package test41.io;

import test41.constant.Constant;

import java.io.IOException;

import java.io.BufferedWriter;

import java.io.FileWriter;

public class DiskWriter {

/**

* This method writes whatever input text is given to it into a file.

* Read the Java File I/O tutorial for more detials.

* @return true if file was written successfully.

*/

public boolean writeToAFile(String inputString) {

boolean isFileWrittenSuccessfully;

try {

/* Create the output text file if it does not already exist and then write to it*/

BufferedWriter out = new BufferedWriter(new FileWriter(Constant.filePath + Constant.nameOfOutputFile, true));

out.write(inputString);

out.newLine(); /*Write a new line after writing the above line, so that the next time, another text falls on a new line rather than on the same line.*/

out.close();

isFileWrittenSuccessfully = true;

} catch (IOException e) {

/* It's a good practice to use Log4J to log an error, rather than print stack trace to the console. */

isFileWrittenSuccessfully = false;

e.printStackTrace();

}

return isFileWrittenSuccessfully;

}

}

The first JSP calls this Servlet, the Servlet calls DiskWriter and

writes to the file and then the Servlet calls the second JSP

package test41.servlet;

import test41.io.DiskWriter;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import java.io.IOException;

/**

* This Servlet gets called when you submit the form, since the form's action has /ProcessThisFormServlet.

* But one must declare this servlet in your applications web.xml located under WEB-INF , and give

* the URL patterns mapping. Your webserver (e.g Tomcat) looks at the url /ProcessThisFormServlet

* then reads web.xml and figures out the name and location of this servlet and calls

* either doPost or doGet depending on whether you submitted the form via POST or GET

*/

public class ProcessThisFormServlet extends HttpServlet {

/**

* This handles the HTTP Request, if the form was submitted via action="GET"

* @param request

* @param response

*/

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

doPost(request,response);

}

/**

* * This handles the HTTP Request, if the form was submitted via action="POST"

* @param request

* @param response

*/

public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

String textToBeWritten = request.getParameter("genreId");

/*In this method - write the core logic that writes a file to disk. Write the ID of the selected Genre*/

DiskWriter diskWriter = new DiskWriter();

boolean isFileWrittenSuccessfully = diskWriter.writeToAFile(textToBeWritten);

request.setAttribute("isFileWrittenSuccessfully", isFileWrittenSuccessfully);

RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/p/test41/showResults.jsp");

requestDispatcher.forward(request,response);

}

}

Declare the Servlet in your application's web.xml

located under /WEB-INF/web.xml , and define

the URL mapping for the servlet

<servlet>

<servlet-name>ProcessThisFormServlet</servlet-name>

<servlet-class>test41.servlet.ProcessThisFormServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>ProcessThisFormServlet</servlet-name>

<url-pattern>/ProcessThisFormServlet</url-pattern>

</servlet-mapping>

Assuming that you have set up JDK 1.5 or higher , Tomcat 5.5 or an equivalent web server, JSTL 1.1 , this example should work.

The core concept being this application is the processing of request and response. The user makes a request - the first JSP processes it by showing itself - The user makes another request by submitting the form - the Servlet handles the request - then the servlet forwards the request to another JSP which then handles the request.[/nobr]

appy77a at 2007-7-9 6:07:09 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...