
- •По курсу «Интернет-программирование»
- •Принципы построения интернет-приложений на Java
- •Сервлеты (Servlet) и jsp
- •Сервлеты
- •Синтаксис jsp-страницы
- •Комментарии
- •Директивы
- •Объявления
- •Выражения
- •Скриплеты
- •Объекты request, response, cookie, session
- •Загрузка файлов на сервер
- •Объект request
- •Объект response
- •Объект cookie
- •Объект session
- •Приложение 2
Объект session
Method |
Description |
Object getAttribute(String name) |
returns the object bound with the specified name in session, or null. |
Enumeration getAttributeNames() |
returns an Enumeration of String objects for the names of all the objects in session. |
long getCreationTime() |
returns the session creation time in milliseconds since midnight January 1, 1970 GMT. |
String getId() |
returns a string containing the unique identifier for this session. |
long getLastAccessedTime() |
returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT. |
int getMaxInactiveInterval() |
returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses. |
void invalidate() |
invalidates this session. |
boolean isNew() |
returns true if the session is new to the client. |
removeAttribute(String name) |
removes the object by name from the session. |
void setAttribute(String name, Object value) |
binds an object to session by name |
void setMaxInactiveInterval(int interval) |
Sets the time, in seconds, between client requests before the servlet container will invalidate this session. |
Приложение 2
Примеры чтения и записи данных в файл на Java
Листинг 2.1. Запись данных в файл.
String fileName = "Путь к файлу";
String text = "MIET";
//Создание объекта файла
File file = new File(fileName);
try {
//если файл не существует - создаем
if(!file.exists()){
file.createNewFile();
}
//создаем объект типа PrintWriter для записи текста в файл
PrintWriter outFile = new PrintWriter(file.getAbsoluteFile());
try {
//Запись текста в файл
outFile.print(text);
} finally {
//Необходимо должны закрыть файл иначе данные не запишутся
outFile.close();
}
} catch(IOException e) {
throw new RuntimeException(e);
}
Листинг 2.2. Чтение данных из файла.
String fileName = "Путь к файлу";
File file = new File(fileName);
//Объект для построения строки
StringBuilder sb = new StringBuilder();
if(file.exists()) {
try {
//Объект для чтения файла в буфер
BufferedReader in = new BufferedReader(new FileReader( file.getAbsoluteFile()));
try {
//В цикле построчно считываем файл
String s;
while ((s = in.readLine()) != null) {
sb.append(s);
sb.append("\n");
}
} finally {
in.close();
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
//Теперь в sb находится содержимое файла и его можно получить методом sb.toString()