# 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]