Lab2.
Zad.1.
Zastosowanie komponentu File Upload. Komponent ten pozwala użytkownikowi aplikacji internetowej zlokalizować pliki w systemie i zapisać pliki na serwerze. Jest on przeznaczony do gromadzenia plików tekstowych, plików graficznych i innych.
Zawartość ładowanego pliku jest ładowana razem z informacją o pliku: nazwą pliku, rozmiarem pliku oraz typem MIME (text/plan lub image/jpeg).
Server przetrzymuje ładowany plik w pamięci do rozmiaru 4096 jako plik tymczasowy. Można ten rozmiar zmienić modyfikując parametr sizeThreshold w pliku web.xml za pomocą edytora XML.
Przypadki ładowania pliku:
Wskazanie miejsca do przechowania pliku (zad.1)
Utworzenie właściwości UploadedFile w ”backing bean” i przypisanie jej do wartości zwracanej przez komponent np. przy opuszczaniu strony jako obsługa typu action przycisku.
Zapisanie pliku do bazy danych.
Domyślnie, komponent File Upload pozwala pobierać pliki do rozmiaru 1 MB. Ta wielkość może ulec zmianie przez ustawieniu filtru w edytorze XML pliku web.xml dokonując zmiany wartości parametru maxSize.
1. Wybierz opcję File/New Project. Wybierz kategorię projektu Web, a rodzaj projektu Web Application
2. Kliknij na Next
3. Podaj nazwę projektu (Project name), wybierz katalog (Project Location) 4. Wybierz domyślny serwer aplikacji GlassFish V2 z listy Server oraz
wersję Javy Enterprise (Java 5 EE Version) – wybierz domyślne wartości.
5. Kliknij na Next, wybierz Visual Web JavaServer Faces i naciśnij Finish.
6. Okno projektu (Projects) zawiera układ plików typu BluePrints. Plik Page1.jsp jest stroną startową napisaną w języku JSP i znajduje się w
„podkatalogu” Web-Pages.
7. Okno Files zawiera układ fizyczny plików. Plik Page1.jsp oraz Page1.java
stanowią całość- plik Page1.java obsługuje główną stronę jsp.
8. Zaprojektuj stronę Page1 korzystając z Palette Basic
8.1. Przeciągnij kontrolkę Label i File Upload. W oknach Properties obu kontrolek nazwy ich są standardowe:label1 i fileUpload1. Nazwy te można zmieniać. Na komponencie Label napisz np. Załaduj plik graficzny
8.2. Przeciągnij dwa przyciski Button i napisz na nich: Załaduj plik graficzny (na pierwszym) oraz Załaduj plik graficzny w dedykowanym katalogu (na drugim).
8.3. Przeciągnij kontrolkę Message Group
8.4. Wstaw cztery komponenty typu Label – kolejno wpisując tekst na nich: Nazwa pliku, Typ pliku, Rozmiar pliku, URL oraz cztery komponenty typu Static Text.
8.5. Przeciągnij kontrolkę Label i File Upload. W oknach Properties obu kontrolek nazwy ich są standardowe:label6 i fileUpload2. Na kontrolce Label napisać Załaduj plik tekstowy,
8.6. Przeciągnij przycisk Button (id=button3) i napisz na nim: Załaduj plik tekstowy.
8.7. Wstaw komponent Image (id=image1) i w okienku Properties w polu url wywołaj edytor (…) i poszukaj na dysku plik graficzny w np.
w formacie JPEG i przypisz go do pola url.
8.8. Wstaw komponent Tekst Area (textArea1) oraz komponent Label
(label7). Na komponencie Label napisz tekst Zawartość pliku
tekstowego. W okienku Properties komponentu textArea1
właściwość rows ustawić na 10.
8.9. Wybierz z wyskakującego menu po kliknięciu prawego klawisza myszy opcję Preview in Browser, aby zobaczyć widok wyjściowy tworzonej strony.
9. Uzupełnij kod aplikacji w trybie Java strony Page1 (klasa Page1 dziedziczy od klasy AbstractPageBean)
9.1. Dwa atrybuty klasy:
private String realImageFilePath; //ścieżka do pliku na serwerze private static final String IMAGE_URL = "/resources/image-file";
// ścieżka logiczna do pliku w aplikacji internetowej
9.2. metoda init() - po wpisaniu kodu (tekst wytłuszczony) nacisnąć klawisze Alt-Shift-F (w celu sformatowania tekstu) oraz Ctrl-Shift-I (w celu importu pakietów)
public void init() { super.init();
// Perform application initialization that must complete // *before* managed components are initialized // TODO - add your own initialiation code here // Managed Component Initialization
// Perform application initialization that must complete // *after* managed components are initialized // TODO - add your own initialization code here ServletContext theApplicationsServletContext =
(ServletContext) this.getExternalContext().getContext();
this.realImageFilePath = theApplicationsServletContext.getRealPath(IMAGE_URL);
}
9.3. metoda prerender()
public void prerender()
{ String uploadedFileName = (String)this.staticText1.getValue();
if ( uploadedFileName != null ) { image1.setUrl(IMAGE_URL); }
// wstawienie wprowadzonego pliku do komponentu Image }
9.4. metoda obsługująca akcję przycisku Załaduj plik graficzny (należy kliknąć na ten przycisk – strona Page1 będzie w trybie pliku Java)
public String button1_action() {
// TODO: Process the action. Return value is a navigation // case name where null will return to the same page.
UploadedFile uploadedFile = fileUpload1.getUploadedFile();
String uploadedFileName = uploadedFile.getOriginalName();
// Some browsers return complete path name, some don't // Make sure we only have the file name
// First, try forward slash
int index = uploadedFileName.lastIndexOf('/');
String justFileName;
if ( index >= 0) {
justFileName = uploadedFileName.substring( index + 1 );
} else {
// Try backslash
index = uploadedFileName.lastIndexOf('\\');
if (index >= 0) {
justFileName = uploadedFileName.substring( index + 1 );
} else {
// No forward or back slashes
justFileName = uploadedFileName;
} }
this.staticText1.setValue(justFileName);
Long uploadedFileSize = new Long(uploadedFile.getSize());
this.staticText3.setValue(uploadedFileSize);
String uploadedFileType = uploadedFile.getContentType();
this.staticText2.setValue(uploadedFileType);
this.staticText4.setValue(this.realImageFilePath);
if (
uploadedFileType.equals("image/jpeg") || uploadedFileType.equals("image/pjpeg") || uploadedFileType.equals("image/gif") || uploadedFileType.equals("image/png") || uploadedFileType.equals("image/x-png")) { try {
File file = new File(this.realImageFilePath);
uploadedFile.write(file);
} catch (Exception ex) {
error("Cannot upload file: " + justFileName); //komunikat wyświetlany w Message Group }
} else { //komunikat wyświetlany w Message Group
error("You must upload a JPEG, PJPEG, GIF, PNG, or X-PNG file.");
new File(this.realImageFilePath).delete();
}
return null;
}
Metoda wyświetla informację dodatkową o załadowanym pliku oraz
zapamiętuje plik w zmiennej pliku this.realImageFilePath. Należy nacisnąć
klawisze Alt-Shift-F (w celu sformatowania tekstu) oraz Ctrl-Shift-I (w celu
importu pakietów)
9.5. Metoda obsługująca klawisz Załaduj plik graficzny w dedykowanym katalogu (zapis w istniejącym katalogu) -(należy kliknąć na ten przycisk – strona Page1 będzie w trybie pliku Java)
public String button2_action() {
// TODO: Process the action. Return value is a navigation // case name where null will return to the same page.
UploadedFile uploadedFile = fileUpload1.getUploadedFile();
String uploadedFileName = uploadedFile.getOriginalName();
// Some browsers return complete path name, some don't // Make sure we only have the file name
// First, try forward slash
int index = uploadedFileName.lastIndexOf('/');
String justFileName;
if ( index >= 0) {
justFileName = uploadedFileName.substring( index + 1 );
} else {
// Try backslash
index = uploadedFileName.lastIndexOf('\\');
if (index >= 0) {
justFileName = uploadedFileName.substring( index + 1 );
} else {
// No forward or back slashes
justFileName = uploadedFileName;
} }
this.staticText1.setValue(justFileName);
Long uploadedFileSize = new Long(uploadedFile.getSize());
this.staticText3.setValue(uploadedFileSize);
String uploadedFileType = uploadedFile.getContentType();
this.staticText2.setValue(uploadedFileType);
this.staticText4.setValue(this.realImageFilePath);
try {
File file = new File("C:/upload/images" + File.separatorChar + justFileName);
//w znanym miejscu na serwerze – katalog musi istnieć uploadedFile.write(file);
}
catch (Exception ex) {
error("Cannot upload file: " + staticText1);} //komunikat wyświetlany w Message Group return null;
}
9.6. Metoda obsługująca klawisz Załaduj plik tekstowy -(należy kliknąć na ten przycisk – strona Page1 będzie w trybie pliku Java)
public String button3_action() {
// TODO: Process the action. Return value is a navigation // case name where null will return to the same page.
UploadedFile uploadedFile = (UploadedFile) fileUpload2.getUploadedFile();
//komunikat wyświetlany w Message Group info("Uploaded file originally named ' " + uploadedFile.getOriginalName() + " ' of size ' " + uploadedFile.getSize() + " ' ");
textArea1.setText(uploadedFile.getAsString());
return null;
}
9.7. Uruchom aplikację (Kliknij prawym klawiszem myszy w oknie Project
na nazwę projektu, w ukazanym oknie uruchom kolejno Build Project,
Deploy Project, Run Project) i uruchom poszczególne funkcje aplikacji.
Table 1: Input Components
Component Description Palette
Section
Text Field An input field for a single line of text. Basic
Text Area An input field for multiple lines of text. Basic
Password Field An input field that echoes the input characters with a replacement character
to mask the input. Basic
Calendar An input field with a pop-up calendar that allows the user to select a date. Basic Drop Down
List A drop-down menu, also referred to as a combo box. Basic
Listbox A list from which the user can select either one item or multiple items,
depending on how the component is configured. Basic
Checkbox A single-character box that the user can either select (check) or clear. Basic Radio Button A single radio button that the user can select (check). Basic Add Remove
List Two lists (one for available options, one for selected options) with buttons to
move the options between the lists, and to order the selected options. Composite File Upload A component with a text input field and a Browse button that displays a file
chooser for specifying a file to upload. The application uploads the specified file when the user submits the page.
Basic
Table 2: Display Components
Component Description Palette
Section
Static Text Field for displaying text. Basic
Label Text field that can be associated with an input field and for which you can
specify a weak, medium, or strong font style. Basic
Image Inline image. Basic
Message Text field that is linked to a specific component for displaying validation
errors and other messages about that component. Basic
Message
Group Text field for displaying runtime error messages, program generated error messages, and, optionally, validation errors and other messages about components that are on the page.
Basic
Alert Displays an icon and informational text such as a warning, an error, or the
successful completion of some event. Composite
Page Alert Similar to an Alert component, but is intended for displaying the icon and
information on a separate page. Layout
Table 3: Grouping Components
Component Description Palette
Section Checkbox Group Displays two or more check boxes in a grid layout. Basic Radio Button Group Displays two or more radio buttons in a grid layout and
ensures that only one button can be selected at a time. Basic Table, Table Row Group, and
Table Column Displays data from a composite data type such as a
database table or an array. Basic
Tree and Tree Node Renders an expandable list in a tree structure. Basic
Tab Set and Tab Displays different layouts on the same page. Also can be
used as a navigational tool. Layout
Grid Panel Organizes the components within a layout of rows and
columns. Layout
Group Panel Groups a set of components in flow layout mode. Layout Layout Panel Use to group a set of components in flow layout mode or
grid layout mode. Layout
Property Sheet, Property Sheet
Section, and Property Lays out a single column of labeled components quickly,
and divides the components into sections. Layout Breadcrumbs Lays out a series of link components separated by right
angle brackets (>). Composite
Page Fragment Box Groups components that you want to consistently display
on two or more pages. Layout
Table 4: Action Components
Component Description Palette
Section
Button Button that submits the associated form. Basic
Hyperlink Text field that submits a URL or submits a form. Basic
Image Hyperlink Image that submits a URL or submits a form. Basic Tree Node Subcomponent of a Tree or Tree Node. A leaf tree node can optionally
submit a URL or submit a form. Basic
Tab Subcomponent of a Tab Set or a Tab. A tab can optionally submit a URL or
submit a form. Composite