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 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. Text Area An input field for multiple lines of text. Password Field An input field that echoes the input characters with a replacement character to mask the input. Calendar An input field with a pop-up calendar that allows the user to select a date. Drop Down List Listbox A drop-down menu, also referred to as a combo box. A list from which the user can select either one item or multiple items, depending on how the component is configured. Checkbox A single-character box that the user can either select (check) or clear. Radio Button A single radio button that the user can select (check). Add Remove List File Upload 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. 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. Composite Table 2: Display Components Component Description Palette Section Static Text Field for displaying text. Label Text field that can be associated with an input field and for which you can specify a weak, medium, or strong font style. Image Inline image. Message Message Group Alert Page Alert Text field that is linked to a specific component for displaying validation errors and other messages about that component. 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. Displays an icon and informational text such as a warning, an error, or the successful completion of some event. Similar to an Alert component, but is intended for displaying the icon and information on a separate page. Composite
Table 3: Grouping Components Component Description Palette Section Checkbox Group Displays two or more check boxes in a grid layout. Radio Button Group Table, Table Row Group, and Table Column Displays two or more radio buttons in a grid layout and ensures that only one button can be selected at a time. Displays data from a composite data type such as a database table or an array. Tree and Tree Node Renders an expandable list in a tree structure. Tab Set and Tab Grid Panel Displays different layouts on the same page. Also can be used as a navigational tool. Organizes the components within a layout of rows and columns. Group Panel Groups a set of components in flow layout mode. Panel Property Sheet, Property Sheet Section, and Property Breadcrumbs Page Fragment Box Use to group a set of components in flow layout mode or grid layout mode. Lays out a single column of labeled components quickly, and divides the components into sections. Lays out a series of link components separated by right angle brackets (>). Groups components that you want to consistently display on two or more pages. Composite Table 4: Action Components Component Description Palette Section Button Button that submits the associated form. Hyperlink Text field that submits a URL or submits a form. Image Hyperlink Image that submits a URL or submits a form. Tree Node Tab Subcomponent of a Tree or Tree Node. A leaf tree node can optionally submit a URL or submit a form. Subcomponent of a Tab Set or a Tab. A tab can optionally submit a URL or submit a form. Composite