Формы в JSP - добавление даты рядом с каждым постом - PullRequest
0 голосов
/ 15 февраля 2012
<html>    
<head>        
<title>JSP Form</title>        
<style>            
</style>    
</head>    
<body>        

<form action="TestFileHandling.jsp" method="post">            
<fieldset>                
<legend>User Information</legend>                

<label for="question">Question</label> 
<input type="text" name="question" /> <br/>   

<input type="submit" value="submit"> 
</fieldset>        
</form>    

</body>
</html>

Выше приведена простая форма, которая позволяет пользователю ввести вопрос перед отправкой.

<%@page import="myPackage.FileReaderWriter"%>
<%@page import="java.util.Vector"%>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01                   
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>


 <%
Vector<String[]> v = new Vector<String[]>();
String[] str1 = {request.getParameter("question")};
v.addElement(str1);


FileReaderWriter.saveVectorToFile(v, "MyTestFile.txt");
%>



<%

Vector<String[]> vec =          FileReaderWriter.readFileToVector     ("MyTestFile.txt");
for (int i = 0; i < vec.size(); i++) 
{
    out.print("|");
    for (int j = 0; j < vec.elementAt(i).length; j++) 
    {
        out.print(vec.elementAt(i)[j] + "|");
    }
%>
<br>
<%
}
%>

</body>
</html>

Эта часть берет введенный вопрос и сохраняет его в текстовом файле, а затем открывает файл.чтобы отобразить все, что находится внутри.

Все это делается с помощью следующего Java-кода:

package myPackage;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Vector;

public class FileReaderWriter {
public static void saveVectorToFile(Vector<String[]> v, String sFileName)
{
    try
    {
        // Create a new file writer
        FileWriter writer = new FileWriter(sFileName, true);

        // Loop through all the elements of the vector
        for (int i = 0; i < v.size(); i++)
        {
            // Capture the index of the last item of each array
            int lastIndex = v.elementAt(i).length - 1;
            // Loop through all the items of the array, except 
            // the last one.
            for (int j = 0; j < lastIndex; j++)
            {
                // Append the item to the file.
                writer.append(v.elementAt(i)[j]);
                // Append a comma after each item.
                writer.append(',');
            }
            // Append the last item.
            writer.append(v.elementAt(i)[lastIndex]);
            // Append a new line character to the end of the line
            // (i.e. Start new line)
            writer.append('\n');
        }
        // Save and close the file
        writer.flush();
        writer.close();
    }
    // Catch the exception if an Input/Output error occurs
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

public static Vector<String[]> readFileToVector(String sFileName)
{
    // Initialise the BufferedReader
    BufferedReader br = null;

    // Create a new Vector. The elements of this Vector are String arrays.
    Vector<String[]> v = new Vector<String[]>();
    try
    {
        // Try to read the file into the buffer
        br = new BufferedReader(new FileReader(sFileName));
        // Initialise a String to save the read line.
        String line = null;

        // Loop to read all the lines
        while ((line = br.readLine()) != null)
        {
            // Convert the each line into an array of Strings using 
            // comma as a separator
            String[] values = line.split(",");

            // Add the String array into the Vector
            v.addElement(values);
        }
    }
    // Catch the exception if the file does not exist
    catch (FileNotFoundException ex)
    {
        ex.printStackTrace();
    }
    // Catch the exception if an Input/Output error occurs
    catch (IOException ex)
    {
        ex.printStackTrace();
    }
    // Close the buffer handler
    finally
    {
        try
        {
            if (br != null)
                br.close();
        } catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }
    // return the Vector
    return v;
}


}

Меня действительно смущает то, как мне отредактировать это так, чтобы после публикации вопросав форме дата и время публикации автоматически добавляются в начало каждого вопроса.

Для этого я знаю, что сначала мне нужно будет импортировать утилиту даты в Java, а затем добавить что-то подобноемоя страница формы:

<%!Date startTime = new Date();%>

Как только я доберусь до этой части, я подумаю, как мне передать информацию из startTime в мой файл Java, который обрабатывает добавление вектора?

Что-то еще, что я уже пробовал, просто помещало Date startTime = new Date(); в java-файл, а затем использовал простой код, такой как writer.append(startTime);, чтобы добавить дату внутри startTimeОн задал вопрос, но это не сработало и просто выдало ошибку.В конце концов это привело меня к мысли, что лучший способ сделать это - просто использовать скрипт:

<%!Date startTime = new Date();%>

Как именно я передаю информацию, хранящуюся в startTime, в свой код Java, чтобы онможно добавить внутри того же элемента вектора, в который был сохранен введенный вопрос?Спасибо за любую помощь или совет.

РЕДАКТИРОВАТЬ: кто-то может также объяснить, почему writer.append(startTime); не работает?Кажется, это должно работать совершенно нормально ... Надеюсь, понимание того, что не так, приблизит меня к пониманию этого

1 Ответ

1 голос
/ 15 февраля 2012

Просто добавьте его в String[] перед добавлением в Vector<String[]>:

String[] str1 = { startTime.toString(), request.getParameter("question") };

Если вам нужен другой формат даты, посмотрите на SimpleDateFormat.


Не связано с конкретной проблемой, возможно, вы имеете дело с десятилетним приложением, но понимаете ли вы, что этот код полон устаревших API и плохих практик?

...